mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
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.
This commit is contained in:
1 parent
e935263ccb
commit
eeb10e02fd
46 files changed
+5582
-104
No files matched your search
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
@@ -349,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
|
||||
@@ -997,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)
|
||||
}
|
||||
@@ -3801,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 -> {
|
||||
@@ -3893,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)
|
||||
@@ -3976,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)
|
||||
}
|
||||
@@ -5270,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
|
||||
@@ -5299,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() {
|
||||
@@ -6202,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 = {}) {
|
||||
@@ -6389,6 +6396,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
heldButtons.clear()
|
||||
hidePrimaryKeyboard()
|
||||
sessionClipboard.stop()
|
||||
sessionTextInput.stop()
|
||||
padMotion?.stop()
|
||||
cursorVisible = false
|
||||
closeSecondScreen(reset = false)
|
||||
@@ -6404,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()
|
||||
@@ -6475,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()
|
||||
@@ -6554,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)
|
||||
@@ -7285,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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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,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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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}')
|
||||
@@ -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[@]}"
|
||||
@@ -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.
|
||||
@@ -712,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
|
||||
@@ -1978,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
|
||||
@@ -2093,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
|
||||
|
||||
@@ -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
@@ -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))
|
||||
@@ -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 \
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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()
|
||||
@@ -128,7 +128,9 @@ int main(void) {
|
||||
while (write(g_input_pipe[1], &wake, sizeof(wake)) == sizeof(wake)) n++;
|
||||
assert(n > 0 && errno == EAGAIN);
|
||||
droiddeck_wayland_set_output_refresh_rate(120000);
|
||||
drain(); expect(4, 120000, 1);
|
||||
droiddeck_dispatch_pending_input();
|
||||
assert(queued() == 0);
|
||||
expect(4, 120000, 1);
|
||||
droiddeck_wayland_set_output_refresh_rate(0);
|
||||
drain(); expect(5, 60000, 1);
|
||||
droiddeck_wayland_set_output_refresh_rate(-1);
|
||||
@@ -162,7 +164,8 @@ class OutputRefreshTest(unittest.TestCase):
|
||||
self.skipTest('A host C compiler is required')
|
||||
source = SOURCE.read_text()
|
||||
functions = ('nominal_refresh_ns', 'output_send_mode', 'output_notify_mode',
|
||||
'output_resized', 'on_input_readable', 'droiddeck_wayland_output_resized',
|
||||
'output_resized', 'dispatch_input', 'on_input_readable',
|
||||
'droiddeck_dispatch_pending_input', 'droiddeck_wayland_output_resized',
|
||||
'droiddeck_wayland_set_scale_mode',
|
||||
'droiddeck_wayland_set_output_refresh_rate')
|
||||
harness = PREAMBLE + '\n'.join(extract_function(source, name) for name in functions) + CHECKS
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import tempfile
|
||||
@@ -78,6 +80,7 @@ class WindowsRuntimePreparationTest(unittest.TestCase):
|
||||
mock.patch.object(prepare, 'read_gamescope', return_value=({}, {
|
||||
'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \
|
||||
mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \
|
||||
mock.patch.object(prepare, 'prepare_ime', return_value=({}, {})), \
|
||||
mock.patch.object(prepare, 'git', return_value=b''), \
|
||||
mock.patch.object(prepare.runtime, 'record'), mock.patch.object(prepare.runtime, 'verify'), \
|
||||
mock.patch.object(prepare.vr_build, 'build', return_value=({vr_name: b'new library'}, vr_manifest)) as build:
|
||||
@@ -109,7 +112,14 @@ class WindowsRuntimePreparationTest(unittest.TestCase):
|
||||
archive.assert_not_called()
|
||||
|
||||
def test_current_helpers_are_allowed_only_when_restaged_from_source(self):
|
||||
helpers = prepare.LOCAL_SESSION_HELPERS
|
||||
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',
|
||||
}
|
||||
self.assertEqual(prepare.LOCAL_SESSION_HELPERS, helpers)
|
||||
sources = {prepare.ROOT / path: 'assets/linuxfs/' + path.split('/overlay/')[1]
|
||||
for path in helpers}
|
||||
for local_changes in (set(), helpers):
|
||||
@@ -138,7 +148,7 @@ class WindowsRuntimePreparationTest(unittest.TestCase):
|
||||
def test_other_helper_changes_still_need_an_audit(self):
|
||||
with mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()), \
|
||||
mock.patch.object(prepare, 'changed', return_value={
|
||||
'tools/linuxfs/overlay/usr/local/bin/droiddeck-session'}):
|
||||
'tools/linuxfs/overlay/usr/local/bin/droiddeck-unreviewed'}):
|
||||
with self.assertRaisesRegex(ValueError, 'Sources changed since'):
|
||||
prepare.check_sources()
|
||||
|
||||
@@ -175,5 +185,337 @@ class WindowsRuntimePreparationTest(unittest.TestCase):
|
||||
prepare.check_sources()
|
||||
|
||||
|
||||
def test_ime_sources_are_regenerated_from_pinned_rpms_in_every_stage(self):
|
||||
ime = {'tools/ime/prepare.py', 'tools/ime/packages.json', 'tools/ime/smoke.py'}
|
||||
with mock.patch.object(prepare, 'changed', side_effect=[ime, ime, ime]), \
|
||||
mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(), b'']):
|
||||
classifications = prepare.check_sources()
|
||||
self.assertEqual(set(classifications), ime)
|
||||
for action in classifications.values():
|
||||
self.assertIn('regenerated from checksum-pinned RPMs', action)
|
||||
self.assertIn('never reused from donor', action)
|
||||
|
||||
def test_unknown_ime_and_native_sources_still_fail_the_audit(self):
|
||||
for path in ('tools/ime/unreviewed.py', 'app/src/main/cpp/unreviewed.cpp'):
|
||||
with self.subTest(path=path), \
|
||||
mock.patch.object(prepare, 'git', return_value=prepare.DONOR_TREE.encode()), \
|
||||
mock.patch.object(prepare, 'changed', return_value={path}):
|
||||
with self.assertRaisesRegex(ValueError, 'Sources changed since'):
|
||||
prepare.check_sources()
|
||||
with mock.patch.object(prepare, 'changed', side_effect=[set(), set(), set()]), \
|
||||
mock.patch.object(prepare, 'git', side_effect=[prepare.DONOR_TREE.encode(),
|
||||
b'tools/ime/unreviewed.py\0']):
|
||||
with self.assertRaisesRegex(ValueError, 'Unreviewed runtime'):
|
||||
prepare.check_sources()
|
||||
|
||||
def test_ime_payload_is_staged_before_record_and_overrides_donor_files(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
apk = root / 'donor.apk'
|
||||
files = {prepare.IME_MANIFEST: b'generated manifest',
|
||||
'usr/local/share/droiddeck/pinyin.so': b'generated ime'}
|
||||
with ZipFile(apk, 'w') as package:
|
||||
package.writestr('assets/linuxfs/' + prepare.IME_MANIFEST, b'donor manifest')
|
||||
package.writestr('assets/linuxfs/usr/local/share/droiddeck/pinyin.so', b'donor ime')
|
||||
(root / 'app/build').mkdir(parents=True)
|
||||
(root / 'app/build/runtime-inputs.json').write_text('{}')
|
||||
staged = {}
|
||||
|
||||
def record():
|
||||
for name in files:
|
||||
staged[name] = (root / 'app/src/main/assets/linuxfs' / name).read_bytes()
|
||||
|
||||
with mock.patch.object(prepare, 'ROOT', root), \
|
||||
mock.patch.object(prepare, 'check_sources', return_value={}), \
|
||||
mock.patch.object(prepare, 'DONOR_SHA256', prepare.runtime.digest(apk)), \
|
||||
mock.patch.object(prepare, 'REBUILT', {}), \
|
||||
mock.patch.object(prepare, 'JNI', ()), mock.patch.object(prepare, 'PREPARED', ()), \
|
||||
mock.patch.object(prepare, 'LOCAL_BUILD_PLUMBING', set()), \
|
||||
mock.patch.object(prepare, 'source_assets', return_value={}), \
|
||||
mock.patch.object(prepare, 'read_gamescope', return_value=({}, {
|
||||
'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \
|
||||
mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \
|
||||
mock.patch.object(prepare, 'prepare_ime',
|
||||
return_value=(files, {'version': 1, 'files': {}})), \
|
||||
mock.patch.object(prepare, 'git', return_value=b''), \
|
||||
mock.patch.object(prepare.runtime, 'record', side_effect=record), \
|
||||
mock.patch.object(prepare.runtime, 'verify'), \
|
||||
mock.patch.object(prepare.vr_build, 'build', return_value=({}, {})):
|
||||
prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip')
|
||||
self.assertEqual(staged, files)
|
||||
output = json.loads((root / 'app/build/windows-runtime-provenance.json').read_text())
|
||||
self.assertEqual(output['ime_build'], {'version': 1, 'files': {}})
|
||||
self.assertIn('regenerated from checksum-pinned RPMs',
|
||||
output['outputs']['app/src/main/assets/linuxfs/' + prepare.IME_MANIFEST]['origin'])
|
||||
|
||||
def test_second_preparation_accepts_existing_generated_ime_files(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
apk = root / 'donor.apk'
|
||||
with ZipFile(apk, 'w') as package:
|
||||
package.writestr('assets/linuxfs/unchanged.so', b'unchanged component')
|
||||
(root / 'app/build').mkdir(parents=True)
|
||||
(root / 'app/build/runtime-inputs.json').write_text('{}')
|
||||
files = {prepare.IME_MANIFEST: b'generated manifest'}
|
||||
with mock.patch.object(prepare, 'ROOT', root), \
|
||||
mock.patch.object(prepare, 'check_sources', return_value={}), \
|
||||
mock.patch.object(prepare, 'DONOR_SHA256', prepare.runtime.digest(apk)), \
|
||||
mock.patch.object(prepare, 'REBUILT', {}), \
|
||||
mock.patch.object(prepare, 'JNI', ()), mock.patch.object(prepare, 'PREPARED', ()), \
|
||||
mock.patch.object(prepare, 'LOCAL_BUILD_PLUMBING', set()), \
|
||||
mock.patch.object(prepare, 'source_assets', return_value={}), \
|
||||
mock.patch.object(prepare, 'read_gamescope', return_value=({}, {
|
||||
'GAMESCOPE_REPO': 'repo', 'GAMESCOPE_TAG': 'tag', 'GAMESCOPE_SHA256': 'hash'})), \
|
||||
mock.patch.object(prepare, 'validate_tracked_assets', return_value={}), \
|
||||
mock.patch.object(prepare, 'prepare_ime',
|
||||
return_value=(files, {'version': 1, 'files': {}})) as prepare_ime, \
|
||||
mock.patch.object(prepare, 'git', return_value=b''), \
|
||||
mock.patch.object(prepare.runtime, 'record'), \
|
||||
mock.patch.object(prepare.runtime, 'verify'), \
|
||||
mock.patch.object(prepare.vr_build, 'build', return_value=({}, {})) as build_vr, \
|
||||
mock.patch.object(prepare.vr_build, 'validate', return_value=({}, {})) as validate_vr:
|
||||
prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip')
|
||||
prepare.prepare(apk, root, root, llvm_strip=root / 'bin/llvm-strip', rebuilt_vr=root / 'cached-vr')
|
||||
build_vr.assert_called_once()
|
||||
validate_vr.assert_called_once()
|
||||
self.assertEqual(prepare_ime.call_args_list, [
|
||||
mock.call(prepare.vr_build.IMAGE),
|
||||
mock.call(prepare.vr_build.IMAGE),
|
||||
])
|
||||
self.assertEqual((root / 'app/src/main/assets/linuxfs' / prepare.IME_MANIFEST).read_bytes(),
|
||||
b'generated manifest')
|
||||
|
||||
def test_windows_ime_preparation_uses_docker_without_local_extractors(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
(root / 'tools/ime').mkdir(parents=True)
|
||||
(root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8')
|
||||
(root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8')
|
||||
manifest = {'version': 1, 'files': {
|
||||
'usr/local/share/droiddeck/pinyin.so': {
|
||||
'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}}
|
||||
commands = []
|
||||
|
||||
def run(command, check=True, capture_output=True, text=True):
|
||||
commands.append(command)
|
||||
if command[1:3] == ['image', 'inspect']:
|
||||
return mock.Mock(returncode=0, stdout='sha256:image-id linux/amd64\n', stderr='')
|
||||
mounted = next(part for part in command if part.endswith(':/out'))
|
||||
output = Path(mounted.removesuffix(':/out'))
|
||||
target = output / 'usr/local/share/droiddeck/pinyin.so'
|
||||
target.parent.mkdir(parents=True)
|
||||
target.write_bytes(b'ime')
|
||||
(output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8')
|
||||
return mock.Mock(returncode=0, stdout='', stderr='')
|
||||
|
||||
with mock.patch.object(prepare, 'ROOT', root), \
|
||||
mock.patch.object(prepare.sys, 'platform', 'win32'), \
|
||||
mock.patch.object(prepare.shutil, 'which', return_value='docker') as locate, \
|
||||
mock.patch.object(prepare.subprocess, 'run', side_effect=run):
|
||||
files, provenance = prepare.prepare_ime('compiler-image')
|
||||
inspect_command, command = commands
|
||||
self.assertEqual(inspect_command, ['docker', 'image', 'inspect', '--format',
|
||||
'{{.Id}} {{.Os}}/{{.Architecture}}', 'compiler-image'])
|
||||
self.assertEqual(command[0], 'docker')
|
||||
self.assertIn('--rm', command)
|
||||
self.assertIn('--platform', command)
|
||||
self.assertIn('linux/amd64', command)
|
||||
self.assertIn('sha256:image-id', command)
|
||||
self.assertNotIn('sha256:image-id linux/amd64', command)
|
||||
self.assertNotIn('compiler-image', command)
|
||||
shell = command[-1]
|
||||
self.assertNotIn('apt-get', shell)
|
||||
self.assertIn('command -v "$tool"', shell)
|
||||
self.assertIn('rpm2cpio cpio', shell)
|
||||
self.assertIn('rebuild compiler image using tools/local-cross.Dockerfile', shell)
|
||||
self.assertIn('exec python3 /src/tools/ime/prepare.py', shell)
|
||||
self.assertIn('--packages /cache', shell)
|
||||
self.assertIn('--download', shell)
|
||||
self.assertIn('--output /out', shell)
|
||||
locate.assert_called_once_with('docker')
|
||||
self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime')
|
||||
self.assertEqual(json.loads(files[prepare.IME_MANIFEST]), manifest)
|
||||
self.assertEqual(provenance, manifest)
|
||||
|
||||
def test_windows_ime_preparation_reuses_existing_default_image_without_building(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
(root / 'tools/ime').mkdir(parents=True)
|
||||
(root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8')
|
||||
(root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8')
|
||||
manifest = {'version': 1, 'files': {
|
||||
'usr/local/share/droiddeck/pinyin.so': {
|
||||
'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}}
|
||||
commands = []
|
||||
|
||||
def run(command, check=True, capture_output=True, text=True, input=None):
|
||||
commands.append(command)
|
||||
if command[1:3] == ['image', 'inspect']:
|
||||
return mock.Mock(returncode=0, stdout='sha256:existing-v5 linux/amd64\n', stderr='')
|
||||
mounted = next(part for part in command if part.endswith(':/out'))
|
||||
output = Path(mounted.removesuffix(':/out'))
|
||||
target = output / 'usr/local/share/droiddeck/pinyin.so'
|
||||
target.parent.mkdir(parents=True)
|
||||
target.write_bytes(b'ime')
|
||||
(output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8')
|
||||
return mock.Mock(returncode=0, stdout='', stderr='')
|
||||
|
||||
with mock.patch.object(prepare, 'ROOT', root), \
|
||||
mock.patch.object(prepare.sys, 'platform', 'win32'), \
|
||||
mock.patch.object(prepare.shutil, 'which', return_value='docker'), \
|
||||
mock.patch.object(prepare.subprocess, 'run', side_effect=run):
|
||||
files, provenance = prepare.prepare_ime(prepare.vr_build.IMAGE)
|
||||
self.assertEqual(prepare.vr_build.IMAGE, 'droiddeck-local-cross:24.04-v5')
|
||||
self.assertEqual([cmd[1] for cmd in commands], ['image', 'run'])
|
||||
self.assertEqual(commands[0], ['docker', 'image', 'inspect', '--format',
|
||||
'{{.Id}} {{.Os}}/{{.Architecture}}', 'droiddeck-local-cross:24.04-v5'])
|
||||
self.assertIn('sha256:existing-v5', commands[1])
|
||||
self.assertNotIn('sha256:existing-v5 linux/amd64', commands[1])
|
||||
self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime')
|
||||
self.assertEqual(provenance, manifest)
|
||||
|
||||
def test_windows_ime_preparation_builds_missing_or_incompatible_default_image_and_runs_by_id(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
(root / 'tools/ime').mkdir(parents=True)
|
||||
(root / 'tools/ime/prepare.py').write_text('# prepare', encoding='utf-8')
|
||||
(root / 'tools/ime/packages.json').write_text('{}', encoding='utf-8')
|
||||
(root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\r\nRUN echo ok\r\n')
|
||||
manifest = {'version': 1, 'files': {
|
||||
'usr/local/share/droiddeck/pinyin.so': {
|
||||
'sha256': hashlib.sha256(b'ime').hexdigest(), 'mode': 420}}}
|
||||
for label, first_inspect in (
|
||||
('missing', mock.Mock(returncode=1, stdout='', stderr='No such image')),
|
||||
('linux/arm64', mock.Mock(returncode=0, stdout='sha256:arm64-id linux/arm64\n', stderr='')),
|
||||
('windows/amd64', mock.Mock(returncode=0, stdout='sha256:win-id windows/amd64\n', stderr='')),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
calls = []
|
||||
inspected = 0
|
||||
|
||||
def run(command, check=True, capture_output=False, text=False, input=None):
|
||||
nonlocal inspected
|
||||
calls.append((command, input))
|
||||
if command[1:3] == ['image', 'inspect']:
|
||||
inspected += 1
|
||||
if inspected == 1:
|
||||
return first_inspect
|
||||
return mock.Mock(returncode=0, stdout='sha256:built-v5-id linux/amd64\n', stderr='')
|
||||
if command[1] == 'build':
|
||||
return mock.Mock(returncode=0)
|
||||
mounted = next(part for part in command if part.endswith(':/out'))
|
||||
output = Path(mounted.removesuffix(':/out'))
|
||||
target = output / 'usr/local/share/droiddeck/pinyin.so'
|
||||
target.parent.mkdir(parents=True)
|
||||
target.write_bytes(b'ime')
|
||||
(output / prepare.IME_MANIFEST).write_text(json.dumps(manifest), encoding='utf-8')
|
||||
return mock.Mock(returncode=0)
|
||||
|
||||
with mock.patch.object(prepare, 'ROOT', root), \
|
||||
mock.patch.object(prepare.sys, 'platform', 'win32'), \
|
||||
mock.patch.object(prepare.shutil, 'which', return_value='docker'), \
|
||||
mock.patch.object(prepare.subprocess, 'run', side_effect=run):
|
||||
files, provenance = prepare.prepare_ime(prepare.vr_build.IMAGE)
|
||||
self.assertEqual([cmd[1] for cmd, _ in calls], ['image', 'build', 'image', 'run'])
|
||||
self.assertEqual(calls[0][0], ['docker', 'image', 'inspect', '--format',
|
||||
'{{.Id}} {{.Os}}/{{.Architecture}}',
|
||||
'droiddeck-local-cross:24.04-v5'])
|
||||
build_cmd, build_input = calls[1]
|
||||
self.assertEqual(build_cmd[:8], ['docker', 'build', '--platform', 'linux/amd64',
|
||||
'--tag', 'droiddeck-local-cross:24.04-v5', '--file', '-'])
|
||||
self.assertEqual(build_input, b'FROM ubuntu:24.04\nRUN echo ok\n')
|
||||
run_cmd = calls[3][0]
|
||||
self.assertIn('sha256:built-v5-id', run_cmd)
|
||||
self.assertNotIn('sha256:built-v5-id linux/amd64', run_cmd)
|
||||
self.assertNotIn('sha256:arm64-id', run_cmd)
|
||||
self.assertNotIn('sha256:win-id', run_cmd)
|
||||
self.assertNotIn('droiddeck-local-cross:24.04-v5', run_cmd)
|
||||
self.assertNotIn('apt-get', run_cmd[-1])
|
||||
self.assertEqual(files['usr/local/share/droiddeck/pinyin.so'], b'ime')
|
||||
self.assertEqual(provenance, manifest)
|
||||
|
||||
def test_windows_ime_preparation_reports_default_image_build_failure(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
(root / 'tools').mkdir(parents=True)
|
||||
(root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\n')
|
||||
commands = []
|
||||
build_error = prepare.subprocess.CalledProcessError(17, ['docker', 'build'])
|
||||
|
||||
def run(command, check=True, capture_output=False, text=False, input=None):
|
||||
commands.append(command)
|
||||
if command[1:3] == ['image', 'inspect']:
|
||||
return mock.Mock(returncode=1, stdout='', stderr='No such image')
|
||||
if command[1] == 'build':
|
||||
raise build_error
|
||||
self.fail('unexpected command: ' + repr(command))
|
||||
|
||||
with mock.patch.object(prepare, 'ROOT', root), \
|
||||
mock.patch.object(prepare.sys, 'platform', 'win32'), \
|
||||
mock.patch.object(prepare.shutil, 'which', return_value='docker'), \
|
||||
mock.patch.object(prepare.subprocess, 'run', side_effect=run):
|
||||
with self.assertRaises(ValueError) as context:
|
||||
prepare.prepare_ime(prepare.vr_build.IMAGE)
|
||||
message = str(context.exception)
|
||||
self.assertIn(prepare.vr_build.IMAGE, message)
|
||||
self.assertRegex(message, r'(?i)build.*default compiler')
|
||||
self.assertRegex(message, r'(?i)output.*rerun')
|
||||
self.assertIs(context.exception.__cause__, build_error)
|
||||
self.assertEqual(context.exception.__cause__.returncode, 17)
|
||||
self.assertEqual([cmd[1] for cmd in commands], ['image', 'build'])
|
||||
|
||||
def test_windows_ime_preparation_stops_if_default_image_still_has_no_id_or_wrong_platform_after_build(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
(root / 'tools').mkdir(parents=True)
|
||||
(root / 'tools/local-cross.Dockerfile').write_bytes(b'FROM ubuntu:24.04\n')
|
||||
for label, result, detail in (
|
||||
('missing', mock.Mock(returncode=1, stdout='', stderr='still missing'), 'still missing'),
|
||||
('wrong-arch', mock.Mock(returncode=0, stdout='sha256:arm64-id linux/arm64\n', stderr=''), 'linux/arm64'),
|
||||
('malformed', mock.Mock(returncode=0, stdout='sha256:only-id\n', stderr=''), 'sha256:only-id'),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
commands = []
|
||||
|
||||
def run(command, check=True, capture_output=False, text=False, input=None):
|
||||
commands.append(command)
|
||||
if command[1:3] == ['image', 'inspect']:
|
||||
return result
|
||||
return mock.Mock(returncode=0)
|
||||
|
||||
with mock.patch.object(prepare, 'ROOT', root), \
|
||||
mock.patch.object(prepare.sys, 'platform', 'win32'), \
|
||||
mock.patch.object(prepare.shutil, 'which', return_value='docker'), \
|
||||
mock.patch.object(prepare.subprocess, 'run', side_effect=run):
|
||||
with self.assertRaisesRegex(ValueError, 'requires the existing Docker image') as context:
|
||||
prepare.prepare_ime(prepare.vr_build.IMAGE)
|
||||
self.assertIn('linux/amd64', str(context.exception))
|
||||
self.assertIn(prepare.vr_build.IMAGE, str(context.exception))
|
||||
self.assertIn(detail, str(context.exception))
|
||||
self.assertEqual([cmd[1] for cmd in commands], ['image', 'build', 'image'])
|
||||
|
||||
def test_windows_ime_preparation_rejects_a_missing_or_incompatible_custom_image_before_running(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
for label, result, detail in (
|
||||
('missing', mock.Mock(returncode=1, stdout='', stderr='No such image'), 'No such image'),
|
||||
('linux/arm64', mock.Mock(returncode=0, stdout='sha256:custom-arm linux/arm64\n', stderr=''), 'linux/arm64'),
|
||||
('windows/amd64', mock.Mock(returncode=0, stdout='sha256:custom-win windows/amd64\n', stderr=''), 'windows/amd64'),
|
||||
):
|
||||
with self.subTest(case=label):
|
||||
with mock.patch.object(prepare, 'ROOT', root), \
|
||||
mock.patch.object(prepare.sys, 'platform', 'win32'), \
|
||||
mock.patch.object(prepare.shutil, 'which', return_value='docker'), \
|
||||
mock.patch.object(prepare.subprocess, 'run', return_value=result) as run:
|
||||
with self.assertRaisesRegex(ValueError, 'requires the existing Docker image') as context:
|
||||
prepare.prepare_ime('custom-image')
|
||||
self.assertIn('linux/amd64', str(context.exception))
|
||||
self.assertIn('custom-image', str(context.exception))
|
||||
self.assertIn(detail, str(context.exception))
|
||||
run.assert_called_once()
|
||||
self.assertEqual(run.call_args.args[0], ['docker', 'image', 'inspect', '--format',
|
||||
'{{.Id}} {{.Os}}/{{.Architecture}}', 'custom-image'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Real subprocess checks that droiddeck-session starts its bus before the compositor."""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SESSION = ROOT / "tools/linuxfs/overlay/usr/local/bin/droiddeck-session"
|
||||
|
||||
FIXTURE = '''#!/usr/bin/env python3
|
||||
import ctypes, json, os, signal, subprocess, sys, time
|
||||
|
||||
|
||||
def stat_ppid(pid):
|
||||
try:
|
||||
with open(f"/proc/{pid}/stat", "r", encoding="utf-8") as f:
|
||||
data = f.read()
|
||||
return int(data.rsplit(") ", 1)[1].split()[1])
|
||||
except (FileNotFoundError, IndexError, ProcessLookupError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def wait_orphan(pid, timeout=2.0):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
wpid, status = os.waitpid(pid, os.WNOHANG)
|
||||
if wpid == pid:
|
||||
return status
|
||||
except ChildProcessError:
|
||||
return None
|
||||
time.sleep(0.05)
|
||||
return None
|
||||
|
||||
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
if libc.prctl(36, 1, 0, 0, 0) != 0:
|
||||
raise OSError(ctypes.get_errno(), "prctl(PR_SET_CHILD_SUBREAPER) failed")
|
||||
|
||||
harness = sys.argv[1]
|
||||
fpid = os.getpid()
|
||||
sib = subprocess.Popen(["sleep", "60"])
|
||||
orphan_pid = None
|
||||
orphan_adopted = False
|
||||
orphan_reaped = False
|
||||
orphan_killed = False
|
||||
out, rc = "", None
|
||||
try:
|
||||
helper = (
|
||||
"import subprocess; "
|
||||
"p = subprocess.Popen(['sleep', '60'], start_new_session=True, "
|
||||
"stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL); "
|
||||
"print(p.pid)"
|
||||
)
|
||||
spawner = subprocess.run([sys.executable, "-c", helper],
|
||||
capture_output=True, text=True, check=True, timeout=5)
|
||||
orphan_pid = int(spawner.stdout.strip())
|
||||
deadline = time.monotonic() + 5.0
|
||||
while time.monotonic() < deadline:
|
||||
if stat_ppid(orphan_pid) == fpid:
|
||||
orphan_adopted = True
|
||||
break
|
||||
time.sleep(0.05)
|
||||
res = subprocess.run(["bash", harness, "steam"],
|
||||
env=dict(os.environ, DD_INSIDE="1"),
|
||||
capture_output=True, text=True, timeout=15)
|
||||
out, rc = res.stdout, res.returncode
|
||||
if orphan_adopted:
|
||||
status = wait_orphan(orphan_pid)
|
||||
orphan_reaped = status is not None
|
||||
orphan_killed = (
|
||||
orphan_reaped
|
||||
and os.WIFSIGNALED(status)
|
||||
and os.WTERMSIG(status) == signal.SIGKILL
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
out = exc.stdout or ""
|
||||
if isinstance(out, bytes):
|
||||
out = out.decode()
|
||||
rc = "timeout"
|
||||
finally:
|
||||
alive = sib.poll() is None
|
||||
sib.kill()
|
||||
try:
|
||||
sib.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
if orphan_pid is not None and not orphan_reaped:
|
||||
try:
|
||||
os.kill(orphan_pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
wait_orphan(orphan_pid)
|
||||
|
||||
ppid = bus = None
|
||||
for line in out.splitlines():
|
||||
if line.startswith("PPID="):
|
||||
ppid = int(line[5:])
|
||||
elif line.startswith("BUS="):
|
||||
bus = line[4:]
|
||||
print(json.dumps({
|
||||
"fixture_pid": fpid,
|
||||
"inner_ppid": ppid,
|
||||
"inner_bus": bus,
|
||||
"fixture_bus": os.environ.get("DBUS_SESSION_BUS_ADDRESS", ""),
|
||||
"sibling_killed": not alive,
|
||||
"orphan_adopted": orphan_adopted,
|
||||
"orphan_killed": orphan_killed,
|
||||
"inner_rc": rc,
|
||||
}))
|
||||
'''
|
||||
|
||||
HARNESS = r"""#!/bin/bash
|
||||
set -u
|
||||
export HOME=${{HOME:-/root}}
|
||||
mode=${{1:-desktop}}
|
||||
shift || true
|
||||
{guard_before}
|
||||
if [ -z "${{DD_INSIDE:-}}" ]; then
|
||||
exec "$DD_FIXTURE" "$0"
|
||||
fi
|
||||
{guard_after}
|
||||
printf 'PPID=%s\n' "$PPID"
|
||||
printf 'BUS=%s\n' "${{DBUS_SESSION_BUS_ADDRESS:-}}"
|
||||
{reap}
|
||||
reap_orphans
|
||||
"""
|
||||
|
||||
SETUP = 'if [ -z "${DD_INSIDE:-}" ]; then\n /usr/local/bin/droiddeck-fonts'
|
||||
|
||||
|
||||
def extract():
|
||||
src = SESSION.read_text(encoding="utf-8")
|
||||
gstart = src.index("# Steam and its helpers share one session bus per session")
|
||||
guard = src[gstart:src.index("\nfi\n", gstart) + 4]
|
||||
rstart = src.index("reap_orphans() {")
|
||||
reap = src[rstart:src.index("\n}\n", rstart) + 3]
|
||||
return src, guard, reap
|
||||
|
||||
|
||||
def build_harness():
|
||||
src, guard, reap = extract()
|
||||
assert src.index("shift || true") < src.index(guard)
|
||||
if src.index(guard) < src.index(SETUP):
|
||||
before, after = guard, ""
|
||||
else:
|
||||
before, after = "", guard
|
||||
return HARNESS.format(guard_before=before, guard_after=after, reap=reap)
|
||||
|
||||
|
||||
@unittest.skipUnless(
|
||||
sys.platform.startswith("linux")
|
||||
and shutil.which("dbus-run-session")
|
||||
and shutil.which("bash"),
|
||||
"requires Linux and dbus-run-session and bash on PATH",
|
||||
)
|
||||
class SessionDBusTest(unittest.TestCase):
|
||||
def _run(self, inherited):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td = Path(td)
|
||||
harness = td / "harness.sh"
|
||||
fixture = td / "fixture.py"
|
||||
harness.write_text(build_harness(), encoding="utf-8")
|
||||
harness.chmod(0o755)
|
||||
fixture.write_text(FIXTURE, encoding="utf-8")
|
||||
fixture.chmod(0o755)
|
||||
env = {k: v for k, v in os.environ.items()
|
||||
if k not in ("DBUS_SESSION_BUS_ADDRESS", "DD_INSIDE")}
|
||||
env["DD_FIXTURE"] = str(fixture)
|
||||
cmd = ["bash", str(harness), "steam"]
|
||||
if inherited:
|
||||
cmd = ["dbus-run-session", "--"] + cmd
|
||||
res = subprocess.run(cmd, env=env, cwd=td, capture_output=True,
|
||||
text=True, timeout=30)
|
||||
self.assertEqual(res.returncode, 0, res.stderr)
|
||||
return json.loads(res.stdout.strip().splitlines()[-1])
|
||||
|
||||
def _check(self, data):
|
||||
self.assertEqual(data["inner_ppid"], data["fixture_pid"])
|
||||
self.assertTrue(data["fixture_bus"])
|
||||
self.assertEqual(data["inner_bus"], data["fixture_bus"])
|
||||
self.assertTrue(data["sibling_killed"])
|
||||
self.assertTrue(data["orphan_adopted"])
|
||||
self.assertTrue(data["orphan_killed"])
|
||||
self.assertEqual(data["inner_rc"], 0)
|
||||
|
||||
def test_fresh_bus(self):
|
||||
self._check(self._run(False))
|
||||
|
||||
def test_inherited_bus(self):
|
||||
self._check(self._run(True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Steam pinyin runtime requirements, without network access or a running Steam client."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
SESSION = TOOLS / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
|
||||
WRAPPER = '/usr/local/bin/droiddeck-steam-ime'
|
||||
ENGINE = '/usr/local/lib/droiddeck-ime/ibus-engine-pinyin'
|
||||
DAEMON = '/usr/bin/ibus-daemon'
|
||||
CLIENT = '/usr/bin/ibus'
|
||||
|
||||
|
||||
class SteamImeRuntimeTest(unittest.TestCase):
|
||||
@unittest.skipUnless(shutil.which('bash') and shutil.which('timeout'), 'needs bash and timeout')
|
||||
def test_steam_start_only_exports_address_after_success(self):
|
||||
source = SESSION.read_text()
|
||||
start = source.index(' unset IBUS_ADDRESS\n ime_ibus_pid=')
|
||||
fragment = source[start:source.index(' while :; do', start)]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
commands = {
|
||||
WRAPPER: ('wrapper', '#!/bin/bash\nprintf launched > "$XDG_RUNTIME_DIR/wrapper-started"\nexec sleep 5\n'),
|
||||
ENGINE: ('engine', '#!/bin/bash\nexit 0\n'),
|
||||
DAEMON: ('daemon', '#!/bin/bash\nexit 0\n'),
|
||||
CLIENT: ('client', '#!/bin/bash\ntest -f "$XDG_RUNTIME_DIR/wrapper-started" || exit 1\nprintf "pinyin\\n"\n'),
|
||||
}
|
||||
for path, (basename, script) in commands.items():
|
||||
f = root / basename
|
||||
if path != DAEMON:
|
||||
f.write_text(script)
|
||||
f.chmod(0o755)
|
||||
fragment = fragment.replace(f'{path} ', f'"{f}" ').replace(f'{path} ]', f'"{f}" ]')
|
||||
env = dict(os.environ, XDG_RUNTIME_DIR=directory, IBUS_ADDRESS='unrelated-address')
|
||||
cleanup = '\nprintf "address=%s\\n" "${IBUS_ADDRESS-unset}"\n'
|
||||
cleanup += 'printf "pid=%s\\n" "${ime_ibus_pid:-none}"; stop_steam_ime\n'
|
||||
process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + fragment + cleanup],
|
||||
text=True, capture_output=True, check=True, env=env, timeout=10)
|
||||
self.assertIn('does not include IBus', process.stdout)
|
||||
self.assertIn('address=unset', process.stdout)
|
||||
self.assertFalse((root / 'wrapper-started').exists())
|
||||
(root / 'daemon').write_text(commands[DAEMON][1])
|
||||
(root / 'daemon').chmod(0o755)
|
||||
(root / 'client').write_text('#!/bin/bash\nexit 1\n')
|
||||
refused = fragment.replace('SECONDS + 5', 'SECONDS + 1')
|
||||
process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + refused + cleanup],
|
||||
text=True, capture_output=True, check=True, env=env, timeout=10)
|
||||
self.assertIn('the pinyin engine did not start', process.stdout)
|
||||
self.assertIn('address=unset', process.stdout)
|
||||
self.assertIn('pid=none', process.stdout)
|
||||
(root / 'wrapper-started').unlink()
|
||||
(root / 'client').write_text(commands[CLIENT][1])
|
||||
process = subprocess.run(['bash', '-uc', 'nap() { sleep "$1"; }\n' + fragment + cleanup],
|
||||
text=True, capture_output=True, check=True, env=env, timeout=10)
|
||||
self.assertIn('pinyin engine ready', process.stdout)
|
||||
self.assertIn('address=unix:path=', process.stdout)
|
||||
self.assertEqual((root / 'wrapper-started').read_text(), 'launched')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,907 @@
|
||||
"""Exercise the text bridge through a real X11 client and Xutf8LookupString."""
|
||||
import ctypes
|
||||
import ctypes.util
|
||||
import locale
|
||||
import os
|
||||
import runpy
|
||||
import select
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
HELPER = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-text-input"
|
||||
XVFB = shutil.which("Xvfb")
|
||||
FOCUS_PROPERTY = b"GAMESCOPE_KEYBOARD_FOCUS_DISPLAY"
|
||||
SAMPLE = "中文ABC123,。é😀"
|
||||
MAX_TEXT = 65536
|
||||
ACK_OK = b"\x01"
|
||||
ACK_FAILED = b"\x00"
|
||||
|
||||
KEY_PRESS_MASK = 1 << 0
|
||||
KEY_RELEASE_MASK = 1 << 1
|
||||
STRUCTURE_NOTIFY_MASK = 1 << 17
|
||||
KEY_PRESS = 2
|
||||
KEY_RELEASE = 3
|
||||
MAP_NOTIFY = 19
|
||||
MAPPING_NOTIFY = 34
|
||||
REVERT_TO_PARENT = 2
|
||||
PROPERTY_REPLACE = 0
|
||||
INPUT_STYLE = 0x0408 # XIMPreeditNothing | XIMStatusNothing
|
||||
LC_ALL = 6 # glibc
|
||||
CODESET = 14 # glibc
|
||||
KEYSYM_BACKSPACE = 0xff08
|
||||
KEYSYM_RETURN = 0xff0d
|
||||
|
||||
_X11 = None
|
||||
|
||||
|
||||
class XKeyEvent(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("type", ctypes.c_int),
|
||||
("serial", ctypes.c_ulong),
|
||||
("send_event", ctypes.c_int),
|
||||
("display", ctypes.c_void_p),
|
||||
("window", ctypes.c_ulong),
|
||||
("root", ctypes.c_ulong),
|
||||
("subwindow", ctypes.c_ulong),
|
||||
("time", ctypes.c_ulong),
|
||||
("x", ctypes.c_int),
|
||||
("y", ctypes.c_int),
|
||||
("x_root", ctypes.c_int),
|
||||
("y_root", ctypes.c_int),
|
||||
("state", ctypes.c_uint),
|
||||
("keycode", ctypes.c_uint),
|
||||
("same_screen", ctypes.c_int),
|
||||
]
|
||||
|
||||
|
||||
class XModifierKeymap(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("max_keypermod", ctypes.c_int),
|
||||
("modifiermap", ctypes.POINTER(ctypes.c_ubyte)),
|
||||
]
|
||||
|
||||
|
||||
def _load_x11():
|
||||
lib = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6")
|
||||
lib.XInitThreads.restype = ctypes.c_int
|
||||
lib.XInitThreads() # the consumer reads events in its own thread
|
||||
lib.XOpenDisplay.argtypes = [ctypes.c_char_p]
|
||||
lib.XOpenDisplay.restype = ctypes.c_void_p
|
||||
lib.XCloseDisplay.argtypes = [ctypes.c_void_p]
|
||||
lib.XDefaultRootWindow.argtypes = [ctypes.c_void_p]
|
||||
lib.XDefaultRootWindow.restype = ctypes.c_ulong
|
||||
lib.XCreateSimpleWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int,
|
||||
ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_ulong,
|
||||
ctypes.c_ulong]
|
||||
lib.XCreateSimpleWindow.restype = ctypes.c_ulong
|
||||
lib.XDestroyWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong]
|
||||
lib.XSelectInput.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_long]
|
||||
lib.XMapWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong]
|
||||
lib.XSetInputFocus.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]
|
||||
lib.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
||||
lib.XPending.argtypes = [ctypes.c_void_p]
|
||||
lib.XPending.restype = ctypes.c_int
|
||||
lib.XNextEvent.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
|
||||
lib.XConnectionNumber.argtypes = [ctypes.c_void_p]
|
||||
lib.XConnectionNumber.restype = ctypes.c_int
|
||||
lib.XSetLocaleModifiers.argtypes = [ctypes.c_char_p]
|
||||
lib.XOpenIM.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
|
||||
lib.XOpenIM.restype = ctypes.c_void_p
|
||||
lib.XCreateIC.restype = ctypes.c_void_p
|
||||
lib.XDestroyIC.argtypes = [ctypes.c_void_p]
|
||||
lib.XCloseIM.argtypes = [ctypes.c_void_p]
|
||||
lib.Xutf8LookupString.argtypes = [ctypes.c_void_p, ctypes.POINTER(XKeyEvent),
|
||||
ctypes.POINTER(ctypes.c_char), ctypes.c_int,
|
||||
ctypes.POINTER(ctypes.c_ulong),
|
||||
ctypes.POINTER(ctypes.c_int)]
|
||||
lib.Xutf8LookupString.restype = ctypes.c_int
|
||||
lib.XDisplayKeycodes.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int),
|
||||
ctypes.POINTER(ctypes.c_int)]
|
||||
lib.XRefreshKeyboardMapping.argtypes = [ctypes.c_void_p]
|
||||
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.XQueryKeymap.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
|
||||
lib.XFree.argtypes = [ctypes.c_void_p]
|
||||
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
|
||||
lib.XInternAtom.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]
|
||||
lib.XInternAtom.restype = ctypes.c_ulong
|
||||
lib.XChangeProperty.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong,
|
||||
ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]
|
||||
return lib
|
||||
|
||||
|
||||
def libx11():
|
||||
global _X11
|
||||
if _X11 is None:
|
||||
_X11 = _load_x11()
|
||||
return _X11
|
||||
|
||||
|
||||
class XTextConsumer:
|
||||
"""An ordinary X11 client: it owns a focused window and keeps reading the key events the
|
||||
bridge injects, converting each one through its own input context."""
|
||||
|
||||
def __init__(self, lib, display):
|
||||
self.lib = lib
|
||||
self.lock = threading.Lock()
|
||||
self._text = b""
|
||||
self._presses = []
|
||||
self._releases = []
|
||||
self._keysyms = []
|
||||
self._stopped = threading.Event()
|
||||
self._thread = None
|
||||
self._im = None
|
||||
self._ic = None
|
||||
self._dpy = lib.XOpenDisplay(display.encode())
|
||||
if not self._dpy:
|
||||
raise RuntimeError("the test client cannot open X display " + display)
|
||||
try:
|
||||
self._window = lib.XCreateSimpleWindow(self._dpy, lib.XDefaultRootWindow(self._dpy),
|
||||
0, 0, 200, 100, 0, 0, 0)
|
||||
lib.XSelectInput(self._dpy, self._window,
|
||||
KEY_PRESS_MASK | KEY_RELEASE_MASK | STRUCTURE_NOTIFY_MASK)
|
||||
lib.XMapWindow(self._dpy, self._window)
|
||||
self._wait_for_map(display)
|
||||
lib.XSetInputFocus(self._dpy, self._window, REVERT_TO_PARENT, 0)
|
||||
lib.XSync(self._dpy, False)
|
||||
self.snapshot = self.keymap()
|
||||
self._open_input_context()
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def _wait_for_map(self, display):
|
||||
event = ctypes.create_string_buffer(192)
|
||||
deadline = time.monotonic() + 5
|
||||
while time.monotonic() < deadline:
|
||||
if self.lib.XPending(self._dpy):
|
||||
self.lib.XNextEvent(self._dpy, ctypes.cast(event, ctypes.c_void_p))
|
||||
if ctypes.cast(event, ctypes.POINTER(XKeyEvent)).contents.type == MAP_NOTIFY:
|
||||
return
|
||||
else:
|
||||
select.select([self.lib.XConnectionNumber(self._dpy)], [], [], 0.05)
|
||||
raise RuntimeError("the test client window never became viewable on " + display)
|
||||
|
||||
def _open_input_context(self):
|
||||
locale.setlocale(locale.LC_CTYPE, "C.UTF-8")
|
||||
self.lib.XSetLocaleModifiers(b"@im=none")
|
||||
self._im = self.lib.XOpenIM(self._dpy, None, None, None)
|
||||
if not self._im:
|
||||
raise RuntimeError("Xlib has no input method here, so Xutf8LookupString cannot run")
|
||||
self._ic = self.lib.XCreateIC(ctypes.c_void_p(self._im),
|
||||
ctypes.c_char_p(b"inputStyle"), ctypes.c_ulong(INPUT_STYLE),
|
||||
ctypes.c_char_p(b"clientWindow"), ctypes.c_ulong(self._window),
|
||||
ctypes.c_char_p(b"focusWindow"), ctypes.c_ulong(self._window),
|
||||
ctypes.c_void_p(0))
|
||||
if not self._ic:
|
||||
raise RuntimeError("Xlib refused an input context for Xutf8LookupString")
|
||||
self.lib.XSync(self._dpy, False)
|
||||
|
||||
def start(self):
|
||||
self._thread = threading.Thread(target=self._pump, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _pump(self):
|
||||
event = ctypes.create_string_buffer(192)
|
||||
raw = ctypes.cast(event, ctypes.c_void_p)
|
||||
fd = self.lib.XConnectionNumber(self._dpy)
|
||||
while not self._stopped.is_set():
|
||||
try:
|
||||
pending = self.lib.XPending(self._dpy)
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
if not pending:
|
||||
try:
|
||||
readable, _, _ = select.select([fd], [], [], 0.05)
|
||||
except (OSError, ValueError):
|
||||
return
|
||||
if not readable:
|
||||
continue
|
||||
while self.lib.XPending(self._dpy):
|
||||
self.lib.XNextEvent(self._dpy, raw)
|
||||
if ctypes.cast(event, ctypes.POINTER(ctypes.c_int)).contents.value == MAPPING_NOTIFY:
|
||||
self.lib.XRefreshKeyboardMapping(raw)
|
||||
continue
|
||||
key = ctypes.cast(event, ctypes.POINTER(XKeyEvent))
|
||||
if key.contents.type == KEY_PRESS:
|
||||
self._press(key)
|
||||
elif key.contents.type == KEY_RELEASE:
|
||||
with self.lock:
|
||||
self._releases.append(key.contents.keycode)
|
||||
|
||||
def _press(self, key):
|
||||
buffer = ctypes.create_string_buffer(64)
|
||||
keysym = ctypes.c_ulong(0)
|
||||
status = ctypes.c_int(0)
|
||||
count = self.lib.Xutf8LookupString(ctypes.c_void_p(self._ic), key, buffer, len(buffer),
|
||||
ctypes.byref(keysym), ctypes.byref(status))
|
||||
with self.lock:
|
||||
self._presses.append(key.contents.keycode)
|
||||
self._keysyms.append(keysym.value)
|
||||
if count > 0:
|
||||
self._text += buffer.raw[:count]
|
||||
|
||||
def wait_for(self, count, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
with self.lock:
|
||||
if len(self._presses) >= count and len(self._releases) >= count:
|
||||
return True
|
||||
time.sleep(0.01)
|
||||
with self.lock:
|
||||
return len(self._presses) >= count and len(self._releases) >= count
|
||||
|
||||
def counts(self):
|
||||
with self.lock:
|
||||
return len(self._presses), len(self._releases)
|
||||
|
||||
def press_count(self):
|
||||
with self.lock:
|
||||
return len(self._presses)
|
||||
|
||||
def press_keycodes(self):
|
||||
with self.lock:
|
||||
return sorted(self._presses)
|
||||
|
||||
def release_keycodes(self):
|
||||
with self.lock:
|
||||
return sorted(self._releases)
|
||||
|
||||
def keysyms(self):
|
||||
with self.lock:
|
||||
return list(self._keysyms)
|
||||
|
||||
def text(self):
|
||||
with self.lock:
|
||||
raw = self._text
|
||||
try:
|
||||
return raw.decode("utf-8")
|
||||
except UnicodeDecodeError as error:
|
||||
raise AssertionError("the X11 client derived %r, which is not UTF-8: %s" % (raw, error))
|
||||
|
||||
def keymap(self):
|
||||
first = ctypes.c_int(0)
|
||||
maximum = ctypes.c_int(0)
|
||||
self.lib.XDisplayKeycodes(self._dpy, ctypes.byref(first), ctypes.byref(maximum))
|
||||
count = maximum.value - first.value + 1
|
||||
per = ctypes.c_int(0)
|
||||
symbols = self.lib.XGetKeyboardMapping(self._dpy, first.value, count, ctypes.byref(per))
|
||||
if not symbols:
|
||||
raise RuntimeError("XGetKeyboardMapping returned nothing")
|
||||
values = [symbols[index] for index in range(count * per.value)]
|
||||
self.lib.XFree(ctypes.cast(symbols, ctypes.c_void_p))
|
||||
return (first.value, per.value, values)
|
||||
|
||||
def modifier_codes(self):
|
||||
"""Keycodes the server treats as modifiers; they are never replaceable."""
|
||||
mapping = self.lib.XGetModifierMapping(self._dpy)
|
||||
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 pressed_keys(self):
|
||||
keys = ctypes.create_string_buffer(32)
|
||||
self.lib.XQueryKeymap(self._dpy, ctypes.cast(keys, ctypes.c_void_p))
|
||||
return [index * 8 + bit for index in range(32) for bit in range(8)
|
||||
if keys.raw[index] >> bit & 1]
|
||||
|
||||
def close(self):
|
||||
self._stopped.set()
|
||||
if self._thread is not None:
|
||||
self._thread.join(5)
|
||||
self._thread = None
|
||||
if self._ic:
|
||||
self.lib.XDestroyIC(ctypes.c_void_p(self._ic))
|
||||
self._ic = None
|
||||
if self._im:
|
||||
self.lib.XCloseIM(ctypes.c_void_p(self._im))
|
||||
self._im = None
|
||||
if self._dpy:
|
||||
if getattr(self, "_window", None):
|
||||
self.lib.XDestroyWindow(self._dpy, self._window)
|
||||
self.lib.XCloseDisplay(self._dpy)
|
||||
self._dpy = None
|
||||
|
||||
|
||||
class XRoot:
|
||||
"""Publishes the session properties the bridge reads from the main display's root window."""
|
||||
|
||||
def __init__(self, lib, display):
|
||||
self.lib = lib
|
||||
self._dpy = lib.XOpenDisplay(display.encode())
|
||||
if not self._dpy:
|
||||
raise RuntimeError("the test client cannot open X display " + display)
|
||||
self.root = lib.XDefaultRootWindow(self._dpy)
|
||||
|
||||
def set_string(self, name, value):
|
||||
data = ctypes.create_string_buffer(value, len(value))
|
||||
self.lib.XChangeProperty(self._dpy, self.root, self._atom(name), self._atom(b"STRING"),
|
||||
8, PROPERTY_REPLACE, ctypes.cast(data, ctypes.c_void_p), len(value))
|
||||
self.lib.XSync(self._dpy, False)
|
||||
|
||||
def set_packed_cardinals(self, name, value):
|
||||
# gamescope 3.16.29 stores the display string's bytes packed into CARDINALs, little endian.
|
||||
padded = value + b"\0" * (-len(value) % 4)
|
||||
words = [int.from_bytes(padded[start:start + 4], "little") for start in range(0, len(padded), 4)]
|
||||
data = (ctypes.c_ulong * len(words))(*words)
|
||||
self.lib.XChangeProperty(self._dpy, self.root, self._atom(name), self._atom(b"CARDINAL"),
|
||||
32, PROPERTY_REPLACE, ctypes.cast(data, ctypes.c_void_p), len(words))
|
||||
self.lib.XSync(self._dpy, False)
|
||||
|
||||
def _atom(self, name):
|
||||
return self.lib.XInternAtom(self._dpy, name, 0)
|
||||
|
||||
def close(self):
|
||||
if self._dpy:
|
||||
self.lib.XCloseDisplay(self._dpy)
|
||||
self._dpy = None
|
||||
|
||||
|
||||
LAUNCHER = (
|
||||
"import subprocess, sys, time\n"
|
||||
"child = subprocess.Popen([sys.executable, sys.argv[1], sys.argv[2]])\n"
|
||||
"open(sys.argv[3], 'w').write(str(child.pid))\n"
|
||||
"time.sleep(120)\n"
|
||||
)
|
||||
|
||||
|
||||
@unittest.skipUnless(XVFB, "Xvfb is not installed")
|
||||
class TextInputTest(unittest.TestCase):
|
||||
maxDiff = 8000
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.dir = Path(self.temp.name)
|
||||
self.log = self.dir / "helper.log"
|
||||
try:
|
||||
self.lib = libx11()
|
||||
except OSError as error:
|
||||
self.fail("libX11 is missing, so no X11 client can check the bridge: %s" % error)
|
||||
|
||||
def start_display(self):
|
||||
for number in range(90, 140):
|
||||
path = Path("/tmp/.X11-unix/X%d" % number)
|
||||
if path.exists():
|
||||
continue
|
||||
process = subprocess.Popen(
|
||||
[XVFB, ":%d" % number, "-screen", "0", "320x240x24", "-nolisten", "tcp"],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self.addCleanup(self.stop_display, process)
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
if path.exists():
|
||||
return ":%d" % number
|
||||
if process.poll() is not None:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
self.fail("no Xvfb display could be started")
|
||||
|
||||
@staticmethod
|
||||
def stop_display(process):
|
||||
if process.poll() is not None:
|
||||
return
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
def consume(self, display):
|
||||
try:
|
||||
consumer = XTextConsumer(self.lib, display)
|
||||
except RuntimeError as error:
|
||||
self.fail(str(error))
|
||||
self.addCleanup(consumer.close)
|
||||
consumer.start()
|
||||
return consumer
|
||||
|
||||
def start_helper(self, socket_path, display, game_display=None):
|
||||
self.assertTrue(HELPER.is_file(),
|
||||
"the text bridge %s does not exist; the helper never started" % HELPER)
|
||||
env = dict(os.environ)
|
||||
env["DISPLAY"] = display
|
||||
env.pop("STEAM_GAME_DISPLAY_0", None)
|
||||
if game_display is not None:
|
||||
env["STEAM_GAME_DISPLAY_0"] = game_display
|
||||
stream = open(self.log, "wb")
|
||||
self.addCleanup(stream.close)
|
||||
process = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)], env=env,
|
||||
stdin=subprocess.DEVNULL, stdout=stream, stderr=subprocess.STDOUT)
|
||||
self.addCleanup(self.stop_helper, process)
|
||||
self.wait_for_socket(process, socket_path)
|
||||
return process
|
||||
|
||||
@staticmethod
|
||||
def stop_helper(process):
|
||||
if process.poll() is not None:
|
||||
return
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
def wait_for_socket(self, process, socket_path, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
self.fail("the text bridge exited with %s before serving %s; output: %r"
|
||||
% (process.returncode, socket_path.name, self.output()))
|
||||
if self.listening(socket_path):
|
||||
return
|
||||
time.sleep(0.02)
|
||||
self.fail("the text bridge never listened on %s; output: %r"
|
||||
% (socket_path.name, self.output()))
|
||||
|
||||
@staticmethod
|
||||
def listening(socket_path):
|
||||
try:
|
||||
info = socket_path.lstat()
|
||||
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(0.5)
|
||||
probe.connect(str(socket_path))
|
||||
except OSError:
|
||||
return False
|
||||
finally:
|
||||
probe.close()
|
||||
return True
|
||||
|
||||
def output(self):
|
||||
try:
|
||||
return self.log.read_text(errors="replace")[-2000:]
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
def output_bytes(self):
|
||||
try:
|
||||
return self.log.read_bytes()
|
||||
except OSError:
|
||||
return b""
|
||||
|
||||
def frame(self, socket_path, payload, timeout=15, shutdown=False):
|
||||
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.addCleanup(client.close)
|
||||
client.settimeout(timeout)
|
||||
client.connect(str(socket_path))
|
||||
client.sendall(payload)
|
||||
if shutdown:
|
||||
client.shutdown(socket.SHUT_WR)
|
||||
ack = b""
|
||||
while len(ack) < 1:
|
||||
try:
|
||||
chunk = client.recv(1)
|
||||
except socket.timeout:
|
||||
self.fail("the bridge did not answer within %s seconds" % timeout)
|
||||
if not chunk:
|
||||
break
|
||||
ack += chunk
|
||||
try:
|
||||
tail = client.recv(1)
|
||||
except socket.timeout:
|
||||
self.fail("the bridge kept the connection open after answering %r" % ack)
|
||||
self.assertEqual(b"", tail, "the bridge sent more than its one answer")
|
||||
return ack
|
||||
|
||||
def commit(self, socket_path, text, timeout=15):
|
||||
payload = text if isinstance(text, bytes) else text.encode()
|
||||
return self.frame(socket_path, struct.pack(">I", len(payload)) + payload, timeout)
|
||||
|
||||
def test_exact_unicode_reaches_a_real_x11_client(self):
|
||||
display = self.start_display()
|
||||
consumer = self.consume(display)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
process = self.start_helper(socket_path, display)
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE), "the bridge did not accept the text")
|
||||
self.assertTrue(consumer.wait_for(len(SAMPLE)),
|
||||
"the X11 client saw %d presses and %d releases of the %d key pairs the text needs"
|
||||
% (consumer.counts() + (len(SAMPLE),)))
|
||||
self.assertEqual(SAMPLE, consumer.text())
|
||||
self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(),
|
||||
"a key was pressed without its release")
|
||||
self.stop_helper(process)
|
||||
self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down")
|
||||
self.assertEqual(consumer.snapshot, consumer.keymap(),
|
||||
"the bridge did not restore the keyboard map")
|
||||
self.assertNotIn(SAMPLE.encode(), self.output_bytes(), "the bridge logged the text it typed")
|
||||
|
||||
def test_adjacent_commits_reach_the_client_in_order(self):
|
||||
display = self.start_display()
|
||||
consumer = self.consume(display)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
process = self.start_helper(socket_path, display)
|
||||
for text in ("中文", " ", "abc"):
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, text),
|
||||
"the bridge did not accept %r" % text)
|
||||
expected = "中文 abc"
|
||||
self.assertTrue(consumer.wait_for(len(expected)),
|
||||
"the X11 client saw %d presses and %d releases of the %d key pairs the text needs"
|
||||
% (consumer.counts() + (len(expected),)))
|
||||
self.assertEqual(expected, consumer.text())
|
||||
self.stop_helper(process)
|
||||
self.assertEqual(consumer.snapshot, consumer.keymap(),
|
||||
"the bridge did not restore the keyboard map")
|
||||
self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down")
|
||||
|
||||
def test_chinese_then_backspace_then_return_are_real_keysyms(self):
|
||||
display = self.start_display()
|
||||
consumer = self.consume(display)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
process = self.start_helper(socket_path, display)
|
||||
for text in ("中文", "\b", "\r"):
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, text),
|
||||
"the bridge did not accept %r" % text)
|
||||
self.assertTrue(consumer.wait_for(4),
|
||||
"the X11 client saw %d presses and %d releases of the 4 key pairs the text needs"
|
||||
% consumer.counts())
|
||||
self.assertEqual([0x01000000|ord("中"),0x01000000|ord("文"),KEYSYM_BACKSPACE,KEYSYM_RETURN],
|
||||
consumer.keysyms(),
|
||||
"the soft controls must reach the client as real keysyms after the text")
|
||||
self.assertEqual("中文\b\r", consumer.text(),
|
||||
"Xutf8LookupString is a raw lookup, not an editor; the controls stay literal")
|
||||
self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(),
|
||||
"a key was pressed without its release")
|
||||
self.stop_helper(process)
|
||||
self.assertEqual(consumer.snapshot, consumer.keymap(),
|
||||
"the bridge did not restore the keyboard map")
|
||||
self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down")
|
||||
|
||||
def test_malformed_frames_are_refused_and_the_next_text_still_works(self):
|
||||
display = self.start_display()
|
||||
consumer = self.consume(display)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
process = self.start_helper(socket_path, display)
|
||||
frames = {
|
||||
"invalid utf8": (struct.pack(">I", 2) + b"\xff\xfe", False),
|
||||
"surrogate": (struct.pack(">I", 3) + b"\xed\xa0\x80", False),
|
||||
"nul": (struct.pack(">I", 3) + b"a\x00b", False),
|
||||
"empty text": (struct.pack(">I", 0), False),
|
||||
"over the size limit": (struct.pack(">I", MAX_TEXT + 1), False),
|
||||
"little endian length": (struct.pack("<I", 5) + b"hello", False),
|
||||
"truncated body": (struct.pack(">I", 10) + b"abc", True),
|
||||
}
|
||||
for name, (payload, shutdown) in frames.items():
|
||||
with self.subTest(name):
|
||||
self.assertEqual(ACK_FAILED, self.frame(socket_path, payload, shutdown=shutdown),
|
||||
"%s must be refused with ACK 0" % name)
|
||||
time.sleep(0.3)
|
||||
self.assertEqual(0, consumer.press_count(), "a refused request still injected keys")
|
||||
self.assertEqual(consumer.snapshot, consumer.keymap(),
|
||||
"a refused request changed the keyboard map")
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE))
|
||||
self.assertTrue(consumer.wait_for(len(SAMPLE)),
|
||||
"the bridge stopped serving after refusing a request")
|
||||
self.assertEqual(SAMPLE, consumer.text())
|
||||
self.stop_helper(process)
|
||||
self.assertEqual([], consumer.pressed_keys())
|
||||
self.assertEqual(consumer.snapshot, consumer.keymap())
|
||||
|
||||
def test_stable_mappings_survive_a_delayed_consumer(self):
|
||||
display = self.start_display()
|
||||
try:
|
||||
consumer = XTextConsumer(self.lib, display)
|
||||
except RuntimeError as error:
|
||||
self.fail(str(error))
|
||||
self.addCleanup(consumer.close)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
process = self.start_helper(socket_path, display)
|
||||
later = "更多"
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE),
|
||||
"the bridge did not accept the first frame")
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, later),
|
||||
"the bridge did not accept the second frame")
|
||||
# Delay event lookup until both commits have been acknowledged.
|
||||
consumer.start()
|
||||
expected = SAMPLE + later
|
||||
self.assertTrue(consumer.wait_for(len(expected)),
|
||||
"the X11 client saw %d presses and %d releases of the %d key pairs the text needs"
|
||||
% (consumer.counts() + (len(expected),)))
|
||||
self.assertEqual(expected, consumer.text(),
|
||||
"a delayed consumer must read every character exactly once, in order")
|
||||
self.assertEqual(consumer.press_keycodes(), consumer.release_keycodes(),
|
||||
"a key was pressed without its release")
|
||||
self.stop_helper(process)
|
||||
self.assertEqual([], consumer.pressed_keys(), "the bridge left keys held down")
|
||||
self.assertEqual(consumer.snapshot, consumer.keymap(),
|
||||
"the bridge did not restore the keyboard map")
|
||||
|
||||
def test_a_frame_larger_than_the_empty_keymap_is_refused(self):
|
||||
display = self.start_display()
|
||||
consumer = self.consume(display)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
process = self.start_helper(socket_path, display)
|
||||
lowest, width, values = consumer.snapshot
|
||||
modifiers = consumer.modifier_codes()
|
||||
empty = 0
|
||||
for index in range(len(values) // width):
|
||||
keycode = lowest + index
|
||||
if keycode < 8 or keycode > 255 or keycode in modifiers:
|
||||
continue
|
||||
if not any(values[index * width:(index + 1) * width]):
|
||||
empty += 1
|
||||
self.assertLessEqual(empty, 248,
|
||||
"the keycodes 8..255 alone cap every session at 248 slots")
|
||||
flood = "".join(chr(0x4E00 + offset) for offset in range(empty + 1))
|
||||
self.assertEqual(ACK_FAILED, self.commit(socket_path, flood),
|
||||
"a frame needing more distinct keysyms than empty rows must be refused")
|
||||
time.sleep(0.5)
|
||||
self.assertEqual(0, consumer.press_count(), "a refused frame still injected keys")
|
||||
self.assertEqual(consumer.snapshot, consumer.keymap(),
|
||||
"a refused frame changed the keyboard map")
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, "中文"),
|
||||
"the refusal consumed the slots it merely measured")
|
||||
self.assertTrue(consumer.wait_for(2), "the next short text was never typed")
|
||||
self.assertEqual("中文", consumer.text())
|
||||
self.stop_helper(process)
|
||||
self.assertEqual([], consumer.pressed_keys())
|
||||
self.assertEqual(consumer.snapshot, consumer.keymap())
|
||||
|
||||
def assert_routing(self, publish):
|
||||
main = self.start_display()
|
||||
game = self.start_display()
|
||||
main_consumer = self.consume(main)
|
||||
game_consumer = self.consume(game)
|
||||
root = XRoot(self.lib, main)
|
||||
self.addCleanup(root.close)
|
||||
publish(root, game.encode())
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
self.start_helper(socket_path, main, game_display=game)
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, SAMPLE))
|
||||
self.assertTrue(game_consumer.wait_for(len(SAMPLE)),
|
||||
"the display named by %s received no text" % FOCUS_PROPERTY.decode())
|
||||
self.assertEqual(SAMPLE, game_consumer.text())
|
||||
time.sleep(0.3)
|
||||
self.assertEqual(0, main_consumer.press_count(), "the text went to both displays")
|
||||
|
||||
def test_two_displays_route_to_the_format8_property(self):
|
||||
self.assert_routing(lambda root, display: root.set_string(FOCUS_PROPERTY, display))
|
||||
|
||||
def test_two_displays_route_to_the_gamescope_format32_property(self):
|
||||
self.assert_routing(lambda root, display: root.set_packed_cardinals(FOCUS_PROPERTY, display))
|
||||
|
||||
def test_ambiguous_routing_injects_nothing(self):
|
||||
main = self.start_display()
|
||||
game = self.start_display()
|
||||
main_consumer = self.consume(main)
|
||||
game_consumer = self.consume(game)
|
||||
root = XRoot(self.lib, main)
|
||||
self.addCleanup(root.close)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
self.start_helper(socket_path, main, game_display=game)
|
||||
self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE),
|
||||
"a missing focus property must not be guessed")
|
||||
root.set_string(FOCUS_PROPERTY, b":177")
|
||||
self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE),
|
||||
"an unknown display must not be used")
|
||||
root.set_string(FOCUS_PROPERTY, b"\xff\xfe")
|
||||
self.assertEqual(ACK_FAILED, self.commit(socket_path, SAMPLE),
|
||||
"unparseable property bytes must not be used")
|
||||
time.sleep(0.3)
|
||||
self.assertEqual((0, 0), (main_consumer.press_count(), game_consumer.press_count()),
|
||||
"a refused route still injected keys")
|
||||
|
||||
def test_sigterm_exits_and_removes_only_its_own_socket(self):
|
||||
display = self.start_display()
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
process = self.start_helper(socket_path, display)
|
||||
foreign = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.addCleanup(foreign.close)
|
||||
foreign_path = self.dir / "someone-else.sock"
|
||||
foreign.bind(str(foreign_path))
|
||||
process.send_signal(signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.fail("the text bridge ignored SIGTERM")
|
||||
self.assertFalse(socket_path.exists(), "the bridge left its own socket behind")
|
||||
self.assertTrue(foreign_path.exists(), "the bridge removed a socket it does not own")
|
||||
|
||||
def test_exits_when_the_session_that_started_it_dies(self):
|
||||
display = self.start_display()
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
self.assertTrue(HELPER.is_file(),
|
||||
"the text bridge %s does not exist; the helper never started" % HELPER)
|
||||
pid_file = self.dir / "bridge.pid"
|
||||
launcher = subprocess.Popen([sys.executable, "-c", LAUNCHER, str(HELPER), str(socket_path),
|
||||
str(pid_file)],
|
||||
env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
self.addCleanup(self.stop_helper, launcher)
|
||||
pid = 0
|
||||
deadline = time.monotonic() + 10
|
||||
while time.monotonic() < deadline:
|
||||
text = pid_file.read_text() if pid_file.exists() else ""
|
||||
if text.strip().isdigit():
|
||||
pid = int(text)
|
||||
break
|
||||
time.sleep(0.02)
|
||||
self.assertTrue(pid, "the launching session never reported the bridge pid")
|
||||
self.addCleanup(self.kill_pid, pid)
|
||||
self.wait_for_socket(launcher, socket_path)
|
||||
launcher.kill()
|
||||
launcher.wait(timeout=10)
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline and self.pid_alive(pid):
|
||||
time.sleep(0.05)
|
||||
self.assertFalse(self.pid_alive(pid), "the bridge outlived the session that started it")
|
||||
self.assertFalse(socket_path.exists(), "the bridge left its socket behind")
|
||||
|
||||
def test_a_shutdown_client_during_a_blocked_tap_gets_no_ack(self):
|
||||
helper = runpy.run_path(str(HELPER))
|
||||
bridge_type = helper["XBridge"]
|
||||
begun = threading.Event()
|
||||
release = threading.Event()
|
||||
taps = []
|
||||
|
||||
class FakeBridge:
|
||||
type_text = bridge_type.type_text
|
||||
|
||||
def target_display(self):
|
||||
return ":fake"
|
||||
|
||||
def state(self, name):
|
||||
return SimpleNamespace(handle=None, codes={ord("a"): 1, ord("b"): 2})
|
||||
|
||||
def _tap(self, handle, keycode):
|
||||
taps.append(keycode)
|
||||
if len(taps) == 1:
|
||||
begun.set()
|
||||
release.wait(10)
|
||||
return True
|
||||
|
||||
server, client = socket.socketpair()
|
||||
self.addCleanup(server.close)
|
||||
self.addCleanup(client.close)
|
||||
worker = threading.Thread(target=helper["serve_connection"],
|
||||
args=(server, FakeBridge()), daemon=True)
|
||||
worker.start()
|
||||
try:
|
||||
client.sendall(struct.pack(">I", (1 << 31) | 2) + b"ab")
|
||||
self.assertTrue(begun.wait(10), "the bridge never began the first tap")
|
||||
client.shutdown(socket.SHUT_WR)
|
||||
readable, _, _ = select.select([client], [], [], 0.05)
|
||||
self.assertEqual([], readable, "the bridge answered a client that went away mid-tap")
|
||||
finally:
|
||||
release.set()
|
||||
client.settimeout(10)
|
||||
self.assertEqual(ACK_FAILED, client.recv(1),
|
||||
"a client that stopped reading must be told the tap failed")
|
||||
worker.join(10)
|
||||
self.assertFalse(worker.is_alive(), "the connection thread did not finish")
|
||||
self.assertEqual([1], taps, "the bridge kept tapping after the client went away")
|
||||
|
||||
def test_a_stalled_client_does_not_block_the_service(self):
|
||||
display = self.start_display()
|
||||
consumer = self.consume(display)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
self.start_helper(socket_path, display)
|
||||
stalled = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.addCleanup(stalled.close)
|
||||
stalled.settimeout(5)
|
||||
stalled.connect(str(socket_path))
|
||||
stalled.sendall(struct.pack(">I", 40))
|
||||
started = time.monotonic()
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, "中文", timeout=20))
|
||||
self.assertLess(time.monotonic() - started, 20)
|
||||
self.assertTrue(consumer.wait_for(2), "the later request was never typed")
|
||||
self.assertEqual("中文", consumer.text())
|
||||
|
||||
def test_sigkill_restart_on_the_same_path_serves_again(self):
|
||||
display = self.start_display()
|
||||
consumer = self.consume(display)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
first = self.start_helper(socket_path, display)
|
||||
first.send_signal(signal.SIGKILL)
|
||||
first.wait(timeout=10)
|
||||
self.start_helper(socket_path, display)
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, "重启", timeout=20))
|
||||
self.assertTrue(consumer.wait_for(2), "text after a SIGKILL restart was never typed")
|
||||
self.assertEqual("重启", consumer.text())
|
||||
|
||||
def test_a_second_helper_leaves_the_live_listener_alone(self):
|
||||
display = self.start_display()
|
||||
consumer = self.consume(display)
|
||||
socket_path = self.dir / "text-input.sock"
|
||||
self.start_helper(socket_path, display)
|
||||
before = socket_path.lstat()
|
||||
stream = open(self.log, "ab")
|
||||
self.addCleanup(stream.close)
|
||||
second = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)],
|
||||
env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL,
|
||||
stdout=stream, stderr=subprocess.STDOUT)
|
||||
self.addCleanup(self.stop_helper, second)
|
||||
try:
|
||||
code = second.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.fail("a second text bridge kept running next to the live one")
|
||||
self.assertNotEqual(0, code, "a second text bridge accepted an occupied path")
|
||||
after = socket_path.lstat()
|
||||
self.assertEqual((before.st_dev, before.st_ino), (after.st_dev, after.st_ino),
|
||||
"a second text bridge replaced the live socket")
|
||||
self.assertEqual(ACK_OK, self.commit(socket_path, "还在", timeout=20))
|
||||
self.assertTrue(consumer.wait_for(2), "the live listener stopped typing after a second launch")
|
||||
self.assertEqual("还在", consumer.text())
|
||||
|
||||
def test_a_regular_file_at_the_socket_path_is_preserved(self):
|
||||
display = self.start_display()
|
||||
socket_path = self.dir / "occupied.sock"
|
||||
socket_path.write_text("not a socket")
|
||||
code = self.launch_expecting_failure(socket_path, display)
|
||||
self.assertNotEqual(0, code, "the text bridge accepted a regular file as its socket")
|
||||
self.assertEqual("not a socket", socket_path.read_text(),
|
||||
"the text bridge overwrote a regular file")
|
||||
|
||||
def test_a_symlink_at_the_socket_path_is_preserved(self):
|
||||
display = self.start_display()
|
||||
target = self.dir / "target"
|
||||
target.write_text("keep")
|
||||
socket_path = self.dir / "link.sock"
|
||||
socket_path.symlink_to(target)
|
||||
code = self.launch_expecting_failure(socket_path, display)
|
||||
self.assertNotEqual(0, code, "the text bridge accepted a symlink as its socket")
|
||||
self.assertTrue(socket_path.is_symlink(), "the text bridge removed a symlink")
|
||||
self.assertEqual("keep", target.read_text())
|
||||
|
||||
def launch_expecting_failure(self, socket_path, display):
|
||||
stream = open(self.log, "wb")
|
||||
self.addCleanup(stream.close)
|
||||
process = subprocess.Popen([sys.executable, str(HELPER), str(socket_path)],
|
||||
env=dict(os.environ, DISPLAY=display), stdin=subprocess.DEVNULL,
|
||||
stdout=stream, stderr=subprocess.STDOUT)
|
||||
self.addCleanup(self.stop_helper, process)
|
||||
try:
|
||||
return process.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.fail("the text bridge kept running on an occupied path")
|
||||
|
||||
@staticmethod
|
||||
def kill_pid(pid):
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def pid_alive(pid):
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
try:
|
||||
state = Path("/proc/%d/stat" % pid).read_text().rsplit(")", 1)[1].split()[0]
|
||||
except (OSError, IndexError):
|
||||
return False
|
||||
return state != "Z"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,487 @@
|
||||
"""Compiled FIFO regression for the native host queue in droiddeck_ext.c."""
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
CC = shutil.which("cc")
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/droiddeck_ext.c"
|
||||
HEADER = SOURCE.with_name("droiddeck_ext.h")
|
||||
|
||||
WAYLAND_H = """
|
||||
#ifndef STUB_WAYLAND_SERVER_H
|
||||
#define STUB_WAYLAND_SERVER_H
|
||||
#include <stdint.h>
|
||||
struct wl_display;
|
||||
struct wl_event_loop;
|
||||
struct wl_resource;
|
||||
struct wl_client;
|
||||
struct wl_event_source;
|
||||
#define WL_EVENT_READABLE 1u
|
||||
struct wl_event_loop *wl_display_get_event_loop(struct wl_display *);
|
||||
void wl_display_flush_clients(struct wl_display *);
|
||||
struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *, int, uint32_t,
|
||||
int (*)(int, uint32_t, void *), void *);
|
||||
#endif
|
||||
"""
|
||||
|
||||
ANDROID_H = """
|
||||
#ifndef STUB_ANDROID_LOG_H
|
||||
#define STUB_ANDROID_LOG_H
|
||||
#define ANDROID_LOG_ERROR 6
|
||||
int __android_log_print(int, const char *, const char *, ...);
|
||||
#endif
|
||||
"""
|
||||
|
||||
AHB_H = """
|
||||
#ifndef STUB_AHB_SWAPCHAIN_H
|
||||
#define STUB_AHB_SWAPCHAIN_H
|
||||
void ahb_swapchain_set_mode(int, int);
|
||||
#endif
|
||||
"""
|
||||
|
||||
COLOR_H = """
|
||||
#ifndef STUB_DROIDDECK_COLOR_H
|
||||
#define STUB_DROIDDECK_COLOR_H
|
||||
void droiddeck_color_set_output(int);
|
||||
#endif
|
||||
"""
|
||||
|
||||
PROGRAM = """
|
||||
#define _GNU_SOURCE 1
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include "android/log.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "ahb_swapchain.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "droiddeck_ext.c"
|
||||
|
||||
#define CHECK(c) do { if (!(c)) { fprintf(stderr, "check failed at line %d", __LINE__); return 1; } } while (0)
|
||||
|
||||
struct ev { int kind; uint32_t a; int b; char text[64]; };
|
||||
static struct ev g_ev[32];
|
||||
static int g_n;
|
||||
static int g_native_key_down[KEY_CNT];
|
||||
static uint32_t g_pending_raw_release;
|
||||
static int g_display_stub;
|
||||
static int g_loop_stub;
|
||||
static int g_fallback_accept;
|
||||
static int g_fallback_token;
|
||||
static int g_hdr_count;
|
||||
|
||||
int text_input_host_commit(const char *u, size_t n)
|
||||
{
|
||||
struct ev *e;
|
||||
if (n == 3 && memcmp(u, "x11", 3) == 0)
|
||||
return 0;
|
||||
if (g_n >= 32 || n >= sizeof(g_ev[0].text))
|
||||
return 0;
|
||||
e = &g_ev[g_n++];
|
||||
e->kind = 1;
|
||||
e->a = (uint32_t)n;
|
||||
memcpy(e->text, u, n);
|
||||
e->text[n] = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void text_input_host_preedit(const char *u, size_t n, int a, int b)
|
||||
{
|
||||
(void)u; (void)n; (void)a; (void)b;
|
||||
}
|
||||
|
||||
void text_input_host_delete(int a, int b) { (void)a; (void)b; }
|
||||
void clipboard_host_text(char *u, size_t n) { (void)n; free(u); }
|
||||
int droiddeck_on_text_input_fallback(const char *u, int n, int token)
|
||||
{
|
||||
if (!g_fallback_accept) return 0;
|
||||
if (n == 3 && memcmp(u, "x11", 3) == 0) {
|
||||
g_fallback_token = token;
|
||||
return 1;
|
||||
}
|
||||
g_fallback_token = token;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int droiddeck_key_is_down(uint32_t k)
|
||||
{
|
||||
return k < KEY_CNT && g_native_key_down[k];
|
||||
}
|
||||
|
||||
void droiddeck_inject_key(uint32_t k, int s)
|
||||
{
|
||||
if (k < KEY_CNT)
|
||||
g_native_key_down[k] = s;
|
||||
if (g_n < 32) {
|
||||
g_ev[g_n].kind = 2;
|
||||
g_ev[g_n].a = k;
|
||||
g_ev[g_n].b = s;
|
||||
g_ev[g_n].text[0] = 0;
|
||||
g_n++;
|
||||
}
|
||||
}
|
||||
|
||||
void droiddeck_dispatch_pending_input(void)
|
||||
{
|
||||
if (!g_pending_raw_release) return;
|
||||
droiddeck_inject_key(g_pending_raw_release, 0);
|
||||
g_pending_raw_release = 0;
|
||||
}
|
||||
|
||||
void clipboard_init(struct wl_display *d) { (void)d; }
|
||||
void text_input_init(struct wl_display *d) { (void)d; }
|
||||
void toplevel_icon_init(struct wl_display *d) { (void)d; }
|
||||
void single_pixel_init(struct wl_display *d) { (void)d; }
|
||||
void ahb_swapchain_set_mode(int a, int b) { (void)a; (void)b; }
|
||||
void droiddeck_color_set_output(int a) { (void)a; g_hdr_count++; }
|
||||
|
||||
struct wl_display *droiddeck_get_display(void) { return (struct wl_display *)&g_display_stub; }
|
||||
void wl_display_flush_clients(struct wl_display *d) { (void)d; }
|
||||
|
||||
struct wl_event_loop *wl_display_get_event_loop(struct wl_display *d)
|
||||
{
|
||||
(void)d;
|
||||
return (struct wl_event_loop *)&g_loop_stub;
|
||||
}
|
||||
|
||||
struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd,
|
||||
uint32_t m, int (*f)(int, uint32_t, void *), void *d)
|
||||
{
|
||||
(void)l; (void)fd; (void)m; (void)f; (void)d;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void droiddeck_log(const char *t, const char *f, ...) { (void)t; (void)f; }
|
||||
|
||||
int __android_log_print(int p, const char *t, const char *f, ...)
|
||||
{
|
||||
(void)p; (void)t; (void)f;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int saved;
|
||||
CHECK(pipe2(g_wake, O_CLOEXEC | O_NONBLOCK) == 0);
|
||||
droiddeck_host_text_commit("中文", (int)strlen("中文"));
|
||||
droiddeck_host_key(28, 1);
|
||||
droiddeck_host_key(28, 0);
|
||||
droiddeck_host_text_commit("日本語", (int)strlen("日本語"));
|
||||
droiddeck_host_key(14, 1);
|
||||
droiddeck_host_key(14, 0);
|
||||
droiddeck_host_key(111, 1);
|
||||
droiddeck_host_key(111, 0);
|
||||
droiddeck_host_key(15, 1);
|
||||
droiddeck_host_key(15, 0);
|
||||
CHECK(g_n == 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 10);
|
||||
CHECK(g_ev[0].kind == 1 && strcmp(g_ev[0].text, "中文") == 0);
|
||||
CHECK(g_ev[1].kind == 2 && g_ev[1].a == 28u && g_ev[1].b == 1);
|
||||
CHECK(g_ev[2].kind == 2 && g_ev[2].a == 28u && g_ev[2].b == 0);
|
||||
CHECK(g_ev[3].kind == 1 && strcmp(g_ev[3].text, "日本語") == 0);
|
||||
CHECK(g_ev[4].kind == 2 && g_ev[4].a == 14u && g_ev[4].b == 1);
|
||||
CHECK(g_ev[5].kind == 2 && g_ev[5].a == 14u && g_ev[5].b == 0);
|
||||
CHECK(g_ev[6].kind == 2 && g_ev[6].a == 111u && g_ev[6].b == 1);
|
||||
CHECK(g_ev[7].kind == 2 && g_ev[7].a == 111u && g_ev[7].b == 0);
|
||||
CHECK(g_ev[8].kind == 2 && g_ev[8].a == 15u && g_ev[8].b == 1);
|
||||
CHECK(g_ev[9].kind == 2 && g_ev[9].a == 15u && g_ev[9].b == 0);
|
||||
saved = g_n;
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved);
|
||||
droiddeck_host_text_commit("尾", (int)strlen("尾"));
|
||||
droiddeck_host_key(16, 1);
|
||||
droiddeck_host_key(16, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 3);
|
||||
CHECK(g_ev[saved].kind == 1 && strcmp(g_ev[saved].text, "尾") == 0);
|
||||
CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 16u && g_ev[saved + 1].b == 1);
|
||||
CHECK(g_ev[saved + 2].kind == 2 && g_ev[saved + 2].a == 16u && g_ev[saved + 2].b == 0);
|
||||
CHECK(g_head == NULL && g_tail == NULL);
|
||||
saved = g_n;
|
||||
g_fallback_accept = 1;
|
||||
droiddeck_host_text_commit("x11", 3);
|
||||
droiddeck_host_key(29, 1);
|
||||
droiddeck_host_key(28, 1);
|
||||
droiddeck_host_key(28, 0);
|
||||
droiddeck_host_key(29, 0);
|
||||
droiddeck_host_text_commit("later", 5);
|
||||
droiddeck_host_hdr_output(1);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved);
|
||||
CHECK(g_hdr_count == 1);
|
||||
CHECK(g_fallback_token > 0);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token + 1, DROIDDECK_TEXT_DELIVERED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved);
|
||||
droiddeck_host_key(30, 1);
|
||||
droiddeck_host_key(30, 0);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_DELIVERED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 7);
|
||||
CHECK(g_ev[saved].kind == 2 && g_ev[saved].a == 29u && g_ev[saved].b == 1);
|
||||
CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 28u && g_ev[saved + 1].b == 1);
|
||||
CHECK(g_ev[saved + 2].kind == 2 && g_ev[saved + 2].a == 28u && g_ev[saved + 2].b == 0);
|
||||
CHECK(g_ev[saved + 3].kind == 2 && g_ev[saved + 3].a == 29u && g_ev[saved + 3].b == 0);
|
||||
CHECK(g_ev[saved + 4].kind == 1 && strcmp(g_ev[saved + 4].text, "later") == 0);
|
||||
CHECK(g_ev[saved + 5].kind == 2 && g_ev[saved + 5].a == 30u && g_ev[saved + 5].b == 1);
|
||||
CHECK(g_ev[saved + 6].kind == 2 && g_ev[saved + 6].a == 30u && g_ev[saved + 6].b == 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 7);
|
||||
g_fallback_accept = 0;
|
||||
droiddeck_host_text_commit("x11", 3);
|
||||
droiddeck_host_key(31, 1);
|
||||
droiddeck_host_key(31, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 9);
|
||||
CHECK(g_ev[saved + 7].kind == 2 && g_ev[saved + 7].a == 31u && g_ev[saved + 7].b == 1);
|
||||
CHECK(g_ev[saved + 8].kind == 2 && g_ev[saved + 8].a == 31u && g_ev[saved + 8].b == 0);
|
||||
CHECK(g_head == NULL && g_tail == NULL);
|
||||
g_n = saved = 0;
|
||||
g_fallback_accept = 1;
|
||||
droiddeck_host_key(29, 1);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 1);
|
||||
CHECK(g_ev[saved].kind == 2 && g_ev[saved].a == 29u && g_ev[saved].b == 1);
|
||||
droiddeck_host_text_commit("x11", 3);
|
||||
droiddeck_host_select_game_field(0);
|
||||
droiddeck_host_text_commit("discard", 7);
|
||||
droiddeck_host_key(29, 0);
|
||||
droiddeck_host_key(32, 1);
|
||||
droiddeck_host_key(32, 0);
|
||||
droiddeck_host_hdr_output(0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 1);
|
||||
CHECK(g_hdr_count == 2);
|
||||
CHECK(g_fallback_token > 0);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 2);
|
||||
CHECK(g_ev[saved + 1].kind == 2 && g_ev[saved + 1].a == 29u && g_ev[saved + 1].b == 0);
|
||||
droiddeck_host_text_commit("held", 4);
|
||||
droiddeck_host_key(33, 1);
|
||||
droiddeck_host_key(33, 0);
|
||||
droiddeck_host_key(34, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 2);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED);
|
||||
droiddeck_host_text_commit("resume", 6);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == saved + 14);
|
||||
CHECK(g_ev[saved + 2].a == KEY_LEFTCTRL && g_ev[saved + 2].b == 1);
|
||||
CHECK(g_ev[saved + 3].a == KEY_A && g_ev[saved + 3].b == 1);
|
||||
CHECK(g_ev[saved + 5].a == KEY_LEFTCTRL && g_ev[saved + 5].b == 0);
|
||||
CHECK(g_ev[saved + 6].kind == 1 && strcmp(g_ev[saved + 6].text, "discard") == 0);
|
||||
CHECK(g_ev[saved + 7].a == 32u && g_ev[saved + 7].b == 1);
|
||||
CHECK(g_ev[saved + 9].kind == 1 && strcmp(g_ev[saved + 9].text, "held") == 0);
|
||||
CHECK(g_ev[saved + 13].kind == 1 && strcmp(g_ev[saved + 13].text, "resume") == 0);
|
||||
CHECK(g_head == NULL && g_tail == NULL);
|
||||
for (int pending = 0; pending <= 1; ++pending) {
|
||||
g_n = 0;
|
||||
droiddeck_inject_key(KEY_LEFTCTRL, 1);
|
||||
if (pending)
|
||||
droiddeck_host_text_commit("x11", 3);
|
||||
droiddeck_host_select_game_field(0);
|
||||
droiddeck_host_text_commit("body", 4);
|
||||
if (pending) {
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 1);
|
||||
}
|
||||
droiddeck_inject_key(KEY_LEFTCTRL, 0);
|
||||
if (pending)
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_DELIVERED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 7);
|
||||
CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_LEFTCTRL && g_ev[2].b == 1);
|
||||
CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_A && g_ev[3].b == 1);
|
||||
CHECK(g_ev[4].kind == 2 && g_ev[4].a == KEY_A && g_ev[4].b == 0);
|
||||
CHECK(g_ev[5].kind == 2 && g_ev[5].a == KEY_LEFTCTRL && g_ev[5].b == 0);
|
||||
CHECK(g_ev[6].kind == 1 && strcmp(g_ev[6].text, "body") == 0);
|
||||
CHECK(!droiddeck_key_is_down(KEY_LEFTCTRL));
|
||||
CHECK(g_head == NULL && g_tail == NULL);
|
||||
}
|
||||
|
||||
g_n = 0;
|
||||
droiddeck_inject_key(KEY_RIGHTCTRL, 1);
|
||||
droiddeck_host_select_game_field(1);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 5);
|
||||
CHECK(g_ev[1].kind == 2 && g_ev[1].a == KEY_A && g_ev[1].b == 1);
|
||||
CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_A && g_ev[2].b == 0);
|
||||
CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_C && g_ev[3].b == 1);
|
||||
CHECK(g_ev[4].kind == 2 && g_ev[4].a == KEY_C && g_ev[4].b == 0);
|
||||
CHECK(droiddeck_key_is_down(KEY_RIGHTCTRL));
|
||||
droiddeck_inject_key(KEY_RIGHTCTRL, 0);
|
||||
CHECK(g_head == NULL && g_tail == NULL);
|
||||
|
||||
for (int copy = 0; copy <= 1; ++copy) {
|
||||
uint32_t key = copy ? KEY_C : KEY_A;
|
||||
g_n = 0;
|
||||
droiddeck_inject_key(key, 1);
|
||||
g_pending_raw_release = key;
|
||||
droiddeck_host_select_game_field(copy);
|
||||
droiddeck_host_text_commit("body", 4);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_pending_raw_release == 0);
|
||||
CHECK(g_n == (copy ? 9 : 7));
|
||||
CHECK(g_ev[1].kind == 2 && g_ev[1].a == key && g_ev[1].b == 0);
|
||||
CHECK(g_ev[2].kind == 2 && g_ev[2].a == KEY_LEFTCTRL && g_ev[2].b == 1);
|
||||
CHECK(g_ev[3].kind == 2 && g_ev[3].a == KEY_A && g_ev[3].b == 1);
|
||||
if (copy) CHECK(g_ev[5].kind == 2 && g_ev[5].a == KEY_C && g_ev[5].b == 1);
|
||||
CHECK(g_ev[g_n - 1].kind == 1 && strcmp(g_ev[g_n - 1].text, "body") == 0);
|
||||
CHECK(!droiddeck_key_is_down(key));
|
||||
}
|
||||
|
||||
for (int held = 0; held <= 1; ++held) {
|
||||
g_n = 0;
|
||||
if (held) {
|
||||
droiddeck_host_key(KEY_ENTER, 1);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(droiddeck_key_is_down(KEY_ENTER));
|
||||
g_n = 0;
|
||||
}
|
||||
droiddeck_host_text_commit("x11", 3);
|
||||
droiddeck_host_key(KEY_LEFTCTRL, 1);
|
||||
if (!held) droiddeck_host_key(KEY_ENTER, 1);
|
||||
droiddeck_host_key(KEY_ENTER, 0);
|
||||
droiddeck_host_key(KEY_KPENTER, 1);
|
||||
droiddeck_host_key(KEY_KPENTER, 0);
|
||||
droiddeck_host_text_commit("\\r", 1);
|
||||
droiddeck_host_key(KEY_LEFTCTRL, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 0);
|
||||
droiddeck_host_text_commit("later", 5);
|
||||
droiddeck_host_key(KEY_ENTER, 1);
|
||||
droiddeck_host_key(KEY_ENTER, 0);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == (held ? 6 : 5));
|
||||
CHECK(g_ev[0].a == KEY_LEFTCTRL && g_ev[0].b == 1);
|
||||
if (held) CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 0);
|
||||
CHECK(g_ev[g_n - 4].a == KEY_LEFTCTRL && g_ev[g_n - 4].b == 0);
|
||||
CHECK(g_ev[g_n - 3].kind == 1 && strcmp(g_ev[g_n - 3].text, "later") == 0);
|
||||
CHECK(g_ev[g_n - 2].a == KEY_ENTER && g_ev[g_n - 2].b == 1);
|
||||
CHECK(g_ev[g_n - 1].a == KEY_ENTER && g_ev[g_n - 1].b == 0);
|
||||
CHECK(!droiddeck_key_is_down(KEY_ENTER) && !droiddeck_key_is_down(KEY_LEFTCTRL));
|
||||
}
|
||||
|
||||
g_n = 0;
|
||||
droiddeck_host_text_commit("x11", 3);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
droiddeck_host_key(KEY_ENTER, 1);
|
||||
droiddeck_host_key(KEY_ENTER, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 2 && g_ev[0].a == KEY_ENTER && g_ev[0].b == 1 && g_ev[1].b == 0);
|
||||
|
||||
g_n = 0;
|
||||
droiddeck_host_text_commit_and_submit("wayland", 7);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 3 && g_ev[0].kind == 1 && strcmp(g_ev[0].text, "wayland") == 0);
|
||||
CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1);
|
||||
CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0);
|
||||
|
||||
for (int result = DROIDDECK_TEXT_NOT_DELIVERED; result <= DROIDDECK_TEXT_DELIVERED; ++result) {
|
||||
g_n = 0;
|
||||
droiddeck_host_text_commit_and_submit("x11", 3);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 0);
|
||||
droiddeck_host_text_commit("later", 5);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, result);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == (result == DROIDDECK_TEXT_DELIVERED ? 3 : 1));
|
||||
if (result == DROIDDECK_TEXT_DELIVERED) {
|
||||
CHECK(g_ev[0].a == KEY_ENTER && g_ev[0].b == 1);
|
||||
CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 0);
|
||||
}
|
||||
CHECK(g_ev[g_n - 1].kind == 1 && strcmp(g_ev[g_n - 1].text, "later") == 0);
|
||||
}
|
||||
|
||||
g_n = 0;
|
||||
g_fallback_accept = 0;
|
||||
droiddeck_host_text_commit_and_submit("x11", 3);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 0);
|
||||
droiddeck_host_text_commit("next", 4);
|
||||
droiddeck_host_key(KEY_ENTER, 1);
|
||||
droiddeck_host_key(KEY_ENTER, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 3 && g_ev[0].kind == 1 && strcmp(g_ev[0].text, "next") == 0);
|
||||
CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1);
|
||||
CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0);
|
||||
|
||||
g_n = 0;
|
||||
g_fallback_accept = 1;
|
||||
droiddeck_host_key(KEY_LEFTCTRL, 1);
|
||||
droiddeck_host_text_commit("x11", 3);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED);
|
||||
droiddeck_host_key(KEY_LEFTCTRL, 0);
|
||||
droiddeck_host_key(KEY_ENTER, 1);
|
||||
for (int i = 0; i <= DROIDDECK_TEXT_DEFERRED_LIMIT; i++)
|
||||
droiddeck_host_text_commit("queued", 6);
|
||||
droiddeck_host_key(KEY_ENTER, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 2 && !droiddeck_key_is_down(KEY_LEFTCTRL));
|
||||
CHECK(g_deferred_overflow && !g_deferred_head && !g_deferred_count && !g_deferred_bytes);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
droiddeck_host_key(KEY_ENTER, 1);
|
||||
droiddeck_host_key(KEY_ENTER, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
CHECK(g_n == 4 && !droiddeck_key_is_down(KEY_ENTER));
|
||||
|
||||
g_n = 0;
|
||||
droiddeck_host_text_commit("x11", 3);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_UNRESOLVED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0);
|
||||
droiddeck_host_text_commit("\\r", 1);
|
||||
droiddeck_host_text_commit("next", 4);
|
||||
droiddeck_host_key(KEY_ENTER, 1);
|
||||
droiddeck_host_key(KEY_ENTER, 0);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0 && g_n == 0);
|
||||
droiddeck_host_text_input_fallback_complete(g_fallback_token, DROIDDECK_TEXT_NOT_DELIVERED);
|
||||
CHECK(on_wake(g_wake[0], 0, NULL) == 0 && g_n == 3);
|
||||
CHECK(g_ev[0].kind == 1 && strcmp(g_ev[0].text, "next") == 0);
|
||||
CHECK(g_ev[1].a == KEY_ENTER && g_ev[1].b == 1);
|
||||
CHECK(g_ev[2].a == KEY_ENTER && g_ev[2].b == 0);
|
||||
|
||||
close(g_wake[0]);
|
||||
close(g_wake[1]);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
@unittest.skipUnless(sys.platform.startswith("linux"), "requires Linux pipe2")
|
||||
@unittest.skipUnless(CC, "requires cc")
|
||||
class WaylandHostOrderTest(unittest.TestCase):
|
||||
def test_fifo_order(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp = Path(tmp)
|
||||
(tmp / "android").mkdir()
|
||||
(tmp / "android/log.h").write_text(ANDROID_H)
|
||||
(tmp / "wayland-server.h").write_text(WAYLAND_H)
|
||||
(tmp / "ahb_swapchain.h").write_text(AHB_H)
|
||||
(tmp / "droiddeck_color.h").write_text(COLOR_H)
|
||||
shutil.copyfile(SOURCE, tmp / "droiddeck_ext.c")
|
||||
shutil.copyfile(HEADER, tmp / "droiddeck_ext.h")
|
||||
(tmp / "program.c").write_text(PROGRAM, encoding="utf-8")
|
||||
subprocess.run([CC, "-std=c11", "-Wall", "-Wextra", "-Werror",
|
||||
"-Wno-unused-parameter", "-pthread", "-I", str(tmp),
|
||||
"-o", str(tmp / "probe"), str(tmp / "program.c")],
|
||||
cwd=tmp, check=True, timeout=30)
|
||||
subprocess.run([str(tmp / "probe")], cwd=tmp, check=True, timeout=10)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -122,6 +122,60 @@ class WindowsVrBuildTest(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, 'configuration differs'):
|
||||
self.validate()
|
||||
|
||||
def test_build_image_selection_and_platform_validation(self):
|
||||
outputs = vr.read_outputs(self.out, self.root)
|
||||
cases = [
|
||||
('cached_amd64', vr.IMAGE, [(0, 'sha256:cached linux/amd64\n')], False, 'sha256:cached', None),
|
||||
('missing_default', vr.IMAGE, [(1, ''), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None),
|
||||
('default_arm64', vr.IMAGE, [(0, 'sha256:old linux/arm64\n'), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None),
|
||||
('default_windows', vr.IMAGE, [(0, 'sha256:old windows/amd64\n'), (0, 'sha256:rebuilt linux/amd64\n')], True, 'sha256:rebuilt', None),
|
||||
('custom_arm64', 'custom:vr', [(0, 'sha256:custom linux/arm64\n')], False, None, r'linux/amd64.*custom:vr'),
|
||||
('rebuild_still_arm64', vr.IMAGE, [(0, 'sha256:old linux/arm64\n'), (0, 'sha256:bad linux/arm64\n')], True, None, r'linux/amd64'),
|
||||
]
|
||||
for name, image, inspects, expect_build, expected_id, err in cases:
|
||||
with self.subTest(name=name):
|
||||
calls, queue = [], list(inspects)
|
||||
def fake_run(cmd, **kw):
|
||||
calls.append(cmd)
|
||||
if cmd[1:3] == ['image', 'inspect']:
|
||||
rc, out = queue.pop(0)
|
||||
return vr.subprocess.CompletedProcess(cmd, rc, stdout=out, stderr='')
|
||||
return vr.subprocess.CompletedProcess(cmd, 0, stdout='linux\n', stderr='')
|
||||
with mock.patch.object(vr.shutil, 'which', return_value='docker'), \
|
||||
mock.patch.object(vr.subprocess, 'run', side_effect=fake_run), \
|
||||
mock.patch.object(vr.subprocess, 'check_output', return_value=b'sha256:legacy\n'), \
|
||||
mock.patch.object(vr, 'read_outputs', return_value=outputs) as m_read, \
|
||||
mock.patch.object(vr, 'validate', return_value=(outputs, self.manifest)) as m_val:
|
||||
if err:
|
||||
with self.assertRaisesRegex(ValueError, err):
|
||||
vr.build(self.out, self.include, self.root, image=image)
|
||||
m_read.assert_not_called()
|
||||
m_val.assert_not_called()
|
||||
else:
|
||||
self.assertEqual(vr.build(self.out, self.include, self.root, image=image), (outputs, self.manifest))
|
||||
m_read.assert_called_once()
|
||||
m_val.assert_called_once_with(self.out, self.include, self.root)
|
||||
inspect_cmds = [c for c in calls if c[1:3] == ['image', 'inspect']]
|
||||
build_cmds = [c for c in calls if c[1] == 'build']
|
||||
run_cmds = [c for c in calls if c[1] == 'run']
|
||||
self.assertEqual(len(inspect_cmds), len(inspects))
|
||||
for c in inspect_cmds:
|
||||
self.assertEqual(c[:5], ['docker', 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}'])
|
||||
if expect_build:
|
||||
self.assertEqual(len(build_cmds), 1)
|
||||
self.assertEqual(build_cmds[0][:6], ['docker', 'build', '--platform', 'linux/amd64', '--tag', image])
|
||||
else:
|
||||
self.assertEqual(build_cmds, [])
|
||||
if expected_id:
|
||||
self.assertEqual(len(run_cmds), 1)
|
||||
self.assertIn(expected_id, run_cmds[0])
|
||||
self.assertNotIn(image, run_cmds[0])
|
||||
self.assertTrue(all('linux/amd64' not in a or a == 'linux/amd64' for a in run_cmds[0]))
|
||||
manifest = json.loads((self.out / vr.MANIFEST).read_text(encoding='utf-8'))
|
||||
self.assertEqual(manifest['compiler_image'], expected_id)
|
||||
else:
|
||||
self.assertEqual(run_cmds, [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -10,7 +10,7 @@ import subprocess
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
IMAGE = 'droiddeck-local-cross:24.04-v3'
|
||||
IMAGE = 'droiddeck-local-cross:24.04-v5'
|
||||
MANIFEST = 'vr-build.json'
|
||||
SOURCE_TREES = ('tools/vr/src', 'tools/vr/tests', 'tools/vr/third_party',
|
||||
'tools/vr/driver_droiddeck', 'tools/vr/layer')
|
||||
@@ -131,14 +131,22 @@ def build(folder, include, root=ROOT, image=IMAGE):
|
||||
snapshot = Path(temp).resolve()
|
||||
if not snapshot.is_relative_to(workspace):
|
||||
raise ValueError('Temporary VR workspace escapes the checkout')
|
||||
inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}}', image],
|
||||
inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image],
|
||||
capture_output=True, text=True)
|
||||
if inspect.returncode:
|
||||
parts = inspect.stdout.strip().split() if inspect.returncode == 0 else []
|
||||
if len(parts) == 2 and parts[1] == 'linux/amd64' and parts[0]:
|
||||
image_id = parts[0]
|
||||
else:
|
||||
if image != IMAGE:
|
||||
raise ValueError('VR compiler image is not available locally: ' + image)
|
||||
subprocess.run([docker, 'build', '--tag', image, '--file', '-', str(snapshot)],
|
||||
raise ValueError(f'VR compiler image is not available locally for linux/amd64: {image} (got {inspect.stdout.strip() or "missing"})')
|
||||
subprocess.run([docker, 'build', '--platform', 'linux/amd64', '--tag', image, '--file', '-', str(snapshot)],
|
||||
input=input_files['tools/local-cross.Dockerfile'], check=True)
|
||||
image_id = subprocess.check_output([docker, 'image', 'inspect', '--format', '{{.Id}}', image]).decode().strip()
|
||||
inspect = subprocess.run([docker, 'image', 'inspect', '--format', '{{.Id}} {{.Os}}/{{.Architecture}}', image],
|
||||
capture_output=True, text=True, check=True)
|
||||
parts = inspect.stdout.strip().split()
|
||||
if len(parts) != 2 or parts[1] != 'linux/amd64' or not parts[0]:
|
||||
raise ValueError(f'VR compiler image {image} expected id and linux/amd64, got {inspect.stdout.strip()!r}')
|
||||
image_id = parts[0]
|
||||
for name, data in input_files.items():
|
||||
target = snapshot / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
Reference in new issue
Block a user