Rename the app SteamDeck → DroidDeck

App name, app ID and code package: DroidDeck, com.droiddeck.launcher
(sources moved to com/droiddeck/launcher, the 68 JNI functions renamed
with them). The new app ID installs beside SteamDeck rather than over it.

Everywhere the name was the app's own: the sidebar title, the session
report, share zips, the shell title, wake-lock and log tags, User-Agents,
the Compose theme, the Download folder and switch files (droiddeck-env,
-osc, -driver, -tu-debug, -no-pad, -pad-log, -no-hud, -wlr-renderer; the
old names are not read), and inside the runtime (droiddeck-desktop,
Firefox's droiddeck.js, the shortcuts tag, the rumble socket, debug and
cache paths). Build scripts, CI artifact (droiddeck-apk), CMake project,
README and the progress log follow.

Kept on purpose: Valve's Steam Deck (the -steamdeck flag,
steamdeck_publicbeta/stable, 'Steam Deck mode', the steamos.cloud
package URLs) and names inside the hosted desktop package (steamdeck.png,
steamdeck-steam, steamdeck-bigpicture). 'Desktop installed' now tests for
labwc instead of the launcher the app stages itself. A committed
__pycache__ .pyc is removed.
This commit is contained in:
The412Banner committed 2026-09-23 18:28:04 -04:00
1 parent a19dfb88a0
commit d160f464b6
118 files changed
+498 -487

No files matched your search

