Compare commits

...
8 changed files with 685 additions and 12 deletions

No files matched your search

+115 -11
View File
@@ -438,25 +438,31 @@ __attribute__((constructor)) static void library_init() {
controller_map();
}
__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 = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
__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;
return -1;
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;
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);
if (sock < 0)
return;
uint16_t data[4];
data[0] = static_cast<uint16_t>(strong);
@@ -927,6 +933,7 @@ 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() {
@@ -963,6 +970,95 @@ __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);
@@ -1058,6 +1154,7 @@ __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;
@@ -1149,6 +1246,7 @@ 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;
}
@@ -1192,8 +1290,13 @@ ioctl_uinput(UinputWriter &w, ioctl_request_t op, void *argp) {
case _IOC_NR(UI_DEV_CREATE):
w.created = true;
if (!is_gamepad(d)) {
Logger::log("uinput: \"%s\" %04x:%04x is not a gamepad; its events are dropped\n", d.name,
d.id.vendor, d.id.product);
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);
return 0;
}
if (publish_uinput(w) < 0) {
@@ -1221,6 +1324,7 @@ __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,6 +3618,12 @@ 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);
}
@@ -3768,6 +3774,7 @@ 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;
@@ -0,0 +1,130 @@
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,6 +1228,7 @@ 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")
@@ -0,0 +1,115 @@
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,7 +333,8 @@ 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;
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 WHEEL_STEP_UNITS = 120, POINTER_DELTA_SCALE = 256;
public static final int FG_ENGINE_LSFG = 0, FG_ENGINE_DDFG = 1;
@@ -0,0 +1,152 @@
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)
}
}
@@ -0,0 +1,163 @@
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()