mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-04 03:55:44 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53fdc2c9ad | ||
|
|
e9877e27f7 | ||
|
|
b67a69542c | ||
|
|
02e7eff284 | ||
|
|
439d9afe5e |
No files matched your search
@@ -438,32 +438,26 @@ __attribute__((constructor)) static void library_init() {
|
||||
controller_map();
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int connect_app_socket(const char *name, int flags) {
|
||||
int sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | flags, 0);
|
||||
if (sock < 0)
|
||||
return -1;
|
||||
|
||||
struct sockaddr_un addr = {};
|
||||
addr.sun_family = AF_UNIX;
|
||||
memcpy(addr.sun_path + 1, name, strlen(name));
|
||||
socklen_t addrlen = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(name);
|
||||
|
||||
if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), addrlen) < 0) {
|
||||
syscall(SYS_close, sock);
|
||||
return -1;
|
||||
}
|
||||
return sock;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void
|
||||
send_vibration(int strong, int weak, uint16_t duration_ms, uint16_t slot) {
|
||||
if (!fake_vibration_enabled())
|
||||
return;
|
||||
|
||||
int sock = connect_app_socket("droiddeck-rumble", SOCK_NONBLOCK);
|
||||
int sock = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
|
||||
if (sock < 0)
|
||||
return;
|
||||
|
||||
struct sockaddr_un addr = {};
|
||||
addr.sun_family = AF_UNIX;
|
||||
const char *name = "droiddeck-rumble";
|
||||
memcpy(addr.sun_path + 1, name, strlen(name));
|
||||
socklen_t addrlen = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(name);
|
||||
|
||||
if (connect(sock, reinterpret_cast<struct sockaddr *>(&addr), addrlen) < 0) {
|
||||
syscall(SYS_close, sock);
|
||||
return;
|
||||
}
|
||||
|
||||
uint16_t data[4];
|
||||
data[0] = static_cast<uint16_t>(strong);
|
||||
data[1] = static_cast<uint16_t>(weak);
|
||||
@@ -933,7 +927,6 @@ struct UinputWriter {
|
||||
std::vector<struct input_event> pending;
|
||||
uint32_t buttons = 0;
|
||||
int16_t axes[8] = {};
|
||||
int desktop = -1;
|
||||
};
|
||||
|
||||
static std::unordered_map<int, std::shared_ptr<UinputWriter>> &uinput_map() {
|
||||
@@ -970,95 +963,6 @@ __attribute__((visibility("hidden"))) static bool is_gamepad(const UinputDescrip
|
||||
test_bit(d.evbits, sizeof(d.evbits), EV_ABS) && test_bit(d.absbits, sizeof(d.absbits), ABS_X);
|
||||
}
|
||||
|
||||
static constexpr const char *DESKTOP_INPUT_SOCKET = "droiddeck-uinput";
|
||||
static constexpr uint32_t DESKTOP_INPUT_MAGIC = 0x4655444b;
|
||||
static constexpr int DESKTOP_INPUT_SEND_TIMEOUT_MS = 200;
|
||||
|
||||
struct DesktopInputHeader {
|
||||
uint32_t magic;
|
||||
int32_t abs_x_min, abs_x_max, abs_y_min, abs_y_max;
|
||||
};
|
||||
|
||||
struct DesktopInputEvent {
|
||||
uint16_t type;
|
||||
uint16_t code;
|
||||
int32_t value;
|
||||
};
|
||||
|
||||
static_assert(sizeof(DesktopInputHeader) == 20 && sizeof(DesktopInputEvent) == 8,
|
||||
"desktop input records must stay ABI-stable");
|
||||
|
||||
__attribute__((visibility("hidden"))) static bool has_keyboard_keys(const UinputDescription &d) {
|
||||
for (int code = KEY_ESC; code < BTN_MISC; code++)
|
||||
if (test_bit(d.keybits, sizeof(d.keybits), code)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static bool is_absolute_pointer(const UinputDescription &d) {
|
||||
return test_bit(d.evbits, sizeof(d.evbits), EV_ABS) && test_bit(d.absbits, sizeof(d.absbits), ABS_X) &&
|
||||
test_bit(d.absbits, sizeof(d.absbits), ABS_Y) &&
|
||||
(test_bit(d.keybits, sizeof(d.keybits), BTN_LEFT) || test_bit(d.keybits, sizeof(d.keybits), BTN_TOUCH)) &&
|
||||
d.absinfo[ABS_X].maximum > d.absinfo[ABS_X].minimum && d.absinfo[ABS_Y].maximum > d.absinfo[ABS_Y].minimum;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static bool is_desktop_input(const UinputDescription &d) {
|
||||
return test_bit(d.evbits, sizeof(d.evbits), EV_KEY) &&
|
||||
(has_keyboard_keys(d) || test_bit(d.keybits, sizeof(d.keybits), BTN_LEFT) || is_absolute_pointer(d));
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static bool send_all(int sock, const void *data, size_t size) {
|
||||
const auto *bytes = static_cast<const uint8_t *>(data);
|
||||
while (size > 0) {
|
||||
ssize_t sent = send(sock, bytes, size, MSG_NOSIGNAL);
|
||||
if (sent < 0 && errno == EINTR) continue;
|
||||
if (sent <= 0) return false;
|
||||
bytes += sent;
|
||||
size -= static_cast<size_t>(sent);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void close_desktop_input(UinputWriter &w) {
|
||||
if (w.desktop < 0) return;
|
||||
syscall(SYS_close, w.desktop);
|
||||
w.desktop = -1;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int connect_desktop_input(const UinputDescription &d) {
|
||||
int sock = connect_app_socket(DESKTOP_INPUT_SOCKET, 0);
|
||||
if (sock < 0) return -1;
|
||||
struct timeval timeout = {0, DESKTOP_INPUT_SEND_TIMEOUT_MS * 1000};
|
||||
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
|
||||
bool absolute = is_absolute_pointer(d);
|
||||
DesktopInputHeader header = {DESKTOP_INPUT_MAGIC,
|
||||
absolute ? d.absinfo[ABS_X].minimum : 0,
|
||||
absolute ? d.absinfo[ABS_X].maximum : 0,
|
||||
absolute ? d.absinfo[ABS_Y].minimum : 0,
|
||||
absolute ? d.absinfo[ABS_Y].maximum : 0};
|
||||
if (!send_all(sock, &header, sizeof(header))) {
|
||||
syscall(SYS_close, sock);
|
||||
return -1;
|
||||
}
|
||||
return sock;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void forward_desktop_input(UinputWriter &w) {
|
||||
if (w.desktop < 0 || w.pending.empty()) return;
|
||||
DesktopInputEvent events[64];
|
||||
size_t count = 0;
|
||||
for (const struct input_event &ev : w.pending) {
|
||||
events[count++] = {ev.type, ev.code, ev.value};
|
||||
if (count == sizeof(events) / sizeof(events[0]) || &ev == &w.pending.back()) {
|
||||
if (!send_all(w.desktop, events, count * sizeof(events[0]))) {
|
||||
Logger::log("uinput: \"%s\" lost the desktop compositor: %s\n", w.description.name, strerror(errno));
|
||||
close_desktop_input(w);
|
||||
return;
|
||||
}
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void unpublish_uinput(UinputWriter &w) {
|
||||
if (!w.published) return;
|
||||
__atomic_add_fetch(&w.ring->generation, 1, __ATOMIC_RELEASE);
|
||||
@@ -1154,7 +1058,6 @@ __attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w)
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static void flush_uinput(UinputWriter &w) {
|
||||
forward_desktop_input(w);
|
||||
if (!w.published || w.pending.empty()) {
|
||||
w.pending.clear();
|
||||
return;
|
||||
@@ -1246,7 +1149,6 @@ ioctl_uinput(UinputWriter &w, ioctl_request_t op, void *argp) {
|
||||
}
|
||||
if (number == _IOC_NR(UI_DEV_DESTROY)) {
|
||||
if (getpid() == w.owner) unpublish_uinput(w);
|
||||
close_desktop_input(w);
|
||||
w.created = false;
|
||||
return 0;
|
||||
}
|
||||
@@ -1290,13 +1192,8 @@ ioctl_uinput(UinputWriter &w, ioctl_request_t op, void *argp) {
|
||||
case _IOC_NR(UI_DEV_CREATE):
|
||||
w.created = true;
|
||||
if (!is_gamepad(d)) {
|
||||
if (is_desktop_input(d)) w.desktop = connect_desktop_input(d);
|
||||
if (w.desktop >= 0)
|
||||
Logger::log("uinput: \"%s\" %04x:%04x goes to the desktop compositor\n", d.name, d.id.vendor,
|
||||
d.id.product);
|
||||
else
|
||||
Logger::log("uinput: \"%s\" %04x:%04x is not a gamepad; its events are dropped\n", d.name,
|
||||
d.id.vendor, d.id.product);
|
||||
Logger::log("uinput: \"%s\" %04x:%04x is not a gamepad; its events are dropped\n", d.name,
|
||||
d.id.vendor, d.id.product);
|
||||
return 0;
|
||||
}
|
||||
if (publish_uinput(w) < 0) {
|
||||
@@ -1324,7 +1221,6 @@ __attribute__((visibility("hidden"))) static void close_uinput(int fd) {
|
||||
auto it = uinput_map().find(fd);
|
||||
if (it == uinput_map().end()) return;
|
||||
if (getpid() == it->second->owner) unpublish_uinput(*it->second);
|
||||
close_desktop_input(*it->second);
|
||||
uinput_map().erase(it);
|
||||
}
|
||||
|
||||
|
||||
@@ -3618,12 +3618,6 @@ static void deliver_pen(const struct input_msg *m) {
|
||||
|
||||
static void key_event(uint32_t evdev, int pressed);
|
||||
struct wl_resource *droiddeck_ime_target(void);
|
||||
static void deliver_scene_pointer(int x, int y) {
|
||||
int w, h;
|
||||
scene_size(&w, &h);
|
||||
pointer_event((double)x * w / INPUT_SPACE_W, (double)y * h / INPUT_SPACE_H, 0, 0);
|
||||
}
|
||||
|
||||
static void deliver_key(const struct input_msg *m) {
|
||||
key_event((uint32_t)m->p1, m->p2);
|
||||
}
|
||||
@@ -3774,7 +3768,6 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
|
||||
case 11: axis_event(m.p1, m.p2, 0); break;
|
||||
case 12: axis_event(m.p1, m.p2, 1); break;
|
||||
case 13: deliver_pen(&m); break;
|
||||
case 14: deliver_scene_pointer(m.p1, m.p2); break;
|
||||
case 20: stream_take(); break;
|
||||
case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
|
||||
case 22: schedule_render(); break;
|
||||
|
||||
@@ -166,14 +166,21 @@ object SteamTouchConfig {
|
||||
|
||||
fun steamRoot(context: Context) = com.droiddeck.launcher.session.SessionPrefs.activeSteamRoot(context)
|
||||
|
||||
private fun controllerConfigs(context: Context) = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
|
||||
|
||||
fun configDir(context: Context): File? {
|
||||
val base = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
|
||||
val base = controllerConfigs(context)
|
||||
val account = accountId(context)
|
||||
if (account != null) File(base, "$account/config").takeIf { it.isDirectory }?.let { return it }
|
||||
return base.listFiles()?.filter { it.name.all(Char::isDigit) && File(it, "config").isDirectory }
|
||||
?.maxByOrNull { it.lastModified() }?.let { File(it, "config") }
|
||||
}
|
||||
|
||||
private fun writableConfigDir(context: Context): File? {
|
||||
val account = accountId(context) ?: return configDir(context)
|
||||
return File(controllerConfigs(context), "$account/config").apply { mkdirs() }.takeIf { it.isDirectory }
|
||||
}
|
||||
|
||||
private fun accountId(context: Context): Long? = try {
|
||||
val users = KeyValues.parse(File(steamRoot(context), "config/loginusers.vdf").readText())
|
||||
val node = users.child("users")
|
||||
@@ -197,7 +204,7 @@ object SteamTouchConfig {
|
||||
}
|
||||
return try {
|
||||
val text = file.readText()
|
||||
val kv = KeyValues.parse(text.removePrefix(""))
|
||||
val kv = KeyValues.parse(text)
|
||||
val mappings = kv.child("controller_mappings") ?: kv
|
||||
val layouts = mappings.string("touch_layout")?.let { hex -> decodeLayouts(hexToBytes(hex)) }
|
||||
Log.i(TAG, "steam touch: app $appId uses ${file.path} (${layouts?.layouts?.size ?: 0} layouts)")
|
||||
@@ -389,8 +396,9 @@ object SteamTouchConfig {
|
||||
bindings: Map<SteamTouchBindings.Ref, (SteamTouchBindings.Binding) -> SteamTouchBindings.Binding> = emptyMap(),
|
||||
options: Options? = null,
|
||||
): File? {
|
||||
val dir = configDir(context) ?: return null
|
||||
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n" else return null
|
||||
val dir = writableConfigDir(context) ?: return null.also { Log.w(TAG, "steam touch: no controller config folder to save app $appId in") }
|
||||
val base = config.text ?: if (config.file == null && bindings.isEmpty()) "\"controller_mappings\"\n{\n\t\"controller_type\"\t\t\"controller_mobile_touch\"\n}\n"
|
||||
else return null.also { Log.w(TAG, "steam touch: ${config.file?.path ?: "default layout"} has no readable text to save into") }
|
||||
val source = bindings.entries.fold(base) { text, (ref, change) ->
|
||||
SteamTouchBindings.rewrite(text, ref, change) ?: text
|
||||
}
|
||||
@@ -408,11 +416,11 @@ object SteamTouchConfig {
|
||||
val existing = Regex("""\n\s*"touch_layout"\s+"[0-9a-fA-F]*"""")
|
||||
val text = if (existing.containsMatchIn(source)) source.replace(existing, "\n$line")
|
||||
else source.replaceFirst(Regex("""("controller_type"\s+"controller_mobile_touch"[^\n]*)"""), "$1\n$line")
|
||||
if (!text.contains("touch_layout")) return null
|
||||
if (!text.contains("touch_layout")) return null.also { Log.w(TAG, "steam touch: ${config.file?.path} is no controller_mobile_touch config") }
|
||||
target.parentFile?.mkdirs()
|
||||
val tmp = File(target.path + ".tmp")
|
||||
tmp.writeText(text)
|
||||
if (!tmp.renameTo(target)) return null
|
||||
if (!tmp.renameTo(target)) return null.also { Log.w(TAG, "steam touch: could not replace ${target.path}") }
|
||||
selectAutosave(dir, key)
|
||||
dropDeviceEntry(dir, key)
|
||||
Log.i(TAG, "steam touch: saved layouts ${sets.keys} for app $appId to ${target.path}")
|
||||
@@ -430,12 +438,13 @@ object SteamTouchConfig {
|
||||
|
||||
private fun selectAutosave(dir: File, key: String) {
|
||||
val file = File(dir, CONFIGSET)
|
||||
val text = if (file.isFile) file.readText() else "\"controller_config\"\n{\n}\n"
|
||||
val entry = "\t\"$key\"\n\t{\n\t\t\"autosave\"\t\t\"1\"\n\t}"
|
||||
val block = Regex("""\n\s*"${Regex.escape(key)}"\s*\{[^}]*\}""", RegexOption.IGNORE_CASE)
|
||||
val next = if (block.containsMatchIn(text)) text.replace(block) { "\n$entry" }
|
||||
else text.substring(0, text.lastIndexOf('}')).trimEnd() + "\n$entry\n}\n"
|
||||
File(file.path + ".tmp").apply { writeText(next) }.renameTo(file)
|
||||
val root = file.takeIf { it.isFile }?.readText()?.let(KeyValues::parse)?.takeIf { it.child("controller_config") != null }
|
||||
?: KeyValues.Node(mutableListOf("controller_config" to KeyValues.Node()))
|
||||
val config = root.child("controller_config") ?: return
|
||||
val entry = key to KeyValues.Node(mutableListOf("autosave" to "1"))
|
||||
val at = config.entries.indexOfFirst { it.first.equals(key, true) && it.second is KeyValues.Node }
|
||||
if (at >= 0) config.entries[at] = entry else config.entries += entry
|
||||
File(file.path + ".tmp").apply { writeText(KeyValues.write(root)) }.renameTo(file)
|
||||
}
|
||||
|
||||
|
||||
@@ -593,34 +602,48 @@ class KeyValues private constructor() {
|
||||
fun string(key: String): String? = entries.firstOrNull { it.first.equals(key, true) && it.second is String }?.second as String?
|
||||
}
|
||||
|
||||
private class Token(val text: String, val quoted: Boolean) {
|
||||
val opens get() = !quoted && text == "{"
|
||||
val closes get() = !quoted && text == "}"
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun write(node: Node): String = write(node, "")
|
||||
|
||||
private fun write(node: Node, indent: String): String = node.entries.joinToString("") { (key, value) ->
|
||||
if (value is Node) "$indent\"${escape(key)}\"\n$indent{\n${write(value, "$indent\t")}$indent}\n"
|
||||
else "$indent\"${escape(key)}\"\t\t\"${escape(value.toString())}\"\n"
|
||||
}
|
||||
|
||||
private fun escape(text: String) = text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\t", "\\t")
|
||||
|
||||
fun parse(text: String): Node {
|
||||
val tokens = tokenize(text)
|
||||
val tokens = tokenize(text.removePrefix("\uFEFF"))
|
||||
var i = 0
|
||||
fun node(): Node {
|
||||
val n = Node()
|
||||
while (i < tokens.size) {
|
||||
val t = tokens[i++]
|
||||
if (t == "}" ) return n
|
||||
if (t == "{") continue
|
||||
if (t.closes) return n
|
||||
if (t.opens) continue
|
||||
if (i >= tokens.size) break
|
||||
val next = tokens[i]
|
||||
if (next == "{") { i++; n.entries += t to node() } else { i++; n.entries += t to next }
|
||||
if (next.opens) { i++; n.entries += t.text to node() } else { i++; n.entries += t.text to next.text }
|
||||
}
|
||||
return n
|
||||
}
|
||||
return node()
|
||||
}
|
||||
|
||||
private fun tokenize(text: String): List<String> {
|
||||
val out = mutableListOf<String>()
|
||||
private fun tokenize(text: String): List<Token> {
|
||||
val out = mutableListOf<Token>()
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
when {
|
||||
c.isWhitespace() -> i++
|
||||
c == '/' && i + 1 < text.length && text[i + 1] == '/' -> while (i < text.length && text[i] != '\n') i++
|
||||
c == '{' || c == '}' -> { out += c.toString(); i++ }
|
||||
c == '{' || c == '}' -> { out += Token(c.toString(), false); i++ }
|
||||
c == '"' -> {
|
||||
val sb = StringBuilder()
|
||||
i++
|
||||
@@ -632,13 +655,13 @@ class KeyValues private constructor() {
|
||||
i++
|
||||
}
|
||||
i++
|
||||
out += sb.toString()
|
||||
out += Token(sb.toString(), true)
|
||||
}
|
||||
c == '[' -> { while (i < text.length && text[i] != ']') i++; i++ }
|
||||
else -> {
|
||||
val start = i
|
||||
while (i < text.length && !text[i].isWhitespace() && text[i] != '{' && text[i] != '}' && text[i] != '"') i++
|
||||
out += text.substring(start, i)
|
||||
out += Token(text.substring(start, i), false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.input.HeldInput
|
||||
import com.droiddeck.launcher.input.InputSpace
|
||||
|
||||
class DesktopUinputDevice(
|
||||
private val absX: IntRange?,
|
||||
private val absY: IntRange?,
|
||||
private val sink: Sink,
|
||||
private val keys: HeldInput,
|
||||
private val buttons: HeldInput,
|
||||
private val source: Int,
|
||||
) {
|
||||
interface Sink {
|
||||
fun key(code: Int, down: Boolean)
|
||||
fun button(code: Int, down: Boolean)
|
||||
fun motion(dx: Int, dy: Int)
|
||||
fun position(x: Int, y: Int)
|
||||
fun wheel(vertical120: Int, horizontal120: Int)
|
||||
}
|
||||
|
||||
private var dx = 0
|
||||
private var dy = 0
|
||||
private var x = -1
|
||||
private var y = -1
|
||||
private var moved = false
|
||||
private var wheel = 0
|
||||
private var hwheel = 0
|
||||
private var wheelHiRes = 0
|
||||
private var hwheelHiRes = 0
|
||||
private var sawWheelHiRes = false
|
||||
private var sawHwheelHiRes = false
|
||||
|
||||
fun event(type: Int, code: Int, value: Int) {
|
||||
when (type) {
|
||||
EV_SYN -> if (code == SYN_REPORT) report()
|
||||
EV_KEY -> if (value != KEY_REPEAT) key(code, value != 0)
|
||||
EV_REL -> relative(code, value)
|
||||
EV_ABS -> absolute(code, value)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
flushMotion()
|
||||
keys.release(source)
|
||||
buttons.release(source)
|
||||
}
|
||||
|
||||
private fun key(code: Int, down: Boolean) {
|
||||
val button = when {
|
||||
code in BTN_LEFT..BTN_TASK -> code
|
||||
code == BTN_TOUCH && absX != null -> BTN_LEFT
|
||||
else -> null
|
||||
}
|
||||
if (button != null) {
|
||||
flushMotion()
|
||||
buttons.set(source, button, down)
|
||||
return
|
||||
}
|
||||
if (code !in KEY_ESC until BTN_MISC && code !in KEY_OK..KEY_MAX) return
|
||||
flushMotion()
|
||||
keys.set(source, code, down)
|
||||
}
|
||||
|
||||
private fun relative(code: Int, value: Int) {
|
||||
when (code) {
|
||||
REL_X -> dx += value
|
||||
REL_Y -> dy += value
|
||||
REL_WHEEL -> wheel += value
|
||||
REL_HWHEEL -> hwheel += value
|
||||
REL_WHEEL_HI_RES -> { wheelHiRes += value; sawWheelHiRes = true }
|
||||
REL_HWHEEL_HI_RES -> { hwheelHiRes += value; sawHwheelHiRes = true }
|
||||
}
|
||||
}
|
||||
|
||||
private fun absolute(code: Int, value: Int) {
|
||||
when (code) {
|
||||
ABS_X -> absX?.let { x = scale(value, it, InputSpace.WIDTH); moved = true }
|
||||
ABS_Y -> absY?.let { y = scale(value, it, InputSpace.HEIGHT); moved = true }
|
||||
}
|
||||
}
|
||||
|
||||
private fun report() {
|
||||
flushMotion()
|
||||
val vertical = if (sawWheelHiRes) -wheelHiRes else -wheel * WHEEL_UNITS
|
||||
val horizontal = if (sawHwheelHiRes) hwheelHiRes else hwheel * WHEEL_UNITS
|
||||
wheel = 0
|
||||
hwheel = 0
|
||||
wheelHiRes = 0
|
||||
hwheelHiRes = 0
|
||||
if (vertical != 0 || horizontal != 0) sink.wheel(vertical, horizontal)
|
||||
}
|
||||
|
||||
private fun flushMotion() {
|
||||
if (dx != 0 || dy != 0) sink.motion(dx, dy)
|
||||
dx = 0
|
||||
dy = 0
|
||||
if (moved && x >= 0 && y >= 0) sink.position(x, y)
|
||||
moved = false
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EV_SYN = 0x00
|
||||
const val EV_KEY = 0x01
|
||||
const val EV_REL = 0x02
|
||||
const val EV_ABS = 0x03
|
||||
const val SYN_REPORT = 0
|
||||
const val KEY_REPEAT = 2
|
||||
const val KEY_ESC = 1
|
||||
const val BTN_MISC = 0x100
|
||||
const val BTN_LEFT = 0x110
|
||||
const val BTN_TASK = 0x117
|
||||
const val BTN_TOUCH = 0x14a
|
||||
const val KEY_OK = 0x160
|
||||
const val KEY_MAX = 0x2ff
|
||||
const val REL_X = 0x00
|
||||
const val REL_Y = 0x01
|
||||
const val REL_HWHEEL = 0x06
|
||||
const val REL_WHEEL = 0x08
|
||||
const val REL_WHEEL_HI_RES = 0x0b
|
||||
const val REL_HWHEEL_HI_RES = 0x0c
|
||||
const val ABS_X = 0x00
|
||||
const val ABS_Y = 0x01
|
||||
const val WHEEL_UNITS = 120
|
||||
|
||||
private fun scale(value: Int, range: IntRange, size: Int): Int =
|
||||
((value.toLong() - range.first) * (size - 1) / (range.last.toLong() - range.first))
|
||||
.toInt().coerceIn(0, size - 1)
|
||||
}
|
||||
}
|
||||
@@ -1228,7 +1228,6 @@ class SessionService : Service() {
|
||||
binds.addAll(gpuStats.binds())
|
||||
}
|
||||
if (controllersOn) components.add(RumbleComponent().also { it.attach(this) })
|
||||
if (SessionState.mode == MODE_DESKTOP) components.add(UinputDesktopComponent().also { it.attach(this) })
|
||||
val home = File(LinuxRuntime.rootDir(this), "root")
|
||||
File(home, "Storage").mkdirs()
|
||||
binds.add(Environment.getExternalStorageDirectory().path + ":/root/Storage")
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.net.LocalServerSocket
|
||||
import android.net.LocalSocket
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.core.SessionPart
|
||||
import com.droiddeck.launcher.input.HeldInput
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.BufferedInputStream
|
||||
import java.io.DataInputStream
|
||||
import java.io.EOFException
|
||||
import java.io.InputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
class UinputDesktopComponent : SessionPart() {
|
||||
@Volatile private var server: LocalServerSocket? = null
|
||||
private val clients = HashMap<LocalSocket, Int>()
|
||||
private val keys = HeldInput(CompositorSink::key)
|
||||
private val buttons = HeldInput(CompositorSink::button)
|
||||
|
||||
override fun start() {
|
||||
val s = try { LocalServerSocket(NAME) } catch (e: Exception) { Log.w(TAG, "uinput: no listener ($e)"); return }
|
||||
server = s
|
||||
Thread({
|
||||
while (server === s) {
|
||||
val client = try { s.accept() } catch (e: Exception) { break }
|
||||
if (runCatching { client.peerCredentials.uid }.getOrNull() !in setOf(android.os.Process.myUid(), 0)) {
|
||||
runCatching { client.close() }
|
||||
continue
|
||||
}
|
||||
val source = synchronized(clients) {
|
||||
if (server !== s) 0
|
||||
else Integer.lowestOneBit(clients.values.fold(0, Int::or).inv()).also { if (it != 0) clients[client] = it }
|
||||
}
|
||||
if (source == 0) {
|
||||
runCatching { client.close() }
|
||||
continue
|
||||
}
|
||||
Thread({ serve(client, source) }, "uinput-device").apply { isDaemon = true; start() }
|
||||
}
|
||||
}, "uinput-desktop").apply { isDaemon = true; start() }
|
||||
Log.i(TAG, "uinput: listening on @$NAME")
|
||||
}
|
||||
|
||||
override fun stop() {
|
||||
val s = server
|
||||
server = null
|
||||
runCatching { s?.close() }
|
||||
synchronized(clients) {
|
||||
clients.keys.forEach { runCatching { it.close() } }
|
||||
clients.clear()
|
||||
}
|
||||
}
|
||||
|
||||
private fun serve(client: LocalSocket, source: Int) {
|
||||
try {
|
||||
read(client.inputStream, CompositorSink, keys, buttons, source)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "uinput: device stream ended ($e)")
|
||||
} finally {
|
||||
synchronized(clients) { clients.remove(client) }
|
||||
runCatching { client.close() }
|
||||
}
|
||||
}
|
||||
|
||||
internal object CompositorSink : DesktopUinputDevice.Sink {
|
||||
override fun key(code: Int, down: Boolean) = WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
|
||||
override fun button(code: Int, down: Boolean) =
|
||||
WaylandCompositor.nativeSendSceneInput(WaylandCompositor.SCENE_BUTTON, code, if (down) 1 else 0)
|
||||
override fun motion(dx: Int, dy: Int) = WaylandCompositor.sendPointerDelta(dx, dy)
|
||||
override fun position(x: Int, y: Int) =
|
||||
WaylandCompositor.nativeSendSceneInput(WaylandCompositor.SCENE_POINTER_SCALED, x, y)
|
||||
override fun wheel(vertical120: Int, horizontal120: Int) =
|
||||
WaylandCompositor.nativeSendSceneInput(WaylandCompositor.SCENE_AXIS, vertical120, horizontal120)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
const val NAME = "droiddeck-uinput"
|
||||
const val MAGIC = 0x4655444b
|
||||
const val HEADER_BYTES = 20
|
||||
const val EVENT_BYTES = 8
|
||||
|
||||
internal fun read(stream: InputStream, sink: DesktopUinputDevice.Sink, keys: HeldInput, buttons: HeldInput, source: Int) {
|
||||
val input = DataInputStream(BufferedInputStream(stream))
|
||||
val header = ByteArray(HEADER_BYTES)
|
||||
input.readFully(header)
|
||||
val h = ByteBuffer.wrap(header).order(ByteOrder.LITTLE_ENDIAN)
|
||||
if (h.int != MAGIC) return
|
||||
val xMin = h.int
|
||||
val xMax = h.int
|
||||
val yMin = h.int
|
||||
val yMax = h.int
|
||||
val device = DesktopUinputDevice(
|
||||
if (xMax > xMin) xMin..xMax else null,
|
||||
if (yMax > yMin) yMin..yMax else null,
|
||||
sink,
|
||||
keys,
|
||||
buttons,
|
||||
source,
|
||||
)
|
||||
val event = ByteArray(EVENT_BYTES)
|
||||
val e = ByteBuffer.wrap(event).order(ByteOrder.LITTLE_ENDIAN)
|
||||
try {
|
||||
while (true) {
|
||||
try { input.readFully(event) } catch (end: EOFException) { return }
|
||||
device.event(e.getShort(0).toInt() and 0xFFFF, e.getShort(2).toInt() and 0xFFFF, e.getInt(4))
|
||||
}
|
||||
} finally {
|
||||
device.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -333,8 +333,7 @@ public final class WaylandCompositor {
|
||||
|
||||
public static native void nativeSendSceneInput(int type, int a, int b);
|
||||
|
||||
public static final int SCENE_BUTTON = 3, SCENE_WHEEL = 4, SCENE_POINTER_DELTA = 6, SCENE_AXIS = 11, SCENE_AXIS_FINGER = 12,
|
||||
SCENE_POINTER_SCALED = 14;
|
||||
public static final int SCENE_BUTTON = 3, SCENE_WHEEL = 4, SCENE_POINTER_DELTA = 6, SCENE_AXIS = 11, SCENE_AXIS_FINGER = 12;
|
||||
public static final int WHEEL_STEP_UNITS = 120, POINTER_DELTA_SCALE = 256;
|
||||
|
||||
public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1;
|
||||
|
||||
@@ -60,6 +60,117 @@ class SteamTouchConfigFilesTest {
|
||||
|
||||
private val template get() = File(steam, "controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf")
|
||||
|
||||
private fun login() = File(steam, "config/loginusers.vdf").apply { parentFile!!.mkdirs() }
|
||||
.writeText("\"users\"\n{\n\t\"76561197960265851\"\n\t{\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
|
||||
|
||||
private fun saveDefault(app: Int): File? {
|
||||
val elements = listOf(SteamTouchConfig.Element(SteamTouchConfig.A, true, 0.5f, 0.6f))
|
||||
return SteamTouchConfig.saveLayouts(context, app, SteamTouchConfig.load(context, app), mapOf(1 to elements))
|
||||
}
|
||||
|
||||
private fun assertSavedA(app: Int, saved: File?) {
|
||||
val loaded = SteamTouchConfig.load(context, app)
|
||||
assertEquals(saved, loaded.file)
|
||||
val a = SteamTouchConfig.elementsFor(loaded, 1, emptyList()).first { it.type == SteamTouchConfig.A }
|
||||
assertEquals(0.5f, a.x, 0.002f)
|
||||
assertEquals(0.6f, a.y, 0.002f)
|
||||
}
|
||||
|
||||
@Test fun savesWhenSteamHasNotCreatedTheAccountsControllerFolder() {
|
||||
File(steam, "steamapps/common/Steam Controller Configs").deleteRecursively()
|
||||
login()
|
||||
val saved = saveDefault(413150)
|
||||
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun savesIntoTheSignedInAccountNotAnotherAccountsFolder() {
|
||||
dir.parentFile!!.deleteRecursively()
|
||||
val other = File(steam, "steamapps/common/Steam Controller Configs/456/config").apply { mkdirs() }
|
||||
login()
|
||||
val saved = saveDefault(413150)
|
||||
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
|
||||
assertFalse(File(other, "413150").exists())
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun withoutAnAccountOrControllerFolderNothingIsWritten() {
|
||||
File(steam, "steamapps/common/Steam Controller Configs").deleteRecursively()
|
||||
assertEquals(null, saveDefault(413150))
|
||||
assertFalse(File(steam, "steamapps/common/Steam Controller Configs").exists())
|
||||
}
|
||||
|
||||
@Test fun anEmptyConfigsetIsRebuiltInsteadOfFailingTheSave() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf").writeText("")
|
||||
val saved = saveDefault(413150)
|
||||
assertEquals(File(dir, "413150/controller_mobile_touch.vdf"), saved)
|
||||
assertTrue(File(dir, "configset_controller_mobile_touch.vdf").readText().contains("\"413150\""))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aConfigsetWithOnlyAQuotedBraceIsRebuilt() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\" \"{\"\n")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun anExistingConfigsetKeepsItsOtherEntries() {
|
||||
configset("configset_controller_mobile_touch.vdf", "8400" to "\"workshop\"\t\t\"7\"")
|
||||
saveDefault(413150)
|
||||
val text = File(dir, "configset_controller_mobile_touch.vdf").readText()
|
||||
assertTrue(text.contains("\"8400\""))
|
||||
assertTrue(text.contains("\"413150\""))
|
||||
}
|
||||
|
||||
private fun withBom(name: String) = File(dir, name).apply { writeText("\uFEFF" + readText()) }
|
||||
|
||||
@Test fun aConfigsetWithAByteOrderMarkKeepsItsOtherEntries() {
|
||||
configset("configset_controller_mobile_touch.vdf", "8400" to "\"workshop\"\t\t\"7\"")
|
||||
withBom("configset_controller_mobile_touch.vdf")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertEquals("7", root?.child("8400")?.string("workshop"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aWorkshopPickInAConfigsetWithAByteOrderMarkIsRead() {
|
||||
val picked = workshop("42", "community")
|
||||
configset("configset_controller_mobile_touch.vdf", "413150" to "\"workshop\"\t\t\"42\"")
|
||||
withBom("configset_controller_mobile_touch.vdf")
|
||||
assertEquals(picked, SteamTouchConfig.load(context, 413150).file)
|
||||
}
|
||||
|
||||
@Test fun aConfigsetMissingItsRootBraceGetsTheEntryAtTheRoot() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf")
|
||||
.writeText("\"controller_config\"\n{\n\t\"8400\"\n\t{\n\t\t\"workshop\"\t\t\"7\"\n\t}\n")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertEquals("7", root?.child("8400")?.string("workshop"))
|
||||
assertEquals(null, root?.child("8400")?.child("413150"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aConfigsetCutOffAfterAKeyGetsTheEntryAtTheRoot() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\"\n{\n\t\"8400\"\n\t{\n\t\t\"workshop\"")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertEquals(null, root?.child("8400")?.child("413150"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aConfigsetWhoseRootIsAQuotedValueIsRebuilt() {
|
||||
File(dir, "configset_controller_mobile_touch.vdf").writeText("\"controller_config\" \"{}\"\n")
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
private fun shortcut(name: String): Int {
|
||||
val shortcut = 2702387189L.toInt()
|
||||
template.apply { parentFile!!.mkdirs(); writeText(touch("Gamepad with Joystick")) }
|
||||
@@ -67,8 +178,7 @@ class SteamTouchConfigFilesTest {
|
||||
"!! Controller 0 attributes:\n Type: 43\n" +
|
||||
"Loaded Config for Last Resort Path for App ID 2702387189, Controller 0: /root/.local/share/Steam//controller_base/templates/controller_mobile_touch_gamepad_joystick.vdf\n",
|
||||
)
|
||||
File(steam, "config/loginusers.vdf").apply { parentFile!!.mkdirs() }
|
||||
.writeText("\"users\"\n{\n\t\"76561197960265851\"\n\t{\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n")
|
||||
login()
|
||||
val vdf = java.io.ByteArrayOutputStream().apply {
|
||||
write("\u0000shortcuts\u0000\u00000\u0000\u0002appid\u0000".toByteArray())
|
||||
write(java.nio.ByteBuffer.allocate(4).order(java.nio.ByteOrder.LITTLE_ENDIAN).putInt(shortcut).array())
|
||||
@@ -89,6 +199,16 @@ class SteamTouchConfigFilesTest {
|
||||
assertEquals(saved, SteamTouchConfig.load(context, shortcut).file)
|
||||
}
|
||||
|
||||
@Test fun aSavedShortcutNameWithBracesDoesNotHideTheNextAppsEntry() {
|
||||
val shortcut = shortcut("Game {")
|
||||
SteamTouchConfig.saveLayouts(context, shortcut, SteamTouchConfig.load(context, shortcut), mapOf(1 to emptyList()))
|
||||
val saved = saveDefault(413150)
|
||||
val root = KeyValues.parse(File(dir, "configset_controller_mobile_touch.vdf").readText()).child("controller_config")
|
||||
assertEquals("1", root?.child("game {")?.string("autosave"))
|
||||
assertEquals("1", root?.child("413150")?.string("autosave"))
|
||||
assertSavedA(413150, saved)
|
||||
}
|
||||
|
||||
@Test fun aShortcutNameThatIsNoPlainFolderNameUsesTheAppId() {
|
||||
for (name in listOf("../escape", "a/b", "..", "Tab\tName")) {
|
||||
assertEquals(name, "2702387189", SteamTouchConfig.steamKey(context, shortcut(name)))
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import com.droiddeck.launcher.input.HeldInput
|
||||
import com.droiddeck.launcher.input.InputSpace
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.ABS_X
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.ABS_Y
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.BTN_LEFT
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.BTN_TOUCH
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.EV_ABS
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.EV_KEY
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.EV_REL
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.EV_SYN
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.REL_HWHEEL
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.REL_WHEEL
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.REL_WHEEL_HI_RES
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.REL_X
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.REL_Y
|
||||
import com.droiddeck.launcher.session.DesktopUinputDevice.Companion.SYN_REPORT
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
class UinputDesktopComponentTest {
|
||||
private class Recorder : DesktopUinputDevice.Sink {
|
||||
val calls = ArrayList<String>()
|
||||
override fun key(code: Int, down: Boolean) { calls.add("key $code $down") }
|
||||
override fun button(code: Int, down: Boolean) { calls.add("button $code $down") }
|
||||
override fun motion(dx: Int, dy: Int) { calls.add("motion $dx $dy") }
|
||||
override fun position(x: Int, y: Int) { calls.add("position $x $y") }
|
||||
override fun wheel(vertical120: Int, horizontal120: Int) { calls.add("wheel $vertical120 $horizontal120") }
|
||||
}
|
||||
|
||||
private fun stream(xMin: Int, xMax: Int, yMin: Int, yMax: Int, vararg events: IntArray, magic: Int = UinputDesktopComponent.MAGIC): ByteArrayInputStream {
|
||||
val b = ByteBuffer.allocate(UinputDesktopComponent.HEADER_BYTES + events.size * UinputDesktopComponent.EVENT_BYTES)
|
||||
.order(ByteOrder.LITTLE_ENDIAN)
|
||||
b.putInt(magic).putInt(xMin).putInt(xMax).putInt(yMin).putInt(yMax)
|
||||
events.forEach { b.putShort(it[0].toShort()).putShort(it[1].toShort()).putInt(it[2]) }
|
||||
return ByteArrayInputStream(b.array())
|
||||
}
|
||||
|
||||
private fun read(stream: ByteArrayInputStream, r: Recorder) =
|
||||
UinputDesktopComponent.read(stream, r, HeldInput(r::key), HeldInput(r::button), 1)
|
||||
|
||||
private fun ev(type: Int, code: Int, value: Int) = intArrayOf(type, code, value)
|
||||
private val syn = ev(EV_SYN, SYN_REPORT, 0)
|
||||
|
||||
@Test fun keyboardKeysReachTheCompositorAndRepeatsAreLeftToIt() {
|
||||
val r = Recorder()
|
||||
read(stream(0, 0, 0, 0, ev(EV_KEY, 30, 1), syn, ev(EV_KEY, 30, 2), syn, ev(EV_KEY, 30, 0), syn), r)
|
||||
assertEquals(listOf("key 30 true", "key 30 false"), r.calls)
|
||||
}
|
||||
|
||||
@Test fun relativeMouseMovesBeforeItClicksAndScrollsInWaylandDirection() {
|
||||
val r = Recorder()
|
||||
read(stream(0, 0, 0, 0,
|
||||
ev(EV_REL, REL_X, 5), ev(EV_REL, REL_Y, -3), ev(EV_REL, REL_X, 2), ev(EV_KEY, BTN_LEFT, 1), syn,
|
||||
ev(EV_KEY, BTN_LEFT, 0), syn,
|
||||
ev(EV_REL, REL_WHEEL, 1), ev(EV_REL, REL_HWHEEL, -1), syn), r)
|
||||
assertEquals(listOf("motion 7 -3", "button $BTN_LEFT true", "button $BTN_LEFT false", "wheel -120 -120"), r.calls)
|
||||
}
|
||||
|
||||
@Test fun highResolutionWheelIsNotCountedTwice() {
|
||||
val r = Recorder()
|
||||
read(stream(0, 0, 0, 0,
|
||||
ev(EV_REL, REL_WHEEL_HI_RES, 60), syn,
|
||||
ev(EV_REL, REL_WHEEL_HI_RES, 60), ev(EV_REL, REL_WHEEL, 1), syn), r)
|
||||
assertEquals(listOf("wheel -60 0", "wheel -60 0"), r.calls)
|
||||
}
|
||||
|
||||
@Test fun absoluteMouseScalesItsRangeToTheInputSpace() {
|
||||
val r = Recorder()
|
||||
read(stream(0, 19200, 0, 12000,
|
||||
ev(EV_ABS, ABS_X, 0), ev(EV_ABS, ABS_Y, 0), syn,
|
||||
ev(EV_ABS, ABS_X, 19200), ev(EV_ABS, ABS_Y, 12000), ev(EV_KEY, BTN_TOUCH, 1), syn,
|
||||
ev(EV_ABS, ABS_X, 40000), syn), r)
|
||||
assertEquals(listOf("position 0 0", "position ${InputSpace.WIDTH - 1} ${InputSpace.HEIGHT - 1}",
|
||||
"button $BTN_LEFT true", "position ${InputSpace.WIDTH - 1} ${InputSpace.HEIGHT - 1}",
|
||||
"button $BTN_LEFT false"), r.calls)
|
||||
}
|
||||
|
||||
@Test fun absoluteAxesAndTouchAreIgnoredWithoutAPointerRange() {
|
||||
val r = Recorder()
|
||||
read(stream(0, 0, 0, 0, ev(EV_ABS, ABS_X, 100), ev(EV_ABS, ABS_Y, 100), ev(EV_KEY, BTN_TOUCH, 1), syn), r)
|
||||
assertEquals(emptyList<String>(), r.calls)
|
||||
}
|
||||
|
||||
@Test fun gamepadButtonsAreNotTurnedIntoKeys() {
|
||||
val r = Recorder()
|
||||
read(stream(0, 0, 0, 0, ev(EV_KEY, 0x130, 1), ev(EV_KEY, 0x13c, 1), syn), r)
|
||||
assertEquals(emptyList<String>(), r.calls)
|
||||
}
|
||||
|
||||
@Test fun aClosedDeviceReleasesWhatItHeld() {
|
||||
val r = Recorder()
|
||||
read(stream(0, 0, 0, 0, ev(EV_KEY, 42, 1), ev(EV_KEY, 0x111, 1), syn), r)
|
||||
assertEquals(listOf("key 42 true", "button 273 true", "key 42 false", "button 273 false"), r.calls)
|
||||
}
|
||||
|
||||
@Test fun aKeyOrButtonHeldByTwoDevicesIsReleasedOnlyWhenBothLetGo() {
|
||||
val r = Recorder()
|
||||
val keys = HeldInput(r::key)
|
||||
val buttons = HeldInput(r::button)
|
||||
val keyboard = DesktopUinputDevice(null, null, r, keys, buttons, 1)
|
||||
val mouse = DesktopUinputDevice(null, null, r, keys, buttons, 2)
|
||||
keyboard.event(EV_KEY, 42, 1)
|
||||
mouse.event(EV_KEY, 42, 1)
|
||||
keyboard.event(EV_KEY, BTN_LEFT, 1)
|
||||
mouse.event(EV_KEY, BTN_LEFT, 1)
|
||||
keyboard.event(EV_KEY, 42, 0)
|
||||
keyboard.release()
|
||||
assertEquals(listOf("key 42 true", "button $BTN_LEFT true"), r.calls)
|
||||
mouse.release()
|
||||
assertEquals(listOf("key 42 true", "button $BTN_LEFT true", "key 42 false", "button $BTN_LEFT false"), r.calls)
|
||||
}
|
||||
|
||||
@Test fun sharedHoldsPassASingleDeviceThroughUnchanged() {
|
||||
val direct = Recorder()
|
||||
val shared = Recorder()
|
||||
val events = arrayOf(ev(EV_KEY, 30, 1), syn, ev(EV_KEY, 30, 0), ev(EV_REL, REL_X, 4), ev(EV_KEY, BTN_LEFT, 1), syn,
|
||||
ev(EV_KEY, BTN_LEFT, 0), ev(EV_REL, REL_WHEEL, 1), syn, ev(EV_KEY, 42, 1), syn)
|
||||
read(stream(0, 0, 0, 0, *events), direct)
|
||||
val keys = HeldInput(shared::key)
|
||||
val buttons = HeldInput(shared::button)
|
||||
DesktopUinputDevice(null, null, Recorder(), keys, buttons, 1).event(EV_KEY, 50, 1)
|
||||
UinputDesktopComponent.read(stream(0, 0, 0, 0, *events), shared, keys, buttons, 2)
|
||||
assertEquals(listOf("key 50 true") + direct.calls, shared.calls)
|
||||
}
|
||||
|
||||
@Test fun sharedHoldsDropReleasesNothingHeld() {
|
||||
val r = Recorder()
|
||||
val keys = HeldInput(r::key)
|
||||
val buttons = HeldInput(r::button)
|
||||
val keyboard = DesktopUinputDevice(null, null, r, keys, buttons, 1)
|
||||
val mouse = DesktopUinputDevice(null, null, r, keys, buttons, 2)
|
||||
keyboard.event(EV_KEY, 30, 0)
|
||||
mouse.event(EV_KEY, BTN_LEFT, 0)
|
||||
keyboard.event(EV_KEY, 30, 1)
|
||||
mouse.event(EV_KEY, 30, 0)
|
||||
mouse.release()
|
||||
keyboard.event(EV_KEY, 30, 0)
|
||||
keyboard.event(EV_KEY, 30, 0)
|
||||
assertEquals(listOf("key 30 true", "key 30 false"), r.calls)
|
||||
}
|
||||
|
||||
@Test fun aStreamWithoutTheHeaderIsIgnored() {
|
||||
val r = Recorder()
|
||||
read(stream(0, 0, 0, 0, ev(EV_KEY, 30, 1), syn, magic = 0x1234), r)
|
||||
assertEquals(emptyList<String>(), r.calls)
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
|
||||
MAGIC = 0x4655444B
|
||||
EV_SYN, EV_KEY, EV_REL, EV_ABS = 0, 1, 2, 3
|
||||
KEY_A, BTN_LEFT, REL_X = 30, 0x110, 0
|
||||
|
||||
PROGRAM = r"""
|
||||
#include <fcntl.h>
|
||||
#include <linux/uinput.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int emit(int fd, int type, int code, int value) {
|
||||
struct input_event ev;
|
||||
memset(&ev, 0, sizeof(ev));
|
||||
ev.type = type;
|
||||
ev.code = code;
|
||||
ev.value = value;
|
||||
return write(fd, &ev, sizeof(ev)) == sizeof(ev) ? 0 : -1;
|
||||
}
|
||||
|
||||
static int make(const char *name, const int *evs, const int *keys, const int *abses, int max) {
|
||||
int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
|
||||
if (fd < 0) return -1;
|
||||
for (; *evs >= 0; evs++) ioctl(fd, UI_SET_EVBIT, *evs);
|
||||
for (; *keys >= 0; keys++) ioctl(fd, UI_SET_KEYBIT, *keys);
|
||||
for (; *abses >= 0; abses++) {
|
||||
struct uinput_abs_setup abs;
|
||||
memset(&abs, 0, sizeof(abs));
|
||||
abs.code = *abses;
|
||||
abs.absinfo.maximum = max;
|
||||
ioctl(fd, UI_SET_ABSBIT, *abses);
|
||||
ioctl(fd, UI_ABS_SETUP, &abs);
|
||||
}
|
||||
struct uinput_setup setup;
|
||||
memset(&setup, 0, sizeof(setup));
|
||||
setup.id.bustype = BUS_USB;
|
||||
setup.id.vendor = 0x1209;
|
||||
strncpy(setup.name, name, sizeof(setup.name) - 1);
|
||||
if (ioctl(fd, UI_DEV_SETUP, &setup) < 0 || ioctl(fd, UI_DEV_CREATE) < 0) return -1;
|
||||
return fd;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
static const int none[] = {-1};
|
||||
static const int key_ev[] = {EV_KEY, -1}, rel_ev[] = {EV_KEY, EV_REL, -1}, abs_ev[] = {EV_KEY, EV_ABS, -1};
|
||||
static const int abs_only[] = {EV_ABS, -1}, pad_ev[] = {EV_KEY, EV_ABS, -1};
|
||||
static const int keyboard[] = {KEY_A, KEY_LEFTSHIFT, -1}, mouse[] = {BTN_LEFT, BTN_RIGHT, -1};
|
||||
static const int pad_keys[] = {BTN_SOUTH, BTN_EAST, -1}, xy[] = {ABS_X, ABS_Y, -1}, xyz[] = {ABS_X, ABS_Y, ABS_Z, -1};
|
||||
|
||||
int kbd = make("test Keyboard", key_ev, keyboard, none, 0);
|
||||
if (kbd < 0 || emit(kbd, EV_KEY, KEY_A, 1) || emit(kbd, EV_SYN, SYN_REPORT, 0)) return 1;
|
||||
close(kbd);
|
||||
|
||||
int rel = make("test Mouse", rel_ev, mouse, none, 0);
|
||||
if (rel < 0 || emit(rel, EV_REL, REL_X, 7) || emit(rel, EV_KEY, BTN_LEFT, 1) || emit(rel, EV_SYN, SYN_REPORT, 0)) return 2;
|
||||
ioctl(rel, UI_DEV_DESTROY);
|
||||
close(rel);
|
||||
|
||||
int abs = make("test Mouse (Absolute)", abs_ev, mouse, xy, 19200);
|
||||
if (abs < 0 || emit(abs, EV_ABS, ABS_X, 9600) || emit(abs, EV_SYN, SYN_REPORT, 0)) return 3;
|
||||
close(abs);
|
||||
|
||||
int sensor = make("test Motion Sensors", abs_only, none, xyz, 32767);
|
||||
if (sensor < 0 || emit(sensor, EV_ABS, ABS_X, 5) || emit(sensor, EV_SYN, SYN_REPORT, 0)) return 4;
|
||||
close(sensor);
|
||||
|
||||
int pad = make("test Gamepad", pad_ev, pad_keys, xy, 32767);
|
||||
if (pad < 0 || emit(pad, EV_KEY, BTN_SOUTH, 1) || emit(pad, EV_SYN, SYN_REPORT, 0)) return 5;
|
||||
char ring[4096];
|
||||
snprintf(ring, sizeof(ring), "%s/.uinput-event16", getenv("FAKE_EVDEV_DIR"));
|
||||
if (access(ring, F_OK) != 0) return 6;
|
||||
snprintf(ring, sizeof(ring), "%s/.uinput-event17", getenv("FAKE_EVDEV_DIR"));
|
||||
if (access(ring, F_OK) == 0) return 7;
|
||||
close(pad);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "linux" and shutil.which("g++") and shutil.which("gcc"), "needs Linux, gcc and g++")
|
||||
class FakeinputDesktopUinputTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.addClassCleanup(shutil.rmtree, cls.tmp, True)
|
||||
cls.library = cls.tmp / "libfakeinput.so"
|
||||
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread", "-std=c++17",
|
||||
"-static-libstdc++", "-static-libgcc", "-Wl,--exclude-libs,ALL", "-o", str(cls.library),
|
||||
str(SOURCE), "-ldl"], check=True)
|
||||
cls.program = cls.tmp / "program"
|
||||
(cls.tmp / "program.c").write_text(PROGRAM)
|
||||
subprocess.run(["gcc", "-o", str(cls.program), str(cls.tmp / "program.c")], check=True)
|
||||
|
||||
def run_program(self):
|
||||
hooks = Path(tempfile.mkdtemp(dir=self.tmp))
|
||||
env = dict(os.environ, LD_PRELOAD=str(self.library), FAKE_EVDEV_DIR=str(hooks), FAKE_EVDEV_UINPUT="1")
|
||||
run = subprocess.run([str(self.program)], env=env, capture_output=True, timeout=10)
|
||||
self.assertEqual(run.returncode, 0, run.stderr)
|
||||
|
||||
def devices(self):
|
||||
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.addCleanup(server.close)
|
||||
try:
|
||||
server.bind("\0droiddeck-uinput")
|
||||
except OSError:
|
||||
self.skipTest("the desktop input socket name is taken on this machine")
|
||||
server.listen(16)
|
||||
server.settimeout(5)
|
||||
got = []
|
||||
|
||||
def accept():
|
||||
while True:
|
||||
try:
|
||||
client, _ = server.accept()
|
||||
except OSError:
|
||||
return
|
||||
with client:
|
||||
data = b""
|
||||
while chunk := client.recv(4096):
|
||||
data += chunk
|
||||
got.append(data)
|
||||
|
||||
reader = threading.Thread(target=accept, daemon=True)
|
||||
reader.start()
|
||||
self.run_program()
|
||||
server.settimeout(0.5)
|
||||
reader.join(10)
|
||||
return got
|
||||
|
||||
@staticmethod
|
||||
def decode(data):
|
||||
header = struct.unpack_from("<Iiiii", data)
|
||||
events = [struct.unpack_from("<HHi", data, 20 + i * 8) for i in range((len(data) - 20) // 8)]
|
||||
return header, events
|
||||
|
||||
def test_keyboard_and_mice_reach_the_app_while_sensors_and_gamepads_do_not(self):
|
||||
got = self.devices()
|
||||
self.assertEqual(len(got), 3)
|
||||
decoded = [self.decode(d) for d in got]
|
||||
self.assertEqual(decoded[0], ((MAGIC, 0, 0, 0, 0), [(EV_KEY, KEY_A, 1), (EV_SYN, 0, 0)]))
|
||||
self.assertEqual(decoded[1], ((MAGIC, 0, 0, 0, 0), [(EV_REL, REL_X, 7), (EV_KEY, BTN_LEFT, 1), (EV_SYN, 0, 0)]))
|
||||
self.assertEqual(decoded[2], ((MAGIC, 0, 19200, 0, 19200), [(EV_ABS, 0, 9600), (EV_SYN, 0, 0)]))
|
||||
|
||||
def test_without_the_app_listening_devices_still_work(self):
|
||||
self.run_program()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user