@@ -0,0 +1,109 @@
package com.droiddeck.launcher.input;
import android.view.KeyEvent;
/**
* Android key codes to Linux evdev codes, for the keys we inject into the compositor's
* wl_keyboard. A hardware keyboard is how an account name and password are typed on the client's
* first run, so this matters before any game does.
*
* <p>evdev's order is not alphabetical: the numbers are the physical positions of a PC keyboard,
* which is what the compositor's xkb keymap is written against. Table taken from Bannerlator's
* Wayland path unchanged.
*/
public final class EvdevKeys {
private EvdevKeys() {}
public static int fromKeyCode(int kc) {
switch (kc) {
// Letters (evdev order is NOT alphabetical)
case KeyEvent.KEYCODE_A: return 30; case KeyEvent.KEYCODE_B: return 48;
case KeyEvent.KEYCODE_C: return 46; case KeyEvent.KEYCODE_D: return 32;
case KeyEvent.KEYCODE_E: return 18; case KeyEvent.KEYCODE_F: return 33;
case KeyEvent.KEYCODE_G: return 34; case KeyEvent.KEYCODE_H: return 35;
case KeyEvent.KEYCODE_I: return 23; case KeyEvent.KEYCODE_J: return 36;
case KeyEvent.KEYCODE_K: return 37; case KeyEvent.KEYCODE_L: return 38;
case KeyEvent.KEYCODE_M: return 50; case KeyEvent.KEYCODE_N: return 49;
case KeyEvent.KEYCODE_O: return 24; case KeyEvent.KEYCODE_P: return 25;
case KeyEvent.KEYCODE_Q: return 16; case KeyEvent.KEYCODE_R: return 19;
case KeyEvent.KEYCODE_S: return 31; case KeyEvent.KEYCODE_T: return 20;
case KeyEvent.KEYCODE_U: return 22; case KeyEvent.KEYCODE_V: return 47;
case KeyEvent.KEYCODE_W: return 17; case KeyEvent.KEYCODE_X: return 45;
case KeyEvent.KEYCODE_Y: return 21; case KeyEvent.KEYCODE_Z: return 44;
// Digit row
case KeyEvent.KEYCODE_1: return 2; case KeyEvent.KEYCODE_2: return 3;
case KeyEvent.KEYCODE_3: return 4; case KeyEvent.KEYCODE_4: return 5;
case KeyEvent.KEYCODE_5: return 6; case KeyEvent.KEYCODE_6: return 7;
case KeyEvent.KEYCODE_7: return 8; case KeyEvent.KEYCODE_8: return 9;
case KeyEvent.KEYCODE_9: return 10; case KeyEvent.KEYCODE_0: return 11;
// Whitespace / edit
case KeyEvent.KEYCODE_ENTER: return 28; case KeyEvent.KEYCODE_NUMPAD_ENTER: return 28;
case KeyEvent.KEYCODE_SPACE: return 57; case KeyEvent.KEYCODE_TAB: return 15;
case KeyEvent.KEYCODE_DEL: return 14; /* backspace */
case KeyEvent.KEYCODE_FORWARD_DEL: return 111; case KeyEvent.KEYCODE_ESCAPE: return 1;
// Modifiers
case KeyEvent.KEYCODE_SHIFT_LEFT: return 42; case KeyEvent.KEYCODE_SHIFT_RIGHT: return 54;
case KeyEvent.KEYCODE_CTRL_LEFT: return 29; case KeyEvent.KEYCODE_CTRL_RIGHT: return 97;
case KeyEvent.KEYCODE_ALT_LEFT: return 56; case KeyEvent.KEYCODE_ALT_RIGHT: return 100;
case KeyEvent.KEYCODE_CAPS_LOCK: return 58;
// Arrows / nav
case KeyEvent.KEYCODE_DPAD_UP: return 103; case KeyEvent.KEYCODE_DPAD_DOWN: return 108;
case KeyEvent.KEYCODE_DPAD_LEFT: return 105; case KeyEvent.KEYCODE_DPAD_RIGHT: return 106;
case KeyEvent.KEYCODE_MOVE_HOME: return 102; case KeyEvent.KEYCODE_MOVE_END: return 107;
case KeyEvent.KEYCODE_PAGE_UP: return 104; case KeyEvent.KEYCODE_PAGE_DOWN: return 109;
case KeyEvent.KEYCODE_INSERT: return 110;
// Punctuation
case KeyEvent.KEYCODE_GRAVE: return 41; case KeyEvent.KEYCODE_MINUS: return 12;
case KeyEvent.KEYCODE_EQUALS: return 13; case KeyEvent.KEYCODE_LEFT_BRACKET: return 26;
case KeyEvent.KEYCODE_RIGHT_BRACKET: return 27; case KeyEvent.KEYCODE_BACKSLASH: return 43;
case KeyEvent.KEYCODE_SEMICOLON: return 39; case KeyEvent.KEYCODE_APOSTROPHE: return 40;
case KeyEvent.KEYCODE_SLASH: return 53; case KeyEvent.KEYCODE_COMMA: return 51;
case KeyEvent.KEYCODE_PERIOD: return 52;
// Function row
case KeyEvent.KEYCODE_F1: return 59; case KeyEvent.KEYCODE_F2: return 60;
case KeyEvent.KEYCODE_F3: return 61; case KeyEvent.KEYCODE_F4: return 62;
case KeyEvent.KEYCODE_F5: return 63; case KeyEvent.KEYCODE_F6: return 64;
case KeyEvent.KEYCODE_F7: return 65; case KeyEvent.KEYCODE_F8: return 66;
case KeyEvent.KEYCODE_F9: return 67; case KeyEvent.KEYCODE_F10: return 68;
case KeyEvent.KEYCODE_F11: return 87; case KeyEvent.KEYCODE_F12: return 88;
default: return -1;
}
}
/**
* The character a key carries when Shift is not held, for a character that needs it - so '@'
* gives '2' and 'A' gives 'a'. Returns 0 when the character is typed without Shift, which is
* also the answer for anything this layout does not place on a key. US layout, which is what
* the session's keymap is.
*/
public static int unshiftedChar(int ch) {
if (ch >= 'A' && ch <= 'Z') return Character.toLowerCase(ch);
int at = SHIFTED_CHARS.indexOf(ch);
return at >= 0 ? PLAIN_CHARS.charAt(at) : 0;
}
// Index-aligned: the symbol, and the key it shares with Shift held.
private static final String SHIFTED_CHARS = "!@#$%^&*()_+{}|:\"<>?~";
private static final String PLAIN_CHARS = "1234567890-=[]\\;',./`";
/** The Android key code that carries an unshifted character, or 0 when nothing does. */
public static int keycodeForChar(int ch) {
if (ch >= 'a' && ch <= 'z') return KeyEvent.KEYCODE_A + (ch - 'a');
if (ch >= '0' && ch <= '9') return KeyEvent.KEYCODE_0 + (ch - '0');
switch (ch) {
case '-': return KeyEvent.KEYCODE_MINUS;
case '=': return KeyEvent.KEYCODE_EQUALS;
case '[': return KeyEvent.KEYCODE_LEFT_BRACKET;
case ']': return KeyEvent.KEYCODE_RIGHT_BRACKET;
case '\\': return KeyEvent.KEYCODE_BACKSLASH;
case ';': return KeyEvent.KEYCODE_SEMICOLON;
case '\'': return KeyEvent.KEYCODE_APOSTROPHE;
case ',': return KeyEvent.KEYCODE_COMMA;
case '.': return KeyEvent.KEYCODE_PERIOD;
case '/': return KeyEvent.KEYCODE_SLASH;
case '`': return KeyEvent.KEYCODE_GRAVE;
case ' ': return KeyEvent.KEYCODE_SPACE;
default: return 0;
}
}
}
@@ -0,0 +1,689 @@
package com.droiddeck.launcher.input;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
/**
* Fake evdev transport for the emulated Xbox 360 pads.
*
* <p>Replaces the old append-file transport (which desynced after ~15 min when an
* unlooped {@code channel.write} left a partial event in the file and the
* IOException was swallowed) with a fixed-size mmap RING BUFFER shared with the
* native reader in {@code fakeinput.cpp}. Delta events are published into the
* ring under a monotonic {@code write_seq}; an authoritative absolute-state
* snapshot is published alongside under a seqlock so the native reader can replay
* a full keyframe to heal any desync (open, ring overflow) without duplicate
* input. Ring layout (magic/version/offsets) is a paired ABI with the native
* {@code FakeInputRingHeader} - keep the two in lockstep.
*/
public class FakeInputWriter {
private static final String TAG = "FakeInputWriter";
// Event types
public static final short EV_SYN = 0x00;
public static final short EV_KEY = 0x01;
public static final short EV_ABS = 0x03;
public static final short EV_MSC = 0x04;
// Event codes
public static final short MSC_SCAN = 0x04;
public static final short SYN_REPORT = 0x00;
// Xbox 360 controller button codes
public static final short BTN_A = 0x130;
public static final short BTN_B = 0x131;
public static final short BTN_X = 0x133;
public static final short BTN_Y = 0x134;
public static final short BTN_TL = 0x136;
public static final short BTN_TR = 0x137;
public static final short BTN_SELECT = 0x13A;
public static final short BTN_START = 0x13B;
public static final short BTN_THUMBL = 0x13D;
public static final short BTN_MODE = 0x13C;
public static final short BTN_THUMBR = 0x13E;
// Absolute axis codes
public static final short ABS_X = 0x00;
public static final short ABS_Y = 0x01;
public static final short ABS_RX = 0x03;
public static final short ABS_RY = 0x04;
public static final short ABS_GAS = 0x09;
public static final short ABS_BRAKE = 0x0A;
public static final short ABS_HAT0X = 0x10;
public static final short ABS_HAT0Y = 0x11;
// Button mapping (bit i of the snapshot buttons word)
private static final short[] BUTTON_MAP = {
BTN_A, BTN_B, BTN_X, BTN_Y, BTN_TL, BTN_TR,
BTN_SELECT, BTN_START, BTN_THUMBL, BTN_THUMBR,
BTN_MODE
};
/** Bit 10 of the snapshot word. The first ten are PadState's own bit order; the Steam
* button is not, because PadState keeps 10 and 11 for the triggers. */
private static final int SNAPSHOT_IDX_MODE = 10;
private static final int EVENT_SIZE = 24;
static final int MAX_EVENTS_PER_UPDATE = 32;
private static final int BUFFER_SIZE = EVENT_SIZE * MAX_EVENTS_PER_UPDATE;
private static final int MAX_FAKE_INPUT_SLOTS = 4;
// Ring layout - MUST match FakeInputRingHeader in fakeinput.cpp.
private static final int RING_CAPACITY_EVENTS = 4096;
private static final int RING_HEADER_SIZE = 64;
private static final int RING_SIZE = RING_HEADER_SIZE + (RING_CAPACITY_EVENTS * EVENT_SIZE);
private static final int RING_MAGIC = 0x46494252; // FIBR
private static final int RING_VERSION = 2;
private static final int RING_MAGIC_OFFSET = 0;
private static final int RING_VERSION_OFFSET = 4;
private static final int RING_EVENT_SIZE_OFFSET = 8;
private static final int RING_CAPACITY_OFFSET = 12;
private static final int RING_WRITE_SEQ_OFFSET = 16;
private static final int RING_GENERATION_OFFSET = 24;
// Authoritative absolute-state snapshot the native reader replays as a full
// keyframe to heal any delta-stream desync. Written under a seqlock
// (RING_SNAPSHOT_SEQ_OFFSET: odd = write in progress).
private static final int RING_SNAPSHOT_SEQ_OFFSET = 32;
private static final int RING_SNAPSHOT_BUTTONS_OFFSET = 40;
private static final int RING_SNAPSHOT_AXES_OFFSET = 44; // short[8]
private static final String RING_DIR_NAME = "fakeinput-rings";
private static final Object RING_LOCK = new Object();
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
static {
System.loadLibrary("sdnative");
}
private static native void nativeStoreFence();
private final File eventFile;
private final int slot;
private final ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
private boolean isOpen = false;
private volatile boolean destroyed = false;
private final boolean[] prevButtonStates = new boolean[12];
private int prevThumbLX, prevThumbLY, prevThumbRX, prevThumbRY;
private int prevTriggerL, prevTriggerR;
private int prevHatX, prevHatY;
private boolean hasChanges = false;
// If a publish fails after prev* state has already advanced, the next frame
// must re-emit the whole state once; otherwise an unchanged control would stay
// silent and the ring snapshot would never catch up.
private boolean pendingFullResend = false;
private boolean forceResend = false;
public FakeInputWriter(String fakeInputPath, int slot) {
this.slot = slot;
this.eventFile = new File(fakeInputPath, "event" + slot);
this.buffer.order(ByteOrder.LITTLE_ENDIAN);
}
private static final class RingSlot {
ByteBuffer data;
File ringFile;
FileChannel ringChannel;
RandomAccessFile ringRaf;
String exportPath;
long generation;
boolean active;
boolean everActivated;
}
// ---- Static ring management (shared by all writers + the env exporter) ----
public static void prepareRingSlots(File fakeInputDir, int slotCount) {
int boundedSlotCount = Math.max(0, Math.min(slotCount, MAX_FAKE_INPUT_SLOTS));
synchronized (RING_LOCK) {
for (int slot = 0; slot < boundedSlotCount; slot++) {
ensureRingSlotLocked(slot, fakeInputDir);
}
}
}
/**
* Prepares every slot ring and returns the {@code slot=path;...} spec the native
* reader consumes via FAKE_EVDEV_MEMFD_PATHS.
*/
public static String getRingEnv(File fakeInputDir) {
synchronized (RING_LOCK) {
prepareRingSlotsLocked(fakeInputDir, MAX_FAKE_INPUT_SLOTS);
return buildRingEnvLocked();
}
}
public static void releaseAllRingSlots() {
synchronized (RING_LOCK) {
for (int slot = 0; slot < RING_SLOTS.length; slot++) {
releaseRingSlotLocked(slot);
}
}
}
private static String buildRingEnvLocked() {
StringBuilder builder = new StringBuilder();
for (int slot = 0; slot < RING_SLOTS.length; slot++) {
RingSlot ringSlot = RING_SLOTS[slot];
if (ringSlot == null || ringSlot.data == null || ringSlot.exportPath == null) {
continue;
}
if (builder.length() > 0) {
builder.append(';');
}
builder.append(slot).append('=').append(ringSlot.exportPath);
}
return builder.toString();
}
private static File getRingDir(File fakeInputDir) {
if (fakeInputDir == null) {
return null;
}
File inputDir = fakeInputDir.getAbsoluteFile();
File parent = inputDir.getParentFile();
return new File(parent != null ? parent : inputDir, RING_DIR_NAME);
}
private static File getRingFile(File fakeInputDir, int slot) {
File ringDir = getRingDir(fakeInputDir);
return ringDir != null ? new File(ringDir, "ring" + slot) : null;
}
private static String getCanonicalOrAbsolutePath(File file) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
return file.getAbsolutePath();
}
}
private static void initializeRingHeader(ByteBuffer data) {
data.order(ByteOrder.LITTLE_ENDIAN);
data.putInt(RING_MAGIC_OFFSET, RING_MAGIC);
data.putInt(RING_VERSION_OFFSET, RING_VERSION);
data.putInt(RING_EVENT_SIZE_OFFSET, EVENT_SIZE);
data.putInt(RING_CAPACITY_OFFSET, RING_CAPACITY_EVENTS);
data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
data.putLong(RING_GENERATION_OFFSET, 0L);
data.putLong(RING_SNAPSHOT_SEQ_OFFSET, 0L);
data.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, 0);
for (int i = 0; i < 8; i++) {
data.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0);
}
}
private static void releaseRingSlotLocked(int slot) {
RingSlot ringSlot = RING_SLOTS[slot];
if (ringSlot == null) {
return;
}
ringSlot.data = null;
if (ringSlot.ringChannel != null) {
try {
ringSlot.ringChannel.close();
} catch (IOException ignored) {
}
ringSlot.ringChannel = null;
}
if (ringSlot.ringRaf != null) {
try {
ringSlot.ringRaf.close();
} catch (IOException ignored) {
}
ringSlot.ringRaf = null;
}
if (ringSlot.ringFile != null && ringSlot.ringFile.exists()) {
ringSlot.ringFile.delete();
}
RING_SLOTS[slot] = null;
}
private static void prepareRingSlotsLocked(File fakeInputDir, int slotCount) {
int boundedSlotCount = Math.max(0, Math.min(slotCount, MAX_FAKE_INPUT_SLOTS));
for (int slot = 0; slot < boundedSlotCount; slot++) {
ensureRingSlotLocked(slot, fakeInputDir);
}
}
private static RingSlot ensureRingSlotLocked(int slot, File fakeInputDir) {
if (slot < 0 || slot >= MAX_FAKE_INPUT_SLOTS || fakeInputDir == null) {
return null;
}
File desiredRingFile = getRingFile(fakeInputDir, slot);
if (desiredRingFile == null) {
return null;
}
desiredRingFile = desiredRingFile.getAbsoluteFile();
RingSlot existing = RING_SLOTS[slot];
if (existing != null && existing.data != null) {
if (existing.ringFile != null && existing.ringFile.equals(desiredRingFile)) {
return existing;
}
releaseRingSlotLocked(slot);
}
RingSlot fileRingSlot = createFileRingSlotLocked(slot, desiredRingFile);
if (fileRingSlot != null) {
RING_SLOTS[slot] = fileRingSlot;
return fileRingSlot;
}
return null;
}
private static RingSlot createFileRingSlotLocked(int slot, File ringFile) {
File ringDir = ringFile.getParentFile();
if (ringDir == null || (!ringDir.exists() && !ringDir.mkdirs())) {
Log.e(TAG, "Failed to create fake input ring directory for slot " + slot);
return null;
}
RandomAccessFile raf = null;
FileChannel channel = null;
try {
raf = new RandomAccessFile(ringFile, "rw");
raf.setLength(RING_SIZE);
channel = raf.getChannel();
ByteBuffer data = channel.map(FileChannel.MapMode.READ_WRITE, 0, RING_SIZE);
initializeRingHeader(data);
RingSlot ringSlot = new RingSlot();
ringSlot.data = data;
ringSlot.ringFile = ringFile.getAbsoluteFile();
ringSlot.ringRaf = raf;
ringSlot.ringChannel = channel;
ringSlot.exportPath = getCanonicalOrAbsolutePath(ringFile);
Log.i(TAG, "Created fake input file ring for slot " + slot + ": " + ringSlot.exportPath);
return ringSlot;
} catch (IOException e) {
Log.e(TAG, "Failed to create fake input file ring for slot " + slot + ": " + e.getMessage());
if (channel != null) {
try {
channel.close();
} catch (IOException ignored) {
}
}
if (raf != null) {
try {
raf.close();
} catch (IOException ignored) {
}
}
return null;
}
}
private RingSlot ensureRingSlot() {
synchronized (RING_LOCK) {
return ensureRingSlotLocked(this.slot, this.eventFile.getParentFile());
}
}
private boolean activateRingSlot() {
RingSlot ringSlot = ensureRingSlot();
if (ringSlot == null || ringSlot.data == null) {
return false;
}
synchronized (ringSlot) {
if (!ringSlot.active) {
if (ringSlot.everActivated) {
ringSlot.generation++;
} else {
ringSlot.everActivated = true;
}
ringSlot.data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
clearSnapshotLocked(ringSlot.data);
ringSlot.data.putLong(RING_GENERATION_OFFSET, ringSlot.generation);
ringSlot.active = true;
Log.d(TAG, "Activated fake input ring for slot " + this.slot
+ " generation=" + ringSlot.generation);
}
}
return true;
}
private void deactivateRingSlot() {
RingSlot ringSlot;
synchronized (RING_LOCK) {
ringSlot = this.slot >= 0 && this.slot < RING_SLOTS.length ? RING_SLOTS[this.slot] : null;
}
if (ringSlot == null) {
return;
}
synchronized (ringSlot) {
if (ringSlot.active && ringSlot.data != null) {
ringSlot.generation++;
ringSlot.data.putLong(RING_WRITE_SEQ_OFFSET, 0L);
clearSnapshotLocked(ringSlot.data);
ringSlot.data.putLong(RING_GENERATION_OFFSET, ringSlot.generation);
Log.i(TAG, "Deactivated fake input ring for slot " + this.slot
+ " generation=" + ringSlot.generation);
}
ringSlot.active = false;
}
}
private boolean flushBufferToRing() {
RingSlot ringSlot = ensureRingSlot();
if (ringSlot == null || ringSlot.data == null) {
return false;
}
// Raw byte copy: endianness is irrelevant since we never interpret
// multi-byte fields out of the source here.
ByteBuffer source = this.buffer.duplicate();
synchronized (ringSlot) {
ByteBuffer ring = ringSlot.data;
long writeSeq = ring.getLong(RING_WRITE_SEQ_OFFSET);
int sourceLimit = source.limit();
while (source.remaining() >= EVENT_SIZE) {
int eventIndex = (int) (writeSeq % RING_CAPACITY_EVENTS);
int targetOffset = RING_HEADER_SIZE + (eventIndex * EVENT_SIZE);
// Bulk-copy one event (EVENT_SIZE bytes) instead of byte-by-byte.
// Bound the source to a single event, position the ring at the slot,
// then let put(ByteBuffer) move the whole block. Mutating the ring's
// Java position is harmless: the native reader uses a raw pointer, not
// this position. API-26 safe (no JDK 13+ absolute bulk put).
source.limit(source.position() + EVENT_SIZE);
ring.position(targetOffset);
ring.put(source);
source.limit(sourceLimit);
writeSeq++;
}
// Publish the resulting absolute state. prev* now hold the post-update
// values, i.e. exactly the state the events just written transition to.
writeSnapshotLocked(ring);
nativeStoreFence();
ring.putLong(RING_WRITE_SEQ_OFFSET, writeSeq);
}
return true;
}
// Publishes the full absolute controller state for the native reader to replay
// as a keyframe. seqlock: bump to odd, write fields, bump to even, with
// store-store fences so the reader's acquire loads see consistent payloads.
private void writeSnapshotLocked(ByteBuffer ring) {
int buttons = 0;
for (int i = 0; i < BUTTON_MAP.length; i++) {
if (this.prevButtonStates[i]) {
buttons |= (1 << i);
}
}
long seq = ring.getLong(RING_SNAPSHOT_SEQ_OFFSET);
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1); // odd: write in progress
nativeStoreFence();
ring.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, buttons);
// Axis order must match the native kSnapshotAxisCodes:
// X, Y, RX, RY, GAS(=triggerR), BRAKE(=triggerL), HAT0X, HAT0Y.
ring.putShort(RING_SNAPSHOT_AXES_OFFSET, clampShort(this.prevThumbLX));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 2, clampShort(this.prevThumbLY));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 4, clampShort(this.prevThumbRX));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 6, clampShort(this.prevThumbRY));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 8, clampShort(this.prevTriggerR));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 10, clampShort(this.prevTriggerL));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 12, clampShort(this.prevHatX));
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + 14, clampShort(this.prevHatY));
nativeStoreFence();
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 2); // even: write complete
}
private static short clampShort(int value) {
if (value > Short.MAX_VALUE) {
return Short.MAX_VALUE;
}
if (value < Short.MIN_VALUE) {
return Short.MIN_VALUE;
}
return (short) value;
}
private static void clearSnapshotLocked(ByteBuffer ring) {
long seq = ring.getLong(RING_SNAPSHOT_SEQ_OFFSET);
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1);
nativeStoreFence();
ring.putInt(RING_SNAPSHOT_BUTTONS_OFFSET, 0);
for (int i = 0; i < 8; i++) {
ring.putShort(RING_SNAPSHOT_AXES_OFFSET + (i * 2), (short) 0);
}
nativeStoreFence();
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 2);
}
private boolean flushBuffer() {
return flushBufferToRing();
}
public synchronized boolean open() {
if (destroyed)
return false;
if (isOpen)
return true;
try {
eventFile.getParentFile().mkdirs();
if (!eventFile.exists()) {
eventFile.createNewFile();
}
if (!activateRingSlot()) {
if (eventFile.exists()) {
eventFile.delete();
}
Log.e(TAG, "Failed to open fake input mmap ring: " + eventFile.getAbsolutePath());
return false;
}
isOpen = true;
Log.i(TAG, "Opened fake input: " + eventFile.getAbsolutePath());
return true;
} catch (IOException e) {
Log.e(TAG, "Failed to open: " + e.getMessage());
return false;
}
}
public synchronized void close() {
isOpen = false;
}
/**
* Reset all input state to neutral (all buttons released, axes zeroed).
* This keeps the ring active so games that cache the file descriptor can still
* reconnect.
*/
public synchronized void reset() {
if (!isOpen && !open())
return;
buffer.clear();
hasChanges = false;
// Release all buttons
for (int i = 0; i < BUTTON_MAP.length; i++) {
if (prevButtonStates[i]) {
prevButtonStates[i] = false;
writeEvent(EV_MSC, MSC_SCAN, BUTTON_MAP[i]);
writeEvent(EV_KEY, BUTTON_MAP[i], 0);
}
}
// Zero all axes
if (prevThumbLX != 0) {
prevThumbLX = 0;
writeEvent(EV_ABS, ABS_X, 0);
}
if (prevThumbLY != 0) {
prevThumbLY = 0;
writeEvent(EV_ABS, ABS_Y, 0);
}
if (prevThumbRX != 0) {
prevThumbRX = 0;
writeEvent(EV_ABS, ABS_RX, 0);
}
if (prevThumbRY != 0) {
prevThumbRY = 0;
writeEvent(EV_ABS, ABS_RY, 0);
}
if (prevTriggerL != 0) {
prevTriggerL = 0;
writeEvent(EV_ABS, ABS_BRAKE, 0);
}
if (prevTriggerR != 0) {
prevTriggerR = 0;
writeEvent(EV_ABS, ABS_GAS, 0);
}
if (prevHatX != 0) {
prevHatX = 0;
writeEvent(EV_ABS, ABS_HAT0X, 0);
}
if (prevHatY != 0) {
prevHatY = 0;
writeEvent(EV_ABS, ABS_HAT0Y, 0);
}
if (hasChanges) {
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer())
Log.e(TAG, "Reset write error: fake input mmap ring unavailable");
}
Log.i(TAG, "Reset fake input to neutral state: " + eventFile.getAbsolutePath());
}
public synchronized void softRelease() {
reset();
close();
Log.i(TAG, "Soft released fake input: " + eventFile.getAbsolutePath());
}
/**
* Full destroy - reset, tear the ring generation down, and delete the discovery node.
*/
public synchronized void destroy() {
destroyed = true;
reset();
close();
deactivateRingSlot();
if (eventFile != null && eventFile.exists()) {
boolean deleted = eventFile.delete();
Log.i(TAG, "Deleted fake input discovery node: " + eventFile.getAbsolutePath() + " (" + deleted + ")");
}
}
private void writeEvent(short type, short code, int value) {
long timeMs = System.currentTimeMillis();
buffer.putLong(timeMs / 1000);
buffer.putLong((timeMs % 1000) * 1000);
buffer.putShort(type);
buffer.putShort(code);
buffer.putInt(value);
hasChanges = true;
}
private void writeButton(int idx, boolean pressed) {
if (idx < 0 || idx >= BUTTON_MAP.length)
return;
if (!forceResend && prevButtonStates[idx] == pressed)
return;
prevButtonStates[idx] = pressed;
writeEvent(EV_MSC, MSC_SCAN, BUTTON_MAP[idx]);
writeEvent(EV_KEY, BUTTON_MAP[idx], pressed ? 1 : 0);
}
public synchronized void writePad(PadState state) {
if (!isOpen && !open())
return;
// Keep the ring delta-first for latency. Full event frames are only used as
// a one-shot repair after a failed publish; normal open/overflow recovery is
// handled by the native snapshot keyframe.
forceResend = pendingFullResend;
pendingFullResend = false;
if (forceResend) {
Log.d(TAG, "Re-emitting full gamepad state after failed publish for slot " + slot);
}
buffer.clear();
hasChanges = false;
// Buttons
for (int i = 0; i < 10; i++) {
writeButton(i, state.isDown(i));
}
// The Steam button. In a Linux session this is what opens the client's own in-game menu,
// and the client looks for it where an Xbox pad keeps it: evdev BTN_MODE, which SDL then
// reports as button 8 - exactly the "guide:b8" in the mapping Steam writes for this pad.
writeButton(SNAPSHOT_IDX_MODE,
state.isDown(PadState.GUIDE));
// Sticks
int lx = (int) (state.leftX * 32767);
int ly = (int) (state.leftY * 32767);
int rx = (int) (state.rightX * 32767);
int ry = (int) (state.rightY * 32767);
// The fake evdev ring is event-queue semantics, so unchanged axes normally
// stay silent; forceResend overrides that to emit a complete keyframe.
if (forceResend || lx != prevThumbLX) {
prevThumbLX = lx;
writeEvent(EV_ABS, ABS_X, lx);
}
if (forceResend || ly != prevThumbLY) {
prevThumbLY = ly;
writeEvent(EV_ABS, ABS_Y, ly);
}
if (forceResend || rx != prevThumbRX) {
prevThumbRX = rx;
writeEvent(EV_ABS, ABS_RX, rx);
}
if (forceResend || ry != prevThumbRY) {
prevThumbRY = ry;
writeEvent(EV_ABS, ABS_RY, ry);
}
// L2 and R2 (Triggers)
int tl = (int) (state.leftTrigger * 255);
int tr = (int) (state.rightTrigger * 255);
if (forceResend || tl != prevTriggerL) {
prevTriggerL = tl;
writeEvent(EV_ABS, ABS_BRAKE, tl);
}
if (forceResend || tr != prevTriggerR) {
prevTriggerR = tr;
writeEvent(EV_ABS, ABS_GAS, tr);
}
// D-pad
int hatX = state.hatX();
int hatY = state.hatY();
if (forceResend || hatX != prevHatX) {
prevHatX = hatX;
writeEvent(EV_ABS, ABS_HAT0X, hatX);
}
if (forceResend || hatY != prevHatY) {
prevHatY = hatY;
writeEvent(EV_ABS, ABS_HAT0Y, hatY);
}
// Detect change else no need to write
if (hasChanges) {
writeEvent(EV_SYN, SYN_REPORT, 0);
buffer.flip();
if (!flushBuffer()) {
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
// Couldn't publish; re-assert the whole state on the next frame.
pendingFullResend = true;
}
}
forceResend = false;
}
public boolean isOpen() {
return isOpen;
}
}
@@ -0,0 +1,128 @@
package com.droiddeck.launcher.input
import android.app.Activity
import android.content.Context
import android.text.InputType
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
/**
* A place for the soft keyboard to land. Steam's UI and the games under it are X11 clients of
* gamescope and know nothing of Wayland text input, so everything the keyboard produces has to
* become key events: what the IME commits as text is turned into the key presses that would have
* typed it (Shift included, from the key character map), and handed to the activity, whose key
* path turns them into evdev codes for the compositor. Backspace, Enter and the keys an IME sends
* directly go the same way.
*
* Invisible and unfocusable until asked for: a focused View would take D-pad and stick motion
* away from the pad.
*/
class KeyboardHost(
context: Context,
private val sendKeyEvent: (KeyEvent) -> Boolean,
) : View(context) {
constructor(activity: Activity) : this(activity, { activity.dispatchKeyEvent(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
init {
isFocusable = false
isFocusableInTouchMode = false
visibility = VISIBLE // present in the tree, draws nothing
layoutParams = android.widget.FrameLayout.LayoutParams(1, 1)
}
override fun onCheckIsTextEditor(): Boolean = shown
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection? {
if (!shown) return null
// No suggestions and no autocorrect: the keyboard sends what was pressed, key by key, which
// is what a password field on the other side needs.
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE or EditorInfo.IME_FLAG_NO_FULLSCREEN or
EditorInfo.IME_FLAG_NO_EXTRACT_UI
return KeyConnection()
}
fun toggle() = if (shown) hide() else show()
fun show() {
shown = true
isFocusable = true
isFocusableInTouchMode = true
requestFocus()
imm.restartInput(this)
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun hide() {
shown = false
imm.hideSoftInputFromWindow(windowToken, 0)
isFocusable = false
isFocusableInTouchMode = false
clearFocus()
}
private inner class KeyConnection : BaseInputConnection(this, false) {
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
if (text.isNullOrEmpty()) return true
// The key events that type this text on a US layout - a capital arrives as Shift
// down, the letter, Shift up. Characters the map cannot place are sent as a bare
// key event carrying the character, which the activity's key path works back from.
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))
}
}
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) }
return true
}
override fun sendKeyEvent(event: KeyEvent): Boolean = this@KeyboardHost.sendKeyEvent(event)
override fun performEditorAction(actionCode: Int): Boolean {
tap(KeyEvent.KEYCODE_ENTER)
return true
}
private fun tap(keyCode: Int) {
val t = System.currentTimeMillis()
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_DOWN, keyCode, 0))
sendKeyEvent(KeyEvent(t, t, KeyEvent.ACTION_UP, keyCode, 0))
}
override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence = ""
override fun getTextAfterCursor(n: Int, flags: Int): CharSequence = ""
override fun getSelectedText(flags: Int): CharSequence? = null
}
/** A key event that carries a character the key map could not place. */
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
}
}
@@ -0,0 +1,341 @@
package com.droiddeck.launcher.input
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.view.MotionEvent
import android.view.View
import kotlin.math.sqrt
/**
* A pad drawn on the screen for devices that have no controller attached.
*
* It writes into the same [PadBridge] a physical pad does, so the Steam client sees one Xbox pad
* whichever is being used, and the two can be used at once. A d-pad, two sticks, the four face
* buttons, the bumpers, and the three centre buttons: enough to drive Big Picture and to play,
* and no control editor.
*
* Where the controls go follows the picture. The compositor letterboxes the session's output onto
* the panel, and a foldable or a wide phone has bars beside or above and below it that are empty
* black: the controls take the bars first, and only overlay the picture when there are none wide
* enough. Only the controls themselves take touches; everything else falls through to the
* activity, where it moves the mouse pointer.
*/
@SuppressLint("ViewConstructor")
class OnScreenControls(context: Context, private val pad: PadBridge) : View(context) {
private class Control(
val id: String,
val label: String,
/** A PadState button number, or -1. */
val button: Int,
/** A d-pad direction (0 up, 1 right, 2 down, 3 left), or -1. */
val dpad: Int,
/** 0 = left stick, 1 = right stick, -1 = a button. */
val stick: Int,
val radius: Float,
) {
var cx = 0f
var cy = 0f
var pressedBy = -1 // the pointer id holding it, or -1
/** A stick's knob offset from its centre, in [-radius, radius]. */
var kx = 0f
var ky = 0f
/** A stick that moved or was let go: its axes are written once, then left alone. */
var dirty = false
fun contains(x: Float, y: Float, radius: Float = this.radius): Boolean {
val dx = x - cx
val dy = y - cy
// A generous hit area: a finger on glass is not a mouse, and a miss in Big Picture
// means the user thinks the pad does not work.
val r = radius * 1.25f
return dx * dx + dy * dy <= r * r
}
/** Moves the knob towards the finger, clamped to the base. */
fun drag(x: Float, y: Float) {
var dx = x - cx
var dy = y - cy
val d = sqrt(dx * dx + dy * dy)
if (d > radius) { dx = dx / d * radius; dy = dy / d * radius }
kx = dx; ky = dy; dirty = true
}
}
private val density = resources.displayMetrics.density
private fun dp(value: Float) = value * density
private val controls = listOf(
Control("up", "▲", -1, 0, -1, dp(26f)),
Control("right", ">", -1, 1, -1, dp(26f)),
Control("down", "▼", -1, 2, -1, dp(26f)),
Control("left", "<", -1, 3, -1, dp(26f)),
Control("ls", "L", -1, -1, 0, dp(48f)),
Control("rs", "R", -1, -1, 1, dp(48f)),
Control("a", "A", 0, -1, -1, dp(30f)),
Control("b", "B", 1, -1, -1, dp(30f)),
Control("x", "X", 2, -1, -1, dp(30f)),
Control("y", "Y", 3, -1, -1, dp(30f)),
Control("lb", "LB", 4, -1, -1, dp(24f)),
Control("rb", "RB", 5, -1, -1, dp(24f)),
Control("select", "⧉", 6, -1, -1, dp(20f)),
Control("start", "☰", 7, -1, -1, dp(20f)),
// The client's own in-game menu; the interposer publishes it as BTN_MODE.
Control("guide", "◉", PadState.GUIDE, -1, -1, dp(22f)),
Control("qam", "⋯", -1, -1, -1, dp(22f)),
)
private var buttonsOnly = false
private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = dp(1.5f)
}
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
typeface = android.graphics.Typeface.DEFAULT_BOLD
}
/** Where the session's picture is drawn on this view, or null when the whole view is picture. */
private var picture: RectF? = null
/** The activity tells the controls where the picture lands; the layout follows it. */
fun setPicture(rect: RectF?) {
val same = (rect == null && picture == null) || (rect != null && picture != null && rect == picture)
if (same) return
picture = rect?.let { RectF(it) }
if (width > 0 && height > 0) { layoutControls(width.toFloat(), height.toFloat()); invalidate() }
}
fun setButtonsOnly(enabled: Boolean) {
if (buttonsOnly == enabled) return
releaseAll()
buttonsOnly = enabled
if (width > 0 && height > 0) layoutControls(width.toFloat(), height.toFloat())
invalidate()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
layoutControls(w.toFloat(), h.toFloat())
}
/**
* Three layouts: side bars (a wide panel showing 16:9), bottom band (a squarer panel showing
* a wide picture), and the overlay when neither bar is wide enough for a cluster. Thumbs reach
* the bottom corners in every one; nothing is placed where a game's own HUD usually is.
*/
private fun layoutControls(w: Float, h: Float) {
if (buttonsOnly) {
val inset = dp(44f)
place("guide", inset, h - inset)
place("qam", w - inset, h - inset)
return
}
val p = picture
val sideBar = if (p != null) minOf(p.left, w - p.right) else 0f
val bottomBand = if (p != null) h - p.bottom else 0f
val margin = dp(34f)
when {
// A cluster (d-pad or face buttons) is ~156 dp across; a stick above it needs the height.
sideBar >= dp(160f) && p != null -> {
val lx = p.left / 2f
val rx = p.right + (w - p.right) / 2f
val bottom = h - margin - dp(74f)
dpadAt(lx, bottom)
faceAt(rx, bottom)
place("ls", lx, bottom - dp(196f))
place("rs", rx, bottom - dp(196f))
place("lb", lx, bottom - dp(196f) - dp(96f))
place("rb", rx, bottom - dp(196f) - dp(96f))
place("select", lx, h - margin + dp(8f))
place("start", rx, h - margin + dp(8f))
place("guide", w / 2f, h - dp(22f))
}
bottomBand >= dp(190f) && p != null -> {
val cy = p.bottom + bottomBand / 2f + dp(12f)
val dx = margin + dp(74f)
val fx = w - margin - dp(74f)
dpadAt(dx, cy)
faceAt(fx, cy)
place("ls", dx + dp(150f), cy)
place("rs", fx - dp(150f), cy)
place("lb", dx, p.bottom + dp(30f))
place("rb", fx, p.bottom + dp(30f))
val centre = w / 2f
place("select", centre - dp(60f), h - dp(30f))
place("guide", centre, h - dp(30f))
place("start", centre + dp(60f), h - dp(30f))
}
else -> {
val dx = margin + dp(74f)
val fx = w - margin - dp(74f)
val bottom = h - margin - dp(74f)
dpadAt(dx, bottom)
faceAt(fx, bottom)
place("ls", dx + dp(142f), bottom)
place("rs", fx - dp(142f), bottom)
place("lb", margin + dp(46f), h - margin - dp(196f))
place("rb", w - margin - dp(46f), h - margin - dp(196f))
val centre = w / 2f
place("select", centre - dp(60f), h - margin - dp(26f))
place("guide", centre, h - margin - dp(26f))
place("start", centre + dp(60f), h - margin - dp(26f))
}
}
}
private fun dpadAt(x: Float, y: Float) {
val step = dp(52f)
place("up", x, y - step)
place("down", x, y + step)
place("left", x - step, y)
place("right", x + step, y)
}
private fun faceAt(x: Float, y: Float) {
val step = dp(50f)
place("a", x, y + step)
place("b", x + step, y)
place("x", x - step, y)
place("y", x, y - step)
}
private fun place(id: String, x: Float, y: Float) {
val control = controls.firstOrNull { it.id == id } ?: return
control.cx = x
control.cy = y
}
override fun onDraw(canvas: Canvas) {
for (control in controls) {
if (!isVisible(control)) continue
val held = control.pressedBy != -1
val radius = controlRadius(control)
if (control.stick >= 0) {
// The base, then the knob where the finger holds it.
fill.color = if (held) Color.argb(60, 199, 125, 255) else Color.argb(50, 20, 12, 30)
canvas.drawCircle(control.cx, control.cy, radius, fill)
stroke.color = if (held) Color.argb(200, 235, 212, 255) else Color.argb(90, 201, 160, 255)
canvas.drawCircle(control.cx, control.cy, radius, stroke)
val knob = radius * 0.46f
fill.color = if (held) Color.argb(170, 199, 125, 255) else Color.argb(110, 60, 40, 90)
canvas.drawCircle(control.cx + control.kx, control.cy + control.ky, knob, fill)
stroke.color = if (held) Color.argb(230, 245, 230, 255) else Color.argb(140, 201, 160, 255)
canvas.drawCircle(control.cx + control.kx, control.cy + control.ky, knob, stroke)
text.color = if (held) Color.WHITE else Color.argb(150, 225, 210, 245)
text.textSize = knob * 0.8f
canvas.drawText(control.label, control.cx + control.kx, control.cy + control.ky + text.textSize * 0.35f, text)
continue
}
fill.color = if (held) Color.argb(150, 199, 125, 255) else Color.argb(70, 20, 12, 30)
canvas.drawCircle(control.cx, control.cy, radius, fill)
stroke.color = if (held) Color.argb(220, 235, 212, 255) else Color.argb(110, 201, 160, 255)
canvas.drawCircle(control.cx, control.cy, radius, stroke)
text.color = if (held) Color.WHITE else Color.argb(190, 225, 210, 245)
val label = if (buttonsOnly && control.id == "guide") "Steam" else control.label
text.textSize = if (buttonsOnly && control.id == "guide") dp(11f) else radius * 0.85f
canvas.drawText(label, control.cx, control.cy + text.textSize * 0.35f, text)
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
val index = event.actionIndex
val control = controlAt(event.getX(index), event.getY(index)) ?: return false
control.pressedBy = event.getPointerId(index)
if (control.stick >= 0) control.drag(event.getX(index), event.getY(index))
apply()
return true
}
MotionEvent.ACTION_MOVE -> {
var changed = false
for (index in 0 until event.pointerCount) {
val pointer = event.getPointerId(index)
val x = event.getX(index)
val y = event.getY(index)
// A stick keeps its finger wherever it goes: the knob follows, clamped.
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
if (stick != null) { stick.drag(x, y); changed = true; continue }
// A finger that slides off a button releases it, and one that slides onto
// another presses that - which is how a d-pad is used in practice.
val over = controlAt(x, y)?.takeIf { it.stick < 0 }
for (control in controls) {
if (control.stick < 0 && control.pressedBy == pointer && control !== over) {
control.pressedBy = -1
changed = true
}
}
if (over != null && over.pressedBy == -1) {
over.pressedBy = pointer
changed = true
}
}
if (changed) apply()
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
val pointer = event.getPointerId(event.actionIndex)
var changed = false
for (control in controls) {
if (control.pressedBy == pointer || event.actionMasked == MotionEvent.ACTION_CANCEL) {
if (control.pressedBy != -1) changed = true
control.pressedBy = -1
if (control.stick >= 0 && (control.kx != 0f || control.ky != 0f)) control.dirty = true
control.kx = 0f; control.ky = 0f
}
}
if (changed) apply()
return true
}
}
return false
}
private fun controlAt(x: Float, y: Float): Control? =
controls.firstOrNull { isVisible(it) && it.contains(x, y, controlRadius(it)) }
private fun isVisible(control: Control): Boolean =
!buttonsOnly || control.id == "guide" || control.id == "qam"
private fun controlRadius(control: Control): Float =
if (buttonsOnly && (control.id == "guide" || control.id == "qam")) dp(30f) else control.radius
private fun apply() {
if (buttonsOnly) {
val guidePressed = controls.first { it.id == "guide" }.pressedBy != -1
val qamPressed = controls.first { it.id == "qam" }.pressedBy != -1
pad.setSystemButtons(guidePressed, qamPressed)
} else {
pad.setSystemButtons(false, false)
pad.applyTouch { state ->
for (control in controls) {
val held = control.pressedBy != -1
when {
control.stick >= 0 && !control.dirty -> {}
control.stick == 0 -> { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius; control.dirty = false }
control.stick == 1 -> { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius; control.dirty = false }
control.dpad == 0 -> state.up = held
control.dpad == 1 -> state.right = held
control.dpad == 2 -> state.down = held
control.dpad == 3 -> state.left = held
control.button >= 0 -> state.press(control.button, held)
}
}
}
}
invalidate()
}
/** Everything up, for when the controls are hidden mid-press. */
fun releaseAll() {
if (controls.none { it.pressedBy != -1 } && !buttonsOnly) return
controls.forEach { it.pressedBy = -1; if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true; it.kx = 0f; it.ky = 0f }
apply()
}
}
@@ -0,0 +1,220 @@
package com.droiddeck.launcher.input;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import java.io.File;
/**
* A physical controller, republished as a synthetic evdev device the Steam client can see.
*
* <p>Android hands a gamepad to the foreground activity as key and motion events; the Steam client
* inside the runtime never sees that. What it does scan is {@code /dev/input}, which the session's
* interposer (libfakeinput.so) serves out of the shared-memory rings written here. So the path is:
* Android event → {@link PadState} → {@link FakeInputWriter} ring → interposer → evdev node →
* SDL → Big Picture.
*
* <p>The identity the interposer reports is an Xbox 360 pad, which is what makes SDL apply a known
* mapping without the user configuring anything.
*/
public final class PadBridge {
private static final String TAG = "PadBridge";
/** Slot 0 is the one the session exports; extra slots would each show as another pad. */
private static final int SLOT = 0;
private static final float DEAD_ZONE = 0.12f;
private static final long QAM_GUIDE_LEAD_MS = 80;
private static final long QAM_A_HOLD_MS = 120;
private static final long QAM_GUIDE_TAIL_MS = 40;
private final FakeInputWriter writer;
private final PadState state = new PadState();
private final PadState effectiveState = new PadState();
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private boolean open;
private boolean systemGuidePressed;
private boolean systemQamPressed;
private boolean qamChordActive;
private boolean qamSyntheticAPressed;
private int qamChordGeneration;
public PadBridge(File fakeInputDir) {
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
}
/** Opens the ring; safe to call more than once. */
public synchronized boolean start() {
if (!open) {
open = writer.open();
Log.i(TAG, "ring slot " + SLOT + (open ? " open" : " NOT open"));
}
return open;
}
public synchronized void stop() {
systemGuidePressed = false;
systemQamPressed = false;
qamChordActive = false;
qamSyntheticAPressed = false;
qamChordGeneration++;
if (open) {
state.clear();
writer.writePad(state);
writer.close();
open = false;
}
}
/** True when the device this event came from is a gamepad or joystick, not the touchscreen. */
public static boolean isFromController(InputDevice device) {
if (device == null) return false;
// A virtual device is the system's own synthetic input, not a pad somebody is holding -
// counting it would hide the on-screen controls with nothing to replace them.
if (device.isVirtual()) return false;
int sources = device.getSources();
return (sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD
|| (sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK;
}
/** Whether any real controller is attached right now. */
public static boolean anyControllerConnected() {
for (int id : InputDevice.getDeviceIds()) {
if (isFromController(InputDevice.getDevice(id))) return true;
}
return false;
}
/** @return true when the event was a pad button and has been consumed. */
public synchronized boolean onKeyEvent(KeyEvent event) {
if (!isFromController(event.getDevice())) return false;
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BUTTON_A: state.press(0, pressed); break;
case KeyEvent.KEYCODE_BUTTON_B: state.press(1, pressed); break;
case KeyEvent.KEYCODE_BUTTON_X: state.press(2, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Y: state.press(3, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L1: state.press(4, pressed); break;
case KeyEvent.KEYCODE_BUTTON_R1: state.press(5, pressed); break;
case KeyEvent.KEYCODE_BUTTON_SELECT:
case KeyEvent.KEYCODE_BACK: state.press(6, pressed); break;
case KeyEvent.KEYCODE_BUTTON_START:
case KeyEvent.KEYCODE_MENU: state.press(7, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: state.press(8, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: state.press(9, pressed); break;
// The client's own in-game menu is opened by this one; the interposer publishes it as
// BTN_MODE, which SDL reports as the "guide" button.
case KeyEvent.KEYCODE_BUTTON_MODE:
case KeyEvent.KEYCODE_HOME: state.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L2: state.leftTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_BUTTON_R2: state.rightTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_DPAD_UP: state.up = pressed; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: state.right = pressed; break;
case KeyEvent.KEYCODE_DPAD_DOWN: state.down = pressed; break;
case KeyEvent.KEYCODE_DPAD_LEFT: state.left = pressed; break;
default: return false;
}
publish();
return true;
}
/** @return true when the event was a pad's sticks/triggers and has been consumed. */
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isFromController(event.getDevice())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
state.leftX = axis(event, MotionEvent.AXIS_X);
// Android's Y axis grows downwards and evdev's ABS_Y does too, so no flip here: what the
// pad reports as "down" is what the client is told.
state.leftY = axis(event, MotionEvent.AXIS_Y);
state.rightX = axis(event, MotionEvent.AXIS_Z);
state.rightY = axis(event, MotionEvent.AXIS_RZ);
float lt = event.getAxisValue(MotionEvent.AXIS_LTRIGGER);
float rt = event.getAxisValue(MotionEvent.AXIS_RTRIGGER);
// Some pads only report the triggers on BRAKE/GAS.
if (lt == 0f) lt = event.getAxisValue(MotionEvent.AXIS_BRAKE);
if (rt == 0f) rt = event.getAxisValue(MotionEvent.AXIS_GAS);
state.leftTrigger = lt;
state.rightTrigger = rt;
float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
state.up = hatY < -0.5f;
state.right = hatX > 0.5f;
state.down = hatY > 0.5f;
state.left = hatX < -0.5f;
publish();
return true;
}
/**
* The on-screen controls' way in: they mutate the same state a physical pad writes, so the
* client only ever sees one device and a user can use both at once without them fighting.
*/
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
mutation.accept(state);
publish();
}
/** Touch-only Steam and QAM buttons, merged with physical input without changing its state. */
public synchronized void setSystemButtons(boolean guidePressed, boolean qamPressed) {
if (systemGuidePressed == guidePressed && systemQamPressed == qamPressed) return;
boolean qamStarted = qamPressed && !systemQamPressed;
systemGuidePressed = guidePressed;
systemQamPressed = qamPressed;
if (qamStarted) startQamChord();
else publish();
}
/** Starts the same Guide-then-A sequence used by the touch QAM button. */
public synchronized void triggerQam() {
startQamChord();
}
private void startQamChord() {
if (qamChordActive) return;
qamChordActive = true;
int generation = ++qamChordGeneration;
publish();
mainHandler.postDelayed(() -> pressQamA(generation), QAM_GUIDE_LEAD_MS);
}
private synchronized void pressQamA(int generation) {
if (generation != qamChordGeneration || !qamChordActive) return;
qamSyntheticAPressed = true;
publish();
mainHandler.postDelayed(() -> releaseQamA(generation), QAM_A_HOLD_MS);
}
private synchronized void releaseQamA(int generation) {
if (generation != qamChordGeneration || !qamChordActive) return;
qamSyntheticAPressed = false;
publish();
mainHandler.postDelayed(() -> releaseQamGuide(generation), QAM_GUIDE_TAIL_MS);
}
private synchronized void releaseQamGuide(int generation) {
if (generation != qamChordGeneration || !qamChordActive) return;
qamChordActive = false;
publish();
}
private void publish() {
if (!open && !start()) return;
if (systemGuidePressed || qamChordActive) {
effectiveState.copyFrom(state);
effectiveState.press(PadState.GUIDE, true);
if (qamSyntheticAPressed) {
effectiveState.press(PadState.A, state.isDown(PadState.A) || qamSyntheticAPressed);
}
writer.writePad(effectiveState);
} else {
writer.writePad(state);
}
}
private static float axis(MotionEvent event, int axis) {
float value = event.getAxisValue(axis);
return Math.abs(value) < DEAD_ZONE ? 0f : value;
}
}
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.input
/**
* What one Xbox-shaped pad is doing right now: two sticks and two triggers as -1..1 / 0..1, the
* four d-pad directions, and a bitmask of the buttons numbered the way the fake evdev node
* reports them. Written by whatever drives the pad (a physical controller, the on-screen one, or
* both at once) and read by [FakeInputWriter] into the guest's input ring.
*/
class PadState {
@JvmField var leftX = 0f
@JvmField var leftY = 0f
@JvmField var rightX = 0f
@JvmField var rightY = 0f
@JvmField var leftTrigger = 0f
@JvmField var rightTrigger = 0f
@JvmField var up = false
@JvmField var right = false
@JvmField var down = false
@JvmField var left = false
private var buttons = 0
fun press(button: Int, down: Boolean) {
buttons = if (down) buttons or (1 shl button) else buttons and (1 shl button).inv()
}
fun isDown(button: Int): Boolean = buttons and (1 shl button) != 0
/** The d-pad as a hat: -1 left, 1 right; -1 up, 1 down. Opposites cancel to 0. */
fun hatX(): Int = if (right && !left) 1 else if (left && !right) -1 else 0
fun hatY(): Int = if (down && !up) 1 else if (up && !down) -1 else 0
fun copyFrom(other: PadState) {
leftX = other.leftX; leftY = other.leftY; rightX = other.rightX; rightY = other.rightY
leftTrigger = other.leftTrigger; rightTrigger = other.rightTrigger
up = other.up; right = other.right; down = other.down; left = other.left
buttons = other.buttons
}
/** Everything released and centred. */
fun clear() {
leftX = 0f; leftY = 0f; rightX = 0f; rightY = 0f
leftTrigger = 0f; rightTrigger = 0f
up = false; right = false; down = false; left = false
buttons = 0
}
companion object {
const val A = 0
const val B = 1
const val X = 2
const val Y = 3
const val LB = 4
const val RB = 5
const val SELECT = 6
const val START = 7
const val L3 = 8
const val R3 = 9
/** The Steam/Guide button, which the fake evdev node reports as BTN_MODE. */
const val GUIDE = 12
}
}
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.ViewConfiguration
import kotlin.math.abs
import kotlin.math.roundToInt
/**
* Touch as a mouse, the way a remote desktop does it: where you touch is where the pointer goes.
*
* - tap ............................ left click
* - drag ........................... moves the pointer, no button (hover)
* - hold, then lift ................ right click
* - hold, then drag ................ left-button drag (a window by its title bar, a selection)
* - two fingers up / down .......... scroll wheel
*
* The listener gets pointer positions in the view's pixels; the activity maps them onto the
* compositor. Mouse events are not handled here - a mouse has real buttons.
*/
class PointerGestures(
private val slopPx: Float,
private val listener: Listener,
) {
interface Listener {
fun onMove(x: Float, y: Float)
/** [button] is an evdev code: BTN_LEFT, BTN_RIGHT. */
fun onButton(button: Int, pressed: Boolean, x: Float, y: Float)
fun onWheel(steps: Int)
fun onLongPress()
}
private val handler = Handler(Looper.getMainLooper())
private var downX = 0f
private var downY = 0f
private var downAt = 0L
private var moved = false
private var held = false // the long press fired
private var dragging = false // left button down after a hold
private var scrolling = false
private var scrollAnchorY = 0f
private val longPress = Runnable {
held = true
listener.onLongPress()
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = event.x; downY = event.y; downAt = event.eventTime
moved = false; held = false; dragging = false; scrolling = false
listener.onMove(event.x, event.y)
handler.postDelayed(longPress, HOLD_MS)
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
// A second finger: scrolling, and whatever the first one was doing is off.
handler.removeCallbacks(longPress)
if (dragging) { listener.onButton(BTN_LEFT, false, event.x, event.y); dragging = false }
scrolling = true
scrollAnchorY = event.getY(0)
return true
}
MotionEvent.ACTION_MOVE -> {
if (scrolling) {
val dy = event.getY(0) - scrollAnchorY
val steps = (dy / SCROLL_STEP_PX).toInt()
if (steps != 0) {
// Finger down = content up = wheel "up", which the compositor takes as negative.
listener.onWheel(-steps)
scrollAnchorY += steps * SCROLL_STEP_PX
}
return true
}
if (!moved && (abs(event.x - downX) > slopPx || abs(event.y - downY) > slopPx)) {
moved = true
handler.removeCallbacks(longPress)
if (held) {
// Held, then moved: a drag with the left button, from where the hold was.
dragging = true
listener.onButton(BTN_LEFT, true, downX, downY)
}
}
if (moved) listener.onMove(event.x, event.y)
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(longPress)
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL
when {
scrolling -> {}
dragging -> listener.onButton(BTN_LEFT, false, event.x, event.y)
held && !moved && !cancelled -> {
listener.onButton(BTN_RIGHT, true, downX, downY)
listener.onButton(BTN_RIGHT, false, downX, downY)
}
!moved && !cancelled && event.eventTime - downAt < TAP_MS -> {
listener.onButton(BTN_LEFT, true, downX, downY)
listener.onButton(BTN_LEFT, false, downX, downY)
}
}
scrolling = false; dragging = false; held = false
return true
}
MotionEvent.ACTION_POINTER_UP -> return true
}
return false
}
companion object {
const val BTN_LEFT = 0x110
const val BTN_RIGHT = 0x111
const val BTN_MIDDLE = 0x112
private const val HOLD_MS = 450L
private const val TAP_MS = 350L
private const val SCROLL_STEP_PX = 40f
fun slop(context: android.content.Context) = ViewConfiguration.get(context).scaledTouchSlop.toFloat()
}
}
@@ -0,0 +1,10 @@
package com.droiddeck.launcher.input
/** The control surface shown on a secondary Android display during a Linux session. */
enum class SecondScreenMode(val id: String, val label: String) {
NONE("none", "None"),
KEYBOARD_TRACKPAD("keyboard-trackpad", "Keyboard + trackpad"),
TERMINAL("terminal", "Terminal"),
}
data class SecondScreenDisplay(val id: Int, val label: String)
@@ -0,0 +1,151 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import kotlin.math.abs
/**
* The screen as a touchpad, the way Bannerlator's desktop containers work: the arrow is where it
* was, and a finger dragged anywhere moves it from there.
*
* - drag one finger .................. moves the pointer (relative, with a little acceleration)
* - tap .............................. left click, where the pointer is
* - second finger taps while one holds right click
* - two-finger tap ................... right click
* - two fingers up / down ............ scroll wheel
* - hold still, then drag ............ left-button drag
* - double-tap, hold, drag ........... left-button drag as well
*
* Positions handed to the listener are the pointer's, in the view's pixels; the caller keeps them
* inside the picture.
*/
class TouchpadGestures(
private val slopPx: Float,
private val listener: PointerGestures.Listener,
) {
/** The pointer, tracked here since every move is relative. */
var x = 0f
private set
var y = 0f
private set
var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f)
var sensitivity = 1.15f
private val handler = Handler(Looper.getMainLooper())
private var lastX = 0f
private var lastY = 0f
private var downAt = 0L
private var lastTapAt = 0L
private var travelled = 0f
private var dragging = false
private var held = false
private var secondDownAt = 0L
private var secondWasTap = false
private var twoFingers = false
private var scrollAnchorY = 0f
private var scrolled = false
private val longPress = Runnable {
held = true
dragging = true
listener.onLongPress()
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
}
fun place(px: Float, py: Float) {
x = px.coerceIn(bounds.left, bounds.right)
y = py.coerceIn(bounds.top, bounds.bottom)
}
fun onTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
lastX = event.x; lastY = event.y
downAt = event.eventTime
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
// A tap shortly before this touch: holding now drags (double-tap-and-hold).
if (event.eventTime - lastTapAt < DOUBLE_TAP_MS) {
dragging = true
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
} else {
dragging = false
handler.postDelayed(longPress, HOLD_MS)
}
return true
}
MotionEvent.ACTION_POINTER_DOWN -> {
handler.removeCallbacks(longPress)
twoFingers = true
secondDownAt = event.eventTime
secondWasTap = true
scrollAnchorY = (event.getY(0) + event.getY(1)) / 2f
return true
}
MotionEvent.ACTION_MOVE -> {
if (twoFingers && event.pointerCount >= 2) {
val mid = (event.getY(0) + event.getY(1)) / 2f
val dy = mid - scrollAnchorY
val steps = (dy / SCROLL_STEP_PX).toInt()
if (steps != 0) {
listener.onWheel(-steps)
scrollAnchorY += steps * SCROLL_STEP_PX
scrolled = true
secondWasTap = false
}
return true
}
val dx = event.x - lastX
val dy = event.y - lastY
lastX = event.x; lastY = event.y
travelled += abs(dx) + abs(dy)
if (travelled > slopPx) {
handler.removeCallbacks(longPress)
// A little acceleration: a slow finger is precise, a fast one crosses the screen.
val speed = (abs(dx) + abs(dy))
val gain = sensitivity * (1f + minOf(speed / 40f, 1.5f))
place(x + dx * gain, y + dy * gain)
listener.onMove(x, y)
}
return true
}
MotionEvent.ACTION_POINTER_UP -> {
// The second finger lifting quickly, with nothing scrolled: a right click.
if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TAP_MS && !scrolled) {
listener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
secondWasTap = false
}
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(longPress)
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL
when {
dragging -> listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
twoFingers -> {
// Both fingers down and up together, no scroll: a right click.
if (secondWasTap && !scrolled && !cancelled && event.eventTime - downAt < TAP_MS * 2) {
listener.onButton(PointerGestures.BTN_RIGHT, true, x, y)
listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
}
}
!cancelled && travelled <= slopPx && event.eventTime - downAt < TAP_MS -> {
listener.onButton(PointerGestures.BTN_LEFT, true, x, y)
listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
lastTapAt = event.eventTime
}
}
dragging = false; held = false; twoFingers = false
return true
}
}
return false
}
companion object {
private const val HOLD_MS = 500L
private const val TAP_MS = 300L
private const val DOUBLE_TAP_MS = 300L
private const val SCROLL_STEP_PX = 36f
}
}