This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-13 21:27:42 -04:00
1 parent 5fd47421f9
commit aecd2ebe1d
852 files changed
+4844 -46144

No files matched your search

@@ -123,7 +123,6 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("keyboardButton", on).apply()
}
/** The physical Select button opens the Steam menu instead of View/Select. */
fun setSelectSteam(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("selectSteam", on).apply()
}
@@ -151,7 +150,6 @@ object ControllerPrefs {
}
fun resetAll(context: Context) {
// On older Android versions clear() does not notify listeners; restore rumble explicitly.
prefs(context).edit().clear().putBoolean("rumble", true).apply()
}
@@ -1,15 +1,6 @@
package com.droiddeck.launcher.input
/**
* The Steam Deck controller's back grips and trackpads, which a handheld's own pad does not have:
* the second screen's Deck controls (DeckControlsPanel) drive them, and each change goes into the
* pad's ring ([FakeInputWriter.writeDeckControls]) for libfakeinput's Deck report.
*
* Trackpad positions are -1..1 each way with y up, as on a Deck; a pad touched reports its
* position, a pad clicked also reports full pressure.
*/
object DeckControls {
/** Bits of the ring's controls word - MUST match DECK_EXTRA_* in fakeinput_steam.cpp. */
const val L4 = 1
const val R4 = 2
const val L5 = 4
@@ -19,7 +10,6 @@ object DeckControls {
private const val LEFT_CLICK = 64
private const val RIGHT_CLICK = 128
/** The pad the Deck controller is made from (PadBridge's slot). */
private const val SLOT = 0
private var controls = 0
@@ -32,7 +22,6 @@ object DeckControls {
publish()
}
/** A finger on (or off) one trackpad at x, y in -1..1, y up. */
@Synchronized
fun setPad(right: Boolean, touching: Boolean, x: Float = 0f, y: Float = 0f) {
val at = if (right) 2 else 0
@@ -49,7 +38,6 @@ object DeckControls {
publish()
}
/** Everything let go - for when the panel goes away with a finger still on it. */
@Synchronized
fun releaseAll() {
if (controls == 0 && pads.all { it.toInt() == 0 } && pressure.all { it.toInt() == 0 }) return
@@ -2,21 +2,11 @@ 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;
@@ -30,36 +20,30 @@ public final class EvdevKeys {
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_DEL: return 14;
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;
@@ -70,23 +54,15 @@ public final class EvdevKeys {
}
}
/**
* 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');
@@ -2,16 +2,11 @@ package com.droiddeck.launcher.input;
import java.io.File;
/**
* Where the fake input rings live and how the guest is told about them. Kept apart from
* {@link FakeInputWriter}, which loads native code, so it can be tested on the JVM.
*/
final class FakeInputRingPaths {
static final String RING_DIR_NAME = "fakeinput-rings";
private FakeInputRingPaths() {}
/** The rings sit beside the fake evdev nodes: session/dev/input -> session/dev/fakeinput-rings. */
static File ringDir(File fakeInputDir) {
if (fakeInputDir == null) {
return null;
@@ -26,13 +21,6 @@ final class FakeInputRingPaths {
return ringDir != null ? new File(ringDir, "ring" + slot) : null;
}
/**
* The ring's path as the guest opens it. The session tree is bound into the guest at its own
* host path, spelled the way {@code Context.getFilesDir()} spells it (LinuxRuntime.binds), so
* the export has to use that same spelling. A canonical path is not that: where
* /data/user/0 is a link, or a separate mount, onto /data/data (ColorOS 16, #166) it resolves
* to a prefix nothing is bound at, and every pad, physical and on-screen, goes dead.
*/
static String exportPath(File ringFile) {
return ringFile.getAbsolutePath();
}
@@ -9,33 +9,17 @@ 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;
@@ -48,7 +32,6 @@ public class FakeInputWriter {
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;
@@ -58,17 +41,12 @@ public class FakeInputWriter {
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;
/** Bit 11: the Quick Access button. Snapshot only - an Xbox pad's evdev node has no such key;
* libfakeinput's Deck controller reads it from here. */
private static final int SNAPSHOT_IDX_QAM = 11;
private static final int EVENT_SIZE = 24;
@@ -76,11 +54,10 @@ public class FakeInputWriter {
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_MAGIC = 0x46494252;
private static final int RING_VERSION = 2;
private static final int RING_MAGIC_OFFSET = 0;
private static final int RING_VERSION_OFFSET = 4;
@@ -88,26 +65,18 @@ public class FakeInputWriter {
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]
// After the events - MUST match the blocks in fakeinput_steam.cpp. DeckImu carries the
// Deck-only motion, grips and trackpads. TritonShared carries the paired Steam Controller's
// native BLE reports and output reports, so the Steam client can see it as its own device.
private static final int RING_SNAPSHOT_AXES_OFFSET = 44;
private static final int IMU_OFFSET = RING_SIZE;
private static final int IMU_MAGIC = 0x31554D49; // IMU1
// Written by libfakeinput, not here: the client's SETTING_IMU_MODE | 0x80000000 (readImuMode).
private static final int IMU_MAGIC = 0x31554D49;
private static final int IMU_MODE_OFFSET = IMU_OFFSET + 4;
private static final int IMU_SEQ_OFFSET = IMU_OFFSET + 8;
private static final int IMU_ACCEL_OFFSET = IMU_OFFSET + 16; // short[3]
private static final int IMU_GYRO_OFFSET = IMU_OFFSET + 22; // short[3]
private static final int DECK_PADS_OFFSET = IMU_OFFSET + 28; // short[4]: left X, Y, right X, Y
private static final int DECK_PRESSURE_OFFSET = IMU_OFFSET + 36; // short[2]: left, right
private static final int DECK_CONTROLS_OFFSET = IMU_OFFSET + 40; // int: DeckControls bits
// Slot 0 only: what the pad is to the Steam client (libfakeinput's PAD_TYPE_*), | PAD_TYPE_SET.
private static final int IMU_ACCEL_OFFSET = IMU_OFFSET + 16;
private static final int IMU_GYRO_OFFSET = IMU_OFFSET + 22;
private static final int DECK_PADS_OFFSET = IMU_OFFSET + 28;
private static final int DECK_PRESSURE_OFFSET = IMU_OFFSET + 36;
private static final int DECK_CONTROLS_OFFSET = IMU_OFFSET + 40;
private static final int PAD_TYPE_OFFSET = IMU_OFFSET + 44;
private static final int PAD_TYPE_SET = 0x80000000;
public static final int PAD_TYPE_DECK = 0;
@@ -115,13 +84,10 @@ public class FakeInputWriter {
public static final int PAD_TYPE_XBOX = 2;
public static final int PAD_TYPE_DS4 = 3;
public static final int PAD_TYPE_DUALSENSE = 4;
/** The type chosen this process, written into a ring made after the choice too; -1 for none. */
private static volatile int padType = -1;
/** The paired controller's state, likewise written into a ring made after it connected. */
private static volatile boolean tritonConnected = false;
private static final int TRITON_OFFSET = RING_SIZE + 64;
private static final int TRITON_MAGIC = 0x4e525454; // TTRN
// Whether the paired controller is connected: libfakeinput offers its device only then.
private static final int TRITON_MAGIC = 0x4e525454;
private static final int TRITON_CONNECTED_OFFSET = TRITON_OFFSET + 4;
private static final int TRITON_INPUT_SEQ_OFFSET = TRITON_OFFSET + 8;
private static final int TRITON_REPORT_ID_OFFSET = TRITON_OFFSET + 16;
@@ -131,7 +97,6 @@ public class FakeInputWriter {
private static final int TRITON_OUTPUT_FEATURE_OFFSET = TRITON_OFFSET + 96;
private static final int TRITON_OUTPUT_LENGTH_OFFSET = TRITON_OFFSET + 100;
private static final int TRITON_OUTPUT_OFFSET = TRITON_OFFSET + 104;
// A feature read: libfakeinput bumps the request, the reply names the request it answers.
private static final int TRITON_GET_REQUEST_OFFSET = TRITON_OFFSET + 168;
private static final int TRITON_GET_REPLY_OFFSET = TRITON_OFFSET + 176;
private static final int TRITON_GET_REPORT_ID_OFFSET = TRITON_OFFSET + 184;
@@ -163,9 +128,6 @@ public class FakeInputWriter {
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;
@@ -186,7 +148,6 @@ public class FakeInputWriter {
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));
@@ -197,10 +158,6 @@ public class FakeInputWriter {
}
}
/**
* 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);
@@ -269,8 +226,6 @@ public class FakeInputWriter {
data.putLong(TRITON_GET_REPLY_OFFSET, 0L);
}
// Lock order: RING_LOCK, then the slot. Every writer holds the slot while it touches data, and
// re-checks it there: a writer that looked the slot up just before this ran finds it gone.
private static void releaseRingSlotLocked(int slot) {
RingSlot ringSlot = RING_SLOTS[slot];
if (ringSlot == null) {
@@ -433,8 +388,6 @@ public class FakeInputWriter {
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;
@@ -446,19 +399,12 @@ public class FakeInputWriter {
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);
@@ -466,9 +412,6 @@ public class FakeInputWriter {
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++) {
@@ -480,11 +423,9 @@ public class FakeInputWriter {
buttons |= (1 << SNAPSHOT_IDX_QAM);
}
long seq = ring.getLong(RING_SNAPSHOT_SEQ_OFFSET);
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1); // odd: write in progress
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 1);
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));
@@ -494,13 +435,9 @@ public class FakeInputWriter {
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
ring.putLong(RING_SNAPSHOT_SEQ_OFFSET, seq + 2);
}
/**
* Publishes the pad's motion for slot {@code slot}: accelerometer and gyro, already in the Deck
* controller's axes and units (see PadMotion). Safe from any thread.
*/
public static void writeMotion(int slot, short[] accel, short[] gyro) {
RingSlot ringSlot;
synchronized (RING_LOCK) {
@@ -511,7 +448,7 @@ public class FakeInputWriter {
ByteBuffer ring = ringSlot.data;
if (ring == null) return;
long seq = ring.getLong(IMU_SEQ_OFFSET);
ring.putLong(IMU_SEQ_OFFSET, seq + 1); // odd: write in progress
ring.putLong(IMU_SEQ_OFFSET, seq + 1);
nativeStoreFence();
for (int i = 0; i < 3; i++) {
ring.putShort(IMU_ACCEL_OFFSET + i * 2, accel[i]);
@@ -523,10 +460,6 @@ public class FakeInputWriter {
}
}
/**
* The motion the Steam client asked the Deck controller of slot {@code slot} for: its
* SETTING_IMU_MODE (0 = off), or -1 until it has said. Safe from any thread.
*/
public static int readImuMode(int slot) {
RingSlot ringSlot;
synchronized (RING_LOCK) {
@@ -540,11 +473,6 @@ public class FakeInputWriter {
}
}
/**
* Publishes the Deck's back grips and trackpads for slot {@code slot} (see DeckControls):
* {@code controls} is the DeckControls bit set, {@code pads} left X, Y, right X, Y and
* {@code pressure} left, right, already in the Deck's units. Safe from any thread.
*/
public static void writeDeckControls(int slot, int controls, short[] pads, short[] pressure) {
RingSlot ringSlot;
synchronized (RING_LOCK) {
@@ -566,20 +494,11 @@ public class FakeInputWriter {
}
}
/**
* Whether the pad, as the Steam client now sees it, has a Quick Access button: a Deck's or a
* Steam Controller's does, an Xbox or PlayStation pad's does not (libfakeinput drops the bit).
* Unset is the Deck, libfakeinput's default.
*/
public static boolean padHasQam() {
int type = padType;
return type < 0 || type == PAD_TYPE_DECK || type == PAD_TYPE_STEAM;
}
/**
* Switches what the pad is to the Steam client while the session runs ([PAD_TYPE_DECK],
* [PAD_TYPE_STEAM] or [PAD_TYPE_XBOX]); libfakeinput unplugs the old device and plugs in the new.
*/
public static void setPadType(int type) {
padType = type;
RingSlot ringSlot;
@@ -595,7 +514,6 @@ public class FakeInputWriter {
}
}
/** The paired Steam Controller came or went (SteamControllerBle): its device is plugged in or out. */
public static void setTritonConnected(int slot, boolean connected) {
tritonConnected = connected;
RingSlot ringSlot = tritonSlot(slot);
@@ -608,7 +526,6 @@ public class FakeInputWriter {
}
}
/** Publishes a native Triton input report (without the HID report ID byte). */
public static void writeTritonState(int slot, int reportId, byte[] report) {
if (report == null || report.length == 0 || report.length > TRITON_REPORT_MAX) return;
RingSlot ringSlot;
@@ -633,7 +550,6 @@ public class FakeInputWriter {
}
}
/** Returns the newest Steam-client output report after {@code lastSequence}, or null. */
public static byte[] readTritonOutput(int slot, long lastSequence) {
RingSlot ringSlot;
synchronized (RING_LOCK) {
@@ -657,7 +573,6 @@ public class FakeInputWriter {
}
}
/** The Steam client's newest unanswered feature read, or 0: its request number. */
public static long readTritonFeatureRequest(int slot) {
RingSlot ringSlot = tritonSlot(slot);
if (ringSlot == null) return 0L;
@@ -670,7 +585,6 @@ public class FakeInputWriter {
}
}
/** Answers feature read {@code request} with the controller's report, or a failure when null. */
public static void writeTritonFeatureReply(int slot, long request, byte[] report) {
RingSlot ringSlot = tritonSlot(slot);
if (ringSlot == null) return;
@@ -748,11 +662,6 @@ public class FakeInputWriter {
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;
@@ -760,7 +669,6 @@ public class FakeInputWriter {
buffer.clear();
hasChanges = false;
// Release all buttons
for (int i = 0; i < BUTTON_MAP.length; i++) {
if (prevButtonStates[i]) {
prevButtonStates[i] = false;
@@ -774,7 +682,6 @@ public class FakeInputWriter {
hasChanges = true;
}
// Zero all axes
if (prevThumbLX != 0) {
prevThumbLX = 0;
writeEvent(EV_ABS, ABS_X, 0);
@@ -823,9 +730,6 @@ public class FakeInputWriter {
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();
@@ -861,9 +765,6 @@ public class FakeInputWriter {
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) {
@@ -873,13 +774,9 @@ public class FakeInputWriter {
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));
boolean qam = state.isDown(PadState.QAM);
@@ -888,14 +785,11 @@ public class FakeInputWriter {
hasChanges = true;
}
// 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);
@@ -913,7 +807,6 @@ public class FakeInputWriter {
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) {
@@ -925,7 +818,6 @@ public class FakeInputWriter {
writeEvent(EV_ABS, ABS_GAS, tr);
}
// D-pad
int hatX = state.hatX();
int hatY = state.hatY();
if (forceResend || hatX != prevHatX) {
@@ -937,13 +829,11 @@ public class FakeInputWriter {
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;
}
}
@@ -13,17 +13,6 @@ 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,
@@ -38,7 +27,7 @@ class KeyboardHost(
init {
isFocusable = false
isFocusableInTouchMode = false
visibility = VISIBLE // present in the tree, draws nothing
visibility = VISIBLE
layoutParams = android.widget.FrameLayout.LayoutParams(1, 1)
}
@@ -46,8 +35,6 @@ class KeyboardHost(
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
@@ -80,9 +67,6 @@ class KeyboardHost(
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)
@@ -125,7 +109,6 @@ class KeyboardHost(
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
@@ -183,7 +183,6 @@ class OnScreenControls(
relayout()
}
/** Hide the full touch pad for an unobstructed screen while keeping its quick toggle available. */
fun setQuickHidden(hidden: Boolean) {
if (buttonsOnly || editing || quickHidden == hidden) return
if (hidden) releaseAll()
@@ -13,27 +13,8 @@ import java.io.File;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicIntegerArray;
/**
* 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. In a Steam session it is a Steam Deck controller
* to the client instead ({@link com.droiddeck.launcher.session.SteamDeckPad}), which has a Quick
* Access button of its own; an Xbox pad has none, so there the client's menu is reached with the
* Guide-then-A chord the client itself answers.
*
* <p>Each further controller is another player: slots 1 to 3, an Xbox 360 pad each, which in a
* Steam session only the client reads (libfakeinput) and hands games through Steam Input.
*/
public final class PadBridge {
private static final String TAG = "PadBridge";
/** Player slots: the session prepares a ring for each (SessionService). */
public static final int SLOTS = 4;
private static final float DEAD_ZONE = 0.12f;
private static final int[] JOYSTICK_AXES = {
@@ -48,18 +29,11 @@ public final class PadBridge {
KeyEvent.KEYCODE_BUTTON_THUMBL, KeyEvent.KEYCODE_BUTTON_THUMBR,
KeyEvent.KEYCODE_BUTTON_MODE, KeyEvent.KEYCODE_BUTTON_L2, KeyEvent.KEYCODE_BUTTON_R2
};
// The client takes A as part of the chord only once it has had Guide held for a while, and a
// client starved of CPU needs longer. Too short, and it acts on A as well, selecting whatever it
// had focused before opening QAM: with 80 ms of lead that was 3 times in 20 at rest, and 250 ms
// none in 20; with the session down to 1 fps a fixed 400 ms still let 3 in 15 through, where
// 1000 ms let none. The lead keeps 80 ms when frames are quick, for a QAM that feels immediate,
// and stretches to eight frames when they are slow.
private static final long QAM_GUIDE_LEAD_MIN_MS = 80;
private static final long QAM_GUIDE_LEAD_MAX_MS = 1500;
private static final int QAM_GUIDE_LEAD_FRAMES = 8;
private static final long QAM_A_HOLD_MS = 200;
private static final long QAM_GUIDE_TAIL_MS = 200;
// Off the main thread, so a busy UI cannot shorten or stretch the steps.
private static final Handler chordHandler;
static {
android.os.HandlerThread thread = new android.os.HandlerThread("qam-chord", android.os.Process.THREAD_PRIORITY_DISPLAY);
@@ -70,7 +44,6 @@ public final class PadBridge {
private final File fakeInputDir;
private final FakeInputWriter writer;
private final PadState state = new PadState();
/** The input device id holding each slot, or {@link #NO_CONTROLLER}. */
private final int[] owners = new int[SLOTS];
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
@@ -82,16 +55,11 @@ public final class PadBridge {
private boolean systemQamPressed;
private boolean qamChordActive;
private boolean qamSyntheticAPressed;
/** The Deck controller's Quick Access button, held for one tap. */
private boolean qamTapPressed;
private int qamChordGeneration;
/** Told on the main thread when a player uses the pad or the on-screen controls; see [setOnPlayerInput]. */
private volatile Runnable onPlayerInput;
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
// What reached the pad over the last stats window, so a report of "the pad does nothing" or
// "touch and the pad don't work together" shows in the app log whether input arrived, from
// which device, and whether it got to the ring. Logged only for a window that had input.
private static final long STATS_WINDOW_MS = 10_000;
private int statButtons, statAxes, statOnScreen, statDropped;
private String statDevice;
@@ -99,14 +67,8 @@ public final class PadBridge {
private final java.util.Set<Integer> seenDevices = new java.util.HashSet<>();
private int lastDeviceId = Integer.MIN_VALUE;
/** No physical controller is driving the pad: nothing yet, or the on-screen controls were last. */
public static final int NO_CONTROLLER = -1;
/**
* The Android input device id of the physical controller that last drove any slot, or
* {@link #NO_CONTROLLER}: where rumble goes when it names no slot of ours (RumbleComponent).
*/
private static volatile int activeControllerId = NO_CONTROLLER;
/** Per slot, the controller its rumble belongs to; slot 0's is none while the on-screen controls lead. */
private static final AtomicIntegerArray slotControllers = new AtomicIntegerArray(SLOTS);
static {
for (int slot = 0; slot < SLOTS; slot++) slotControllers.set(slot, NO_CONTROLLER);
@@ -114,7 +76,6 @@ public final class PadBridge {
public static int activeControllerId() { return activeControllerId; }
/** The controller playing in this ring slot, or the last one used for any other slot. */
public static int controllerForSlot(int slot) {
return slot >= 0 && slot < SLOTS ? slotControllers.get(slot) : activeControllerId;
}
@@ -126,12 +87,10 @@ public final class PadBridge {
for (int slot = 1; slot < SLOTS; slot++) playerStates[slot] = new PadState();
}
/** The physical Select button opens the Steam menu instead of View/Select (Setup → Controller). */
public void setSelectSteam(boolean on) {
selectSteam = on;
}
/** Opens the ring; safe to call more than once. */
public synchronized boolean start() {
if (!open) {
open = writer.open();
@@ -165,19 +124,13 @@ public final class PadBridge {
}
}
/** 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();
if ((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) return true;
if ((sources & InputDevice.SOURCE_JOYSTICK) != InputDevice.SOURCE_JOYSTICK) return false;
if (device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC) return true;
// Some composite keyboards advertise joystick input without any sticks or pad buttons.
// A keyboard's mouse ranges do not establish a joystick; a real hybrid's joystick ranges
// or physical controller buttons do. GAMEPAD above remains authoritative even with keys.
for (int axis : JOYSTICK_AXES) {
InputDevice.MotionRange range = device.getMotionRange(axis, InputDevice.SOURCE_JOYSTICK);
if (range != null && range.getMax() > range.getMin()) return true;
@@ -188,11 +141,9 @@ public final class PadBridge {
return false;
}
/** Whether this key belongs to the pad, rather than a keyboard on the same input device. */
public static boolean isControllerKeyEvent(KeyEvent event) {
InputDevice device = event.getDevice();
if (device == null || device.isVirtual()) return false;
// An explicit pad button is unambiguous even when a hybrid omits its capabilities.
if (KeyEvent.isGamepadButton(event.getKeyCode())) {
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|| device.supportsSource(InputDevice.SOURCE_JOYSTICK);
@@ -206,9 +157,6 @@ public final class PadBridge {
case KeyEvent.KEYCODE_MENU:
case KeyEvent.KEYCODE_HOME:
if (!isFromController(device)) return false;
// Without GAMEPAD, an alphabetic hybrid's keyboard arrows remain keyboard keys.
// Its ambiguous navigation keys need explicit pad/joystick event provenance;
// DPAD alone also describes ordinary keyboard arrows.
return device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|| device.getKeyboardType() != InputDevice.KEYBOARD_TYPE_ALPHABETIC
|| event.isFromSource(InputDevice.SOURCE_GAMEPAD)
@@ -217,17 +165,13 @@ public final class PadBridge {
}
}
/** Mouse motion on a composite controller still belongs to the pointer, not its sticks. */
public static boolean isControllerMotionEvent(MotionEvent event) {
InputDevice device = event.getDevice();
// An actual joystick event, like a pad button, survives a hybrid's missing capabilities.
return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual()
&& (device.supportsSource(InputDevice.SOURCE_GAMEPAD)
|| device.supportsSource(InputDevice.SOURCE_JOYSTICK));
}
/** A Bluetooth keyboard can share a device with a joystick. Classify the key, not just
* the device, so its letters and modifiers still reach the desktop keyboard. */
public static boolean isControllerKey(KeyEvent event) {
return isFromController(event.getDevice())
&& isPadKey(event.getKeyCode(), event.getDevice().getKeyboardType());
@@ -249,7 +193,6 @@ public final class PadBridge {
}
}
/** Whether any real controller is attached right now. */
public static boolean anyControllerConnected() {
for (int id : InputDevice.getDeviceIds()) {
if (isFromController(InputDevice.getDevice(id))) return true;
@@ -257,7 +200,6 @@ public final class PadBridge {
return false;
}
/** Publishes every currently connected controller so the client can enumerate all players. */
public synchronized void syncConnectedControllers() {
for (int deviceId : InputDevice.getDeviceIds()) {
InputDevice device = InputDevice.getDevice(deviceId);
@@ -265,11 +207,6 @@ public final class PadBridge {
}
}
/**
* Called (main thread) when a player presses a button, pushes a stick, trigger or d-pad past
* halfway, or uses the on-screen controls - the session hides its mouse cursor then. Resting
* sticks and trigger noise do not count.
*/
public void setOnPlayerInput(Runnable listener) {
onPlayerInput = listener;
}
@@ -283,7 +220,6 @@ public final class PadBridge {
});
}
/** @return true when the event was a pad button and has been consumed. */
public synchronized boolean onKeyEvent(KeyEvent event) {
if (!isControllerKeyEvent(event)) return false;
int slot = slotFor(event.getDevice());
@@ -297,8 +233,6 @@ public final class PadBridge {
case KeyEvent.KEYCODE_BUTTON_L1: pad.press(4, pressed); break;
case KeyEvent.KEYCODE_BUTTON_R1: pad.press(5, pressed); break;
case KeyEvent.KEYCODE_BUTTON_SELECT:
// Optionally (Setup → Controller) the physical Select button opens the Steam menu
// instead of View/Select: on some handhelds it sits next to the Steam button.
if (selectSteam) pad.press(PadState.GUIDE, pressed);
else pad.press(6, pressed);
break;
@@ -307,8 +241,6 @@ public final class PadBridge {
case KeyEvent.KEYCODE_MENU: pad.press(7, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: pad.press(8, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: pad.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: pad.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = pressed ? 1f : 0f; break;
@@ -327,7 +259,6 @@ public final class PadBridge {
return true;
}
/** @return true when the event was a pad's sticks/triggers and has been consumed. */
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isControllerMotionEvent(event)) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
@@ -337,14 +268,11 @@ public final class PadBridge {
statAxes++;
scheduleStats();
pad.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.
pad.leftY = axis(event, MotionEvent.AXIS_Y);
pad.rightX = axis(event, MotionEvent.AXIS_Z);
pad.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);
pad.leftTrigger = lt;
@@ -363,10 +291,6 @@ public final class PadBridge {
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);
activeControllerId = NO_CONTROLLER;
@@ -377,12 +301,6 @@ public final class PadBridge {
publish();
}
/**
* A controller the app reads itself rather than through Android's input (the Steam Controller
* over Bluetooth, SteamControllerBle): its whole state, merged into the one exported slot as a
* physical pad's events are. Android has no device for it, so a game's rumble cannot reach it.
* It streams its state whether or not anything moved; {@code changed} is whether this one did.
*/
public synchronized void applyExternal(java.util.function.Consumer<PadState> mutation, boolean changed) {
mutation.accept(state);
if (changed) {
@@ -394,21 +312,15 @@ public final class PadBridge {
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;
// A Deck or Steam Controller's QAM button is held for as long as the touch one is.
if (qamStarted && !nativeQam()) startQamChord();
else publish();
}
/**
* Everything released and centred - for when the controller stops feeding the game (the
* session drawer opened), so a button or stick held at that moment is not left down in it.
*/
public synchronized void releaseAll() {
state.clear();
publish();
@@ -419,23 +331,16 @@ public final class PadBridge {
}
}
/** A controller went away: its player's buttons are let go, and a further player's pad is unplugged. */
public synchronized void onDeviceRemoved(int deviceId) {
for (int slot = 0; slot < SLOTS; slot++) {
if (owners[slot] == deviceId) free(slot);
}
}
/**
* Whether the client's pad has its own QAM button to press. The Deck's sysfs being up is not
* enough: the drawer can make the pad an Xbox or PlayStation one, which has none, and a press
* of it never reaches the client.
*/
private static boolean nativeQam() {
return SessionState.getDeckPad() && FakeInputWriter.padHasQam();
}
/** Opens the client's Quick Access menu: a tap of the pad's button, or the Guide-then-A chord. */
public synchronized void triggerQam() {
if (!nativeQam()) {
startQamChord();
@@ -488,7 +393,6 @@ public final class PadBridge {
publish();
}
/** The slot this controller plays in: the one it has, else the first free one, else player 1's. */
private int slotFor(InputDevice device) {
int id = device.getId();
if (owners[0] == id) return 0;
@@ -527,7 +431,6 @@ public final class PadBridge {
}
}
/** Per event, so the common case - the same pad as last time - is a single compare. */
private void noteDevice(InputDevice device, int slot) {
activeControllerId = device.getId();
slotControllers.set(slot, device.getId());
@@ -11,31 +11,14 @@ import android.util.Log
import android.view.Surface
import kotlin.math.roundToInt
/**
* The handheld's own gyro and accelerometer, as the Steam Deck controller's (SteamDeckPad).
*
* The phone is the controller's body, so its motion sensors are the ones a Deck's would be. Android
* reports them in the device's natural orientation; they are turned to the screen as it is shown
* (x right, y up, z towards the player - SDL's frame for a gamepad), then to the Deck's own axes
* and units as SDL's Deck driver undoes them (SDL_hidapi_steamdeck.c): X right, Y away from the
* player, Z up; 1 g = 16384, 2000 °/s = 32768. The Steam client calibrates the gyro itself.
*
* Sensors run only while the session is on screen with the pad a Deck controller, and the client
* wants motion (see [follow]), sampled as often as the Deck reports (4 ms); each reading goes
* straight into the pad's ring ([FakeInputWriter.writeMotion]), where libfakeinput's 4 ms report
* picks up the latest.
*/
class PadMotion(private val context: Context, private val rotation: () -> Int) : SensorEventListener {
private val sensors = context.getSystemService(SensorManager::class.java)
private var thread: HandlerThread? = null
/** Readings are taken only while this is set; a callback already queued when [stop] ran drops. */
@Volatile private var active = false
// Touched only on the worker thread.
private val accel = ShortArray(3)
private val gyro = ShortArray(3)
private var reading = false
private var idlePolls = 0
// Asking the display costs more than the rest of a reading, which arrives every 2 ms.
private var turn = Surface.ROTATION_0
private var turnAt = 0L
@@ -65,8 +48,6 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
val worker = thread ?: return
thread = null
active = false
// On the worker, after any poll or reading already queued there, so nothing registers again
// or overwrites the still controller.
Handler(worker.looper).post {
sensors?.unregisterListener(this)
reading = false
@@ -76,12 +57,6 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
worker.quitSafely()
}
/**
* Reads the sensors while the client wants motion: the Deck's IMU mode (unknown counts as
* wanted), or Steam's touch controls asking for gyro. A game whose layout has no gyro turns the
* mode off; Steam's own menus keep it on. The client also turns it off and on again for a few
* ms whenever it re-applies a layout, so the sensors stop only after two polls without it.
*/
private fun follow(handler: Handler, gyroscope: Sensor?, accelerometer: Sensor?) {
val touch = SteamTouchDevice.current
val wanted = FakeInputWriter.readImuMode(SLOT) != 0 ||
@@ -101,7 +76,6 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
}
}
/** A still controller, not one frozen mid-turn. */
private fun still() {
gyro.fill(0)
FakeInputWriter.writeMotion(SLOT, accel, gyro)
@@ -115,7 +89,6 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
turn = rotation()
turnAt = event.timestamp
}
// Natural orientation to the screen's: Android's display-rotation transform.
val x: Float
val y: Float
when (turn) {
@@ -132,7 +105,6 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
Sensor.TYPE_ACCELEROMETER -> { target = accel; scale = ACCEL_COUNTS_PER_M_S2 }
else -> return
}
// Screen frame (right, up, towards the player) to the Deck's (right, away, up).
target[0] = counts(x * scale)
target[1] = counts(-z * scale)
target[2] = counts(y * scale)
@@ -146,11 +118,8 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
companion object {
private const val TAG = "PadMotion"
/** The pad the Deck controller is made from (PadBridge's slot). */
private const val SLOT = 0
/** The Deck controller's report interval (libfakeinput: DECK_REPORT_INTERVAL_US). */
private const val SAMPLING_US = 4000
/** How often [follow] checks whether the client wants motion. */
private const val POLL_MS = 500L
private const val ROTATION_REFRESH_NS = 250_000_000L
private const val ACCEL_COUNTS_PER_M_S2 = 16384f / SensorManager.GRAVITY_EARTH
@@ -1,11 +1,5 @@
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
@@ -25,7 +19,6 @@ class PadState {
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
@@ -36,7 +29,6 @@ class PadState {
buttons = other.buttons
}
/** Everything released and centred. */
fun clear() {
leftX = 0f; leftY = 0f; rightX = 0f; rightY = 0f
leftTrigger = 0f; rightTrigger = 0f
@@ -55,9 +47,7 @@ class PadState {
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
/** The Quick Access button: a Deck controller's (SteamDeckPad) only, since an Xbox pad has none. */
const val QAM = 13
}
}
@@ -7,25 +7,12 @@ 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()
@@ -36,8 +23,8 @@ class PointerGestures(
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 held = false
private var dragging = false
private var scrolling = false
private var scrollAnchorY = 0f
private val longPress = Runnable {
@@ -55,7 +42,6 @@ class PointerGestures(
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
@@ -67,7 +53,6 @@ class PointerGestures(
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
}
@@ -77,7 +62,6 @@ class PointerGestures(
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)
}
@@ -5,18 +5,15 @@ import android.view.Display
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
/** The control surface shown on a secondary Android display during a Linux session. */
enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
NONE("none", R.string.second_mode_none),
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
TERMINAL("terminal", R.string.second_mode_terminal),
/** The Steam Deck controller's back grips and trackpads; offered while the pad is one. */
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
}
data class SecondScreenDisplay(val id: Int, val label: String)
/** The presentation-capable displays shared by the session controls and Android app launcher. */
object SecondScreenDisplays {
fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List<SecondScreenDisplay> =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION)
@@ -11,7 +11,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.io.IOException
/** Text selections shared by Android and the guest while the session is visible. */
class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
private val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
private val handler = Handler(Looper.getMainLooper())
@@ -20,8 +19,6 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
private val androidListener = ClipboardManager.OnPrimaryClipChangedListener { refresh() }
private val guestListener = object : WaylandCompositor.ClipboardListener {
override fun onGuestClipboardText(text: String) {
// Native callbacks arrive on the compositor thread. Do not publish a delayed callback
// after this activity has paused or been replaced.
handler.post {
if (active && hasFocus() && WaylandCompositor.isClipboardListener(this)) {
val current = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text
@@ -49,11 +46,9 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
handler.removeCallbacksAndMessages(null)
}
/** Android 10+ permits clipboard reads only with window focus. Resume can precede focus. */
fun refresh() {
if (!active || !hasFocus()) return
val clip = clipboard.primaryClip
// Only share literal text, never resolve content URIs or load copied files.
if (clip == null) {
publish(null)
} else if (clip.itemCount > 0) {
@@ -63,8 +58,6 @@ class SessionClipboard(context: Context, private val hasFocus: () -> Boolean) {
private fun publish(text: String?) {
WaylandCompositor.setClipboardText(text)
// Gamescope needs the same selection in its own Xwayland. Rename complete UTF-8 text
// into place so its helper never sees half a launch command. Kept in private app data.
val pending = File(hostFile.parentFile, "android-clipboard.pending")
try {
hostFile.parentFile?.mkdirs()
@@ -18,20 +18,11 @@ import java.nio.ByteOrder
import java.util.ArrayDeque
import java.util.UUID
/**
* Reads the Steam Controller (2025, Triton) through its Valve BLE service. State reports remain
* native Triton packets and are published to the session's separate 28DE:1303 HID device. Steam's
* output reports travel back to their matching BLE characteristics, preserving grip capacitance,
* trackpads, sensors, and controller haptics without folding the controller into the Deck target.
*
* Lizard mode is refreshed while connected; when a session ends, the controller restores it itself.
*/
@SuppressLint("MissingPermission") // BLUETOOTH is granted at install below targetSdk 31
@SuppressLint("MissingPermission")
class SteamControllerBle(private val context: Context) {
private val thread = HandlerThread("steam-controller-ble").apply { start() }
private val handler = Handler(thread.looper)
private val outputReports = mutableMapOf<Int, UUID>()
/** GATT allows one operation at a time: writes carry a value, a feature read none. */
private val queuedWrites = ArrayDeque<Pair<UUID, ByteArray?>>()
private var gatt: BluetoothGatt? = null
private var running = false
@@ -42,10 +33,8 @@ class SteamControllerBle(private val context: Context) {
private var discoveries = 0
private var outputSequence = 0L
private var outputWritePending = false
/** The Steam client's feature read being answered, so the poll queues each one once. */
private var featureRead = 0L
/** Looks for a paired Steam Controller and keeps a connection to it until [stop]. */
fun start() = handler.post {
if (running) return@post
running = true
@@ -53,7 +42,6 @@ class SteamControllerBle(private val context: Context) {
connect()
}
/** Lets the controller go (it returns to lizard mode by itself); this object is done after. */
fun stop() = handler.post {
running = false
handler.removeCallbacksAndMessages(null)
@@ -118,7 +106,6 @@ class SteamControllerBle(private val context: Context) {
if (running) handler.postDelayed(::connect, RETRY_MS)
return
}
// The Triton needs data length extensions, which Android enables for a large MTU.
if (!g.requestMtu(517)) subscribe(g)
}
@@ -160,7 +147,6 @@ class SteamControllerBle(private val context: Context) {
if (g === gatt) onFeatureRead(characteristic.value.takeIf { status == BluetoothGatt.GATT_SUCCESS })
}
// Android 13 hands the value over with the call; older ones only through the characteristic.
override fun onCharacteristicChanged(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic, value: ByteArray) {
if (g === gatt && characteristic.uuid == input) onState(value)
}
@@ -177,8 +163,6 @@ class SteamControllerBle(private val context: Context) {
if (service == null) {
Log.w(TAG, "no Valve service on \"${g.device.name}\" (attempt ${discoveries + 1}); services: " +
g.services.joinToString { it.uuid.toString().take(8) })
// Android may answer from the service list its HID host cached, which can lack the
// vendor service: ask the controller again before giving up on it.
if (++discoveries < 3) {
refreshCache(g)
handler.postDelayed({ if (g === gatt) g.discoverServices() }, 500)
@@ -213,13 +197,11 @@ class SteamControllerBle(private val context: Context) {
g.writeDescriptor(cccd)
}
/** BluetoothGatt.refresh(): hidden, but used to drop stale service caches. */
private fun refreshCache(g: BluetoothGatt) {
runCatching { g.javaClass.getMethod("refresh").invoke(g) }
.onFailure { Log.w(TAG, "could not refresh the service cache", it) }
}
/** SDL's DisableSteamTritonLizardMode: ID_SET_SETTINGS_VALUES (0x87), setting 9 = off. */
private fun refreshLizardMode() {
if (!connected) return
val msg = ByteArray(FEATURE_BYTES)
@@ -228,18 +210,15 @@ class SteamControllerBle(private val context: Context) {
handler.postDelayed(::refreshLizardMode, LIZARD_REFRESH_MS)
}
/** Preserve the full 0x45 or 0x47 packet so Triton-only bits reach Steam's native driver. */
private fun onState(data: ByteArray) {
if (data.size < STATE_BYTES) return
FakeInputWriter.writeTritonState(SLOT, reportId, data)
}
/** A neutral report prevents a link lost mid-press from leaving controls held. */
private fun release() {
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
}
/** Drain Steam HID output reports and write each to Triton's matching BLE characteristic. */
private fun pollOutput() {
if (!running || !connected || gatt == null) return
FakeInputWriter.readTritonOutput(SLOT, outputSequence)?.let { output ->
@@ -249,14 +228,12 @@ class SteamControllerBle(private val context: Context) {
val request = FakeInputWriter.readTritonFeatureRequest(SLOT)
if (request != 0L && request != featureRead) {
featureRead = request
// Behind any queued write, so a read answers the feature report written before it.
queuedWrites.addLast(REPORT to null)
writeNextOutput()
}
handler.postDelayed(::pollOutput, OUTPUT_POLL_MS)
}
/** The controller's answer to a feature read (its info, for one), or null when the read failed. */
private fun onFeatureRead(value: ByteArray?) {
outputWritePending = false
if (featureRead != 0L) {
@@ -277,7 +254,6 @@ class SteamControllerBle(private val context: Context) {
return
}
}
// SDL's BLE driver removes the HID report ID and trailing padding byte before transmission.
enqueueOutput(characteristic, report.copyOfRange(1, report.size - 1))
}
@@ -319,13 +295,11 @@ class SteamControllerBle(private val context: Context) {
companion object {
private const val TAG = "SteamControllerBle"
/** The paired controller's native Triton reports live in slot 0's extended ring. */
private const val SLOT = 0
private const val RETRY_MS = 5_000L
private const val LIZARD_REFRESH_MS = 3_000L
private const val OUTPUT_POLL_MS = 4L
private const val OUTPUT_RETRY_MS = 10L
/** SDL's 64-byte feature report less the report ID and the trailing byte. */
private const val FEATURE_BYTES = 62
private const val STATE_BYTES = 45
private const val OUTPUT_UUID_PREFIX = "100f6c"
@@ -341,7 +315,6 @@ class SteamControllerBle(private val context: Context) {
device.type and BluetoothDevice.DEVICE_TYPE_LE != 0 &&
(device.name ?: "").let { it.startsWith("Steam Ctrl") || it.startsWith("SteamController") }
/** Whether a session should expose a Triton HID node for a paired controller. */
@JvmStatic
fun hasPairedController(context: Context): Boolean {
val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter ?: return false
@@ -350,12 +323,10 @@ class SteamControllerBle(private val context: Context) {
.getOrDefault(false)
}
/** A Steam Controller is connected and feeding its native HID reports. */
@Volatile @JvmStatic
var connected = false
private set
/** Notifies the activity when [connected] changes. */
@Volatile @JvmStatic
var listener: (() -> Unit)? = null
}
@@ -6,21 +6,8 @@ import android.graphics.BitmapFactory
import android.util.LruCache
import java.io.File
/**
* What each touch control is bound to, and the icon it shows - Steam's, as its configurator keeps
* them.
*
* A Steam Input binding is one string: `<action>, <label>, <icon>, <#foreground #background>`, e.g.
* `xinput_button A, Jump, ghost_045_move_0400.png, #232323 #E4E4E4`. The icon is a file name looked
* up as Steam does (steamui.so): the game's own `TouchMenuIcons` folder, then the binding icon
* library `tenfoot/resource/images/library/controller/binding_icons`. Steam draws it filled with
* the foreground colour through its own alpha (mask-image) on a button of the background colour.
* Steam Link is sent these per control by the client it streams from; here they are read from the
* game's touch config, and editing one writes the binding string back, as the configurator does.
*/
object SteamTouchBindings {
/** Steam's binding icon colours (the configurator's palette, steamui sp.js), and its defaults. */
val PALETTE = listOf(
"#FFFFFF", "#E4E4E4", "#AAAAAA", "#787878", "#434343", "#222222", "#0000AD", "#0045AD", "#0074AD",
"#00ADAD", "#33AD69", "#00AD3D", "#00AD00", "#48B119", "#74AD00", "#96AD00", "#ADA200", "#AD5D00",
@@ -29,7 +16,6 @@ object SteamTouchBindings {
const val DEFAULT_FOREGROUND = "#232323"
const val DEFAULT_BACKGROUND = "#E4E4E4"
/** A parsed binding string. Empty strings for absent fields. */
data class Binding(val action: String, val label: String, val icon: String, val foreground: String, val background: String) {
fun compose(): String =
if (icon.isEmpty() && foreground.isEmpty() && background.isEmpty()) "$action, $label, "
@@ -45,10 +31,8 @@ object SteamTouchBindings {
colors.getOrNull(0).orEmpty(), colors.getOrNull(1).orEmpty())
}
/** Where a control's binding lives: its input in the group the preset puts on its source. */
data class Ref(val groupId: String, val input: String)
/** The source and input names a control reads (D-pad: its four directions). */
private fun inputsOf(type: Int): List<Pair<String, String>> = when (type) {
SteamTouchConfig.A -> listOf("button_diamond" to "button_a")
SteamTouchConfig.B -> listOf("button_diamond" to "button_b")
@@ -69,13 +53,8 @@ object SteamTouchBindings {
else -> emptyList()
}
/** D-pad directions, in the order [refsFor] returns them: up, down, left, right. */
val DPAD_INPUTS = listOf("dpad_north", "dpad_south", "dpad_west", "dpad_east")
/**
* Where control [type]'s bindings are for preset [preset] (the action set less one) and its
* active [layers]: a layer's group wins over the base's for the same source.
*/
fun refsFor(mappings: KeyValues.Node, type: Int, preset: Int, layers: List<Int> = emptyList()): List<Ref?> {
val presets = mappings.children("preset").associateBy { it.string("id")?.toIntOrNull() ?: -1 }
val stack = layers.reversed().mapNotNull { presets[it - 1] } + listOfNotNull(presets[preset] ?: presets.values.firstOrNull())
@@ -90,7 +69,6 @@ object SteamTouchBindings {
parts.getOrNull(0) == source && parts.getOrNull(1) == "active" && !parts.contains("modeshift")
}?.first
/** The binding at [ref]: its first activator's first binding (Full_Press when there is one). */
fun bindingAt(mappings: KeyValues.Node, ref: Ref): Binding? {
val group = mappings.children("group").firstOrNull { it.string("id") == ref.groupId } ?: return null
val activators = group.child("inputs")?.child(ref.input)?.child("activators") ?: return null
@@ -98,7 +76,6 @@ object SteamTouchBindings {
return activator?.child("bindings")?.string("binding")?.let(::parse)
}
/** A short glyph for a binding with no icon or label: what it presses. */
fun glyph(binding: Binding?): String? {
val words = binding?.action?.split(' ') ?: return null
val arg = words.getOrNull(1)?.uppercase() ?: return null
@@ -123,12 +100,7 @@ object SteamTouchBindings {
"LEFT_ARROW" to "←", "RIGHT_ARROW" to "→",
)
// ---- Writing a binding back ----
/**
* Rewrites every binding of [ref]'s input in config [text] (VDF) with [change], keeping the rest
* of the file byte for byte. Returns the new text, or null when the input is not there.
*/
fun rewrite(text: String, ref: Ref, change: (Binding) -> Binding): String? {
val tokens = Vdf.tokens(text)
val group = Vdf.blocks(tokens, 0, tokens.size, "group").firstOrNull { (s, e) ->
@@ -145,7 +117,6 @@ object SteamTouchBindings {
return out.toString()
}
/** A VDF tokenizer that keeps where each token sits, for edits that leave the rest untouched. */
private object Vdf {
class Token(val text: String, val quoted: Boolean, val start: Int, val end: Int)
@@ -175,8 +146,6 @@ object SteamTouchBindings {
return out
}
/** The bodies (token index ranges inside the braces) of direct children named [key] of the
* block spanning [from, to). */
fun blocks(tokens: List<Token>, from: Int, to: Int, key: String): List<Pair<Int, Int>> {
val found = mutableListOf<Pair<Int, Int>>()
var i = from
@@ -200,7 +169,6 @@ object SteamTouchBindings {
}
i++
}
// The whole file is one top-level block ("controller_mappings"): look inside it too.
if (found.isEmpty() && from == 0) {
val top = tokens.indexOfFirst { it.text == "{" && !it.quoted }
if (top > 0) {
@@ -217,7 +185,6 @@ object SteamTouchBindings {
return found
}
/** A direct key-value of the block spanning [from, to). */
fun value(tokens: List<Token>, from: Int, to: Int, key: String): String? {
var depth = 0
var i = from
@@ -232,7 +199,6 @@ object SteamTouchBindings {
}
}
// ---- Icons ----
private val cache = object : LruCache<String, Bitmap>(24 * 1024 * 1024) {
override fun sizeOf(key: String, value: Bitmap) = value.byteCount
@@ -241,7 +207,6 @@ object SteamTouchBindings {
fun libraryDir(context: Context) = File(SteamTouchConfig.steamRoot(context), "tenfoot/resource/images/library/controller/binding_icons")
/** The game's own icons folder (`TouchMenuIcons` in its install directory), when it has one. */
fun gameIconsDir(context: Context, appId: Int): File? = try {
val manifest = File(SteamTouchConfig.steamRoot(context), "steamapps/appmanifest_$appId.acf")
val installDir = KeyValues.parse(manifest.readText()).let { it.child("AppState") ?: it }.string("installdir")
@@ -257,7 +222,6 @@ object SteamTouchBindings {
return File(SteamTouchConfig.steamRoot(context), "steamui/images/controller/$name").takeIf { it.isFile }
}
/** An icon, decoded at about [size] px. Blocking (reads a file); cached. */
fun icon(context: Context, appId: Int, name: String, size: Int = 128): Bitmap? {
val key = "$appId/$name/$size"
cache.get(key)?.let { return it }
@@ -276,7 +240,6 @@ object SteamTouchBindings {
fun cachedIcon(appId: Int, name: String, size: Int = 128): Bitmap? = cache.get("$appId/$name/$size")
/** Icon names for the picker: the game's own first, then Steam's library by category. */
fun iconNames(context: Context, appId: Int): List<String> {
val own = gameIconsDir(context, appId)?.list()?.filter { it.endsWith(".png", true) }?.sorted().orEmpty()
val library = libraryDir(context).list()?.filter { it.endsWith(".png", true) && it != "special_blank.png" }?.sorted().orEmpty()
@@ -7,25 +7,9 @@ import java.io.ByteArrayOutputStream
import java.io.File
import java.io.RandomAccessFile
/**
* Steam's touch configs, read and written where Steam keeps them.
*
* A touch config is a Steam Input config (`controller_mobile_touch`) like any other - bindings per
* action set, synced to the account, shared as community configs - with one extra key,
* `touch_layout`: where each on-screen control sits, per action set, as a hex-encoded
* `CVirtualControllerLayouts` protobuf (steammessages_virtualcontroller.proto). Steam Link is
* handed both by the client it streams from; here the client tells the device only the app and
* action set it is on (SteamTouchDevice), so the config is found on disk: the file the client's
* console log says it loaded for the touch controller, else the app's entry in
* `configset_controller_mobile_touch.vdf`. With no layout in it, controls go where Steam Link puts
* them by default. Saving a layout writes `touch_layout` into the app's autosave config, as the
* client does when Steam Link saves one; Steam Cloud picks that file up like any autosave.
* (docs/development/steam-touch-controller.md.)
*/
object SteamTouchConfig {
private const val TAG = "SteamTouch"
// EControllerElementType.
const val THUMB = 0
const val STEAM = 1
const val JOYSTICK_LEFT = 2
@@ -43,7 +27,7 @@ object SteamTouchConfig {
const val TRIGGER_RIGHT = 14
const val BUMPER_LEFT = 15
const val BUMPER_RIGHT = 16
const val MACRO_0 = 17 // 17..24 = macros 0-7
const val MACRO_0 = 17
const val TRACKPAD_CENTER = 25
const val TRACKPAD_LEFT = 26
const val TRACKPAD_RIGHT = 27
@@ -53,27 +37,19 @@ object SteamTouchConfig {
const val MAGNIFYING_GLASS = 29
const val PASTE = 34
/** Controls a layout may place though no binding asks for them (Steam Link's tray). */
val OPTIONAL = setOf(PASTE)
/** A control's place: centre as a fraction of the screen, and its scale. */
data class Element(val type: Int, val visible: Boolean, val x: Float, val y: Float, val xScale: Float = 1f, val yScale: Float = 1f)
data class Layout(val actionSet: Int, val elements: List<Element>, val color: FloatArray?, val version: Int?)
/** A decoded `touch_layout`; [rest] is every other top-level field, written back untouched. */
class Layouts(val layouts: List<Layout>, val rest: ByteArray) {
fun forActionSet(id: Int): Layout? = layouts.firstOrNull { it.actionSet == id }
/** The per-game options Steam Link keeps beside the layouts (CVirtualControllerLayouts
* fields 2-4): input mode, mouse mode, trackpad sensitivity. */
val options: Options get() = Options.decode(rest)
}
/** EInputMode: 1 mouse, 2 controller, 3 both. EMouseMode: 2 absolute cursor (direct touch),
* 3 touch, 4 relative (trackpad); 0 = not set. */
data class Options(val inputMode: Int = INPUT_CONTROLLER, val mouseMode: Int = 0, val trackpadSensitivity: Float = 1f) {
/** [rest] with these options in place of its own fields 2-4, the rest kept as it was. */
fun encodeInto(rest: ByteArray): ByteArray {
val out = ByteArrayOutputStream()
val p = Proto(rest)
@@ -116,7 +92,6 @@ object SteamTouchConfig {
const val MOUSE_TOUCH = 3
const val MOUSE_RELATIVE = 4
/** The config's action sets in preset order: id as the device is told (preset id + 1) and title. */
fun actionSets(config: Config): List<Pair<Int, String>> {
val mappings = config.mappings ?: return listOf(1 to "Default")
val titles = mappings.child("actions")?.entries?.mapNotNull { (key, v) ->
@@ -130,40 +105,30 @@ object SteamTouchConfig {
return sets.ifEmpty { listOf(1 to "Default") }
}
/** A config as the overlay needs it. */
class Config(
val file: File?,
val text: String?,
val layouts: Layouts?,
/** Bound controls per preset (action set id - 1). */
val available: Map<Int, Set<Int>>,
/** The parsed config, for its bindings (SteamTouchBindings). */
val mappings: KeyValues.Node? = null,
) {
/** The config's own title, as Steam Link's tray shows it ("Default", "Gamepad"…). */
val title: String? get() = mappings?.string("title")?.let { t ->
if (t.startsWith("#")) mappings.child("localization")?.child("english")?.string("title") ?: "Default" else t
}
/** The controls to show for [actionSet] (as the device is told it) and [layers]. */
fun availableFor(actionSet: Int, layers: List<Int>): Set<Int> {
val base = available[presetOf(actionSet)] ?: available.values.firstOrNull() ?: DEFAULT_SET
return layers.fold(base) { set, layer -> set + (available[presetOf(layer)] ?: emptySet()) } + ALWAYS
}
}
/** Big Picture's own config uses Steam's basic UI bindings: the default set. */
private val DEFAULT_SET = setOf(DPAD, A, B, X, Y, SELECT, START)
private val ALWAYS = setOf(STEAM, THUMB, KEYBOARD)
/** The layout entry for the action set the device was told about (the client counts from 1,
* 0 for an app with none). */
fun layoutIdOf(actionSet: Int) = if (actionSet <= 0) 1 else actionSet
private fun presetOf(actionSet: Int) = layoutIdOf(actionSet) - 1
// ---- Where Steam keeps them ----
/** A game's name from its app manifest, when it is installed. */
fun gameName(context: Context, appId: Int): String? = try {
val kv = KeyValues.parse(File(steamRoot(context), "steamapps/appmanifest_$appId.acf").readText())
(kv.child("AppState") ?: kv).string("name")
@@ -181,7 +146,6 @@ object SteamTouchConfig {
?.maxByOrNull { it.lastModified() }?.let { File(it, "config") }
}
/** The signed-in account (loginusers.vdf's MostRecent) as a 32-bit account id. */
private fun accountId(context: Context): Long? = try {
val users = KeyValues.parse(File(steamRoot(context), "config/loginusers.vdf").readText())
val node = users.child("users")
@@ -192,11 +156,8 @@ object SteamTouchConfig {
null
}
/** The config the client has for app [appId] on the touch controller. Blocking: reads files. */
fun load(context: Context, appId: Int): Config {
val dir = configDir(context)
// The app's own saved config is what the client loads when there is one (its configset
// entry); otherwise what it logged loading - a template, an official or a workshop config.
val file = dir?.let { autosaveConfig(it, appId) }
?: loggedConfig(context, appId)?.takeIf { isTouchConfig(it) }
?: dir?.let { configsetConfig(context, it, appId) }
@@ -220,9 +181,6 @@ object SteamTouchConfig {
private fun isTouchConfig(file: File) = file.isFile &&
file.bufferedReader().use { r -> generateSequence { r.readLine() }.take(40).any { it.contains("controller_mobile_touch") } }
/** From the client's console log: the last config it loaded for [appId] on the touch controller
* (`Loaded Config for ... App ID <n>, Controller <i>: <path>`, where controller i reported
* type 43). Guest paths come back as the app's own. */
private fun loggedConfig(context: Context, appId: Int): File? = try {
val log = File(steamRoot(context), "logs/console_log.txt")
val tail = RandomAccessFile(log, "r").use { raf ->
@@ -249,7 +207,6 @@ object SteamTouchConfig {
null
}
/** The app's entry in configset_controller_mobile_touch.vdf. */
private fun configsetConfig(context: Context, dir: File, appId: Int): File? = try {
val set = KeyValues.parse(File(dir, CONFIGSET).readText()).child("controller_config")?.child(appId.toString())
when {
@@ -264,9 +221,7 @@ object SteamTouchConfig {
private const val CONFIGSET = "configset_controller_mobile_touch.vdf"
// ---- What a config binds ----
/** Per preset, the controls its active sources bind - what Steam Link shows (UpdateElementAvailability). */
private fun availability(mappings: KeyValues.Node): Map<Int, Set<Int>> {
val groups = mappings.children("group").associateBy({ it.string("id") ?: "" }) { group ->
group.child("inputs")?.entries?.filter { (_, v) -> (v as? KeyValues.Node)?.let(::hasBinding) == true }
@@ -312,11 +267,7 @@ object SteamTouchConfig {
(activator as? KeyValues.Node)?.child("bindings")?.entries?.any { (k, v) -> k == "binding" && (v as? String)?.isNotBlank() == true } == true
} == true
// ---- Steam Link's defaults ----
/** Where Steam Link puts a control with no layout (CVirtualController::BInitializeDefaultElement,
* on a 1280x720 screen), and the same scheme for the controls its table leaves out, made room
* for when a config binds sticks. */
fun defaultElement(type: Int, available: Set<Int>): Element? {
val leftStick = JOYSTICK_LEFT in available
val rightStick = JOYSTICK_RIGHT in available
@@ -352,8 +303,6 @@ object SteamTouchConfig {
return Element(type, true, p.first, p.second)
}
/** The controls to draw: the layout's own where it has one, Steam Link's defaults otherwise,
* only those the config binds. */
fun elementsFor(config: Config, actionSet: Int, layers: List<Int>): List<Element> {
val available = config.availableFor(actionSet, layers)
val layout = config.layouts?.forActionSet(layoutIdOf(actionSet))
@@ -371,14 +320,7 @@ object SteamTouchConfig {
fun layoutColor(config: Config, actionSet: Int): FloatArray? = config.layouts?.forActionSet(layoutIdOf(actionSet))?.color
// ---- Saving ----
/**
* Saves [elements] as the layout of [actionSet] in app [appId]'s touch config: into the app's
* autosave config (`<appid>/controller_mobile_touch.vdf`, made from the config in use when the
* app has none) and selected for the app in the configset, as the client saves a layout Steam
* Link sends it. Returns the file written, or null.
*/
fun saveLayout(
context: Context,
appId: Int,
@@ -389,10 +331,6 @@ object SteamTouchConfig {
bindings: Map<SteamTouchBindings.Ref, (SteamTouchBindings.Binding) -> SteamTouchBindings.Binding> = emptyMap(),
): File? = saveLayouts(context, appId, config, mapOf(layoutIdOf(actionSet) to elements), color?.let { c -> setOf(layoutIdOf(actionSet)).associateWith { c } } ?: emptyMap(), bindings)
/**
* Saves the layouts of several action sets (by layout id) at once, with their colours, any
* binding edits and the per-game [options], into the game's autosave touch config.
*/
fun saveLayouts(
context: Context,
appId: Int,
@@ -403,8 +341,6 @@ object SteamTouchConfig {
options: Options? = null,
): File? {
val dir = configDir(context) ?: return null
// Icons, labels and colours live in the binding strings (SteamTouchBindings), as the
// configurator writes them.
val source = bindings.entries.fold(config.text ?: return null) { text, (ref, change) ->
SteamTouchBindings.rewrite(text, ref, change) ?: text
}
@@ -414,7 +350,7 @@ object SteamTouchConfig {
val written = sets.map { (id, elements) ->
Layout(id, elements, colors[id] ?: old?.forActionSet(id)?.color ?: floatArrayOf(1f, 1f, 1f, 0.4f), old?.forActionSet(id)?.version)
}
val rest = old?.rest ?: byteArrayOf(0x10, 0x02) // input_mode = controller
val rest = old?.rest ?: byteArrayOf(0x10, 0x02)
val layouts = Layouts((keep + written).sortedBy { it.actionSet }, options?.encodeInto(rest) ?: rest)
val hex = bytesToHex(encodeLayouts(layouts))
val line = "\t\"touch_layout\"\t\t\"$hex\""
@@ -431,7 +367,6 @@ object SteamTouchConfig {
return target
}
/** Points the app's configset entry at its autosave config. */
private fun selectAutosave(dir: File, appId: Int) {
val file = File(dir, CONFIGSET)
val text = if (file.isFile) file.readText() else "\"controller_config\"\n{\n}\n"
@@ -442,7 +377,6 @@ object SteamTouchConfig {
File(file.path + ".tmp").apply { writeText(next) }.renameTo(file)
}
// ---- touch_layout: CVirtualControllerLayouts ----
fun decodeLayouts(bytes: ByteArray): Layouts {
val layouts = mutableListOf<Layout>()
@@ -591,7 +525,6 @@ object SteamTouchConfig {
fun bytesToHex(b: ByteArray) = b.joinToString("") { "%02x".format(it.toInt() and 0xff) }
}
/** Valve's KeyValues text format, as far as controller configs use it. */
class KeyValues private constructor() {
class Node(val entries: MutableList<Pair<String, Any>> = mutableListOf()) {
fun child(key: String): Node? = entries.firstOrNull { it.first.equals(key, true) && it.second is Node }?.second as Node?
@@ -22,18 +22,6 @@ import kotlin.math.hypot
import kotlin.math.max
import kotlin.math.min
/**
* Steam's touch controls, drawn by the app.
*
* The layout is Steam's: the game's touch config for the action set the client says is active
* (SteamTouchDevice.State, SteamTouchConfig), placed where the config's layout puts each control or
* where Steam Link would by default, and only the controls the config binds. Touches become the
* touch controller's input report; the client does the rest - bindings, action sets, the virtual
* pad the game reads. Each control shows its binding's icon, label and colours, as Steam keeps them
* (SteamTouchBindings). [startEditing] moves, resizes and hides controls, picks their icons and the
* layout's colour, and saves all of it into the game's touch config, as Steam Link and Steam's
* configurator do.
*/
@SuppressLint("ViewConstructor")
class SteamTouchControls(
context: Context,
@@ -42,19 +30,14 @@ class SteamTouchControls(
private val onKeyboard: () -> Unit,
) : View(context) {
/** The game's input and mouse modes changed (from its config or the menu): the session routes
* touches outside the controls by them. */
var onOptions: (SteamTouchConfig.Options) -> Unit = {}
/** The Paste control: types the clipboard into the session. */
var onPaste: () -> Unit = {}
// Steam Link's own settings, for every game (CVirtualControllerGlobalConfig).
private val prefs = context.getSharedPreferences("steam_touch", Context.MODE_PRIVATE)
private var feedback = prefs.getBoolean("feedback", false)
private var autoFade = prefs.getBoolean("autoFade", true)
private var gyroOn = prefs.getBoolean("gyro", true).also { device.motionEnabled = it }
// Shake the device to hide the controls and again to bring them back (Steam Link's shake_fade).
private var shakeToHide = prefs.getBoolean("shake", false)
private var shakenAway = false
private val sensors by lazy { context.getSystemService(Context.SENSOR_SERVICE) as android.hardware.SensorManager }
@@ -69,7 +52,6 @@ class SteamTouchControls(
val now = android.os.SystemClock.uptimeMillis()
jolts = if (now - lastJolt < 400) jolts + 1 else 1
lastJolt = now
// Three jolts in quick succession, at most once a second.
if (jolts >= 3 && now - lastShake > 1000) {
lastShake = now
jolts = 0
@@ -113,15 +95,12 @@ class SteamTouchControls(
private var tint = Color.WHITE
private var alphaScale = 0.45f
// What each control is bound to (its icon, label, colours), per element type; the D-pad has four.
private class Visual(val ref: SteamTouchBindings.Ref?, val binding: SteamTouchBindings.Binding?)
private var visuals: Map<Int, List<Visual>> = emptyMap()
// Touch state.
private class Finger(val element: Element?, var x: Float, var y: Float, val toolbar: Int = -1)
private val fingers = HashMap<Int, Finger>()
// Editing.
private var editing = false
private var editElements: MutableList<Element> = mutableListOf()
private var hidden: MutableList<Element> = mutableListOf()
@@ -130,7 +109,6 @@ class SteamTouchControls(
private var pinchStart = 0f
private var pinchScale = 1f
private var saving = false
// Icon and colour edits not saved yet.
private val pendingBindings = HashMap<SteamTouchBindings.Ref, SteamTouchBindings.Binding>()
private var pendingColor: FloatArray? = null
private var selectedArm = 0
@@ -162,12 +140,9 @@ class SteamTouchControls(
super.onDetachedFromWindow()
}
/** Follows what the client tells the device: a new app loads its config, a new action set or
* layer redraws. */
private fun refreshState() {
val state = device.state()
val app = if (state.appId == 0) BIG_PICTURE else state.appId
// The client reads the config afresh when the controller (re)connects: so do we.
val reconnected = state.opened > 0 && opened == 0
opened = state.opened
if (app != configApp || reconnected) {
@@ -195,7 +170,6 @@ class SteamTouchControls(
}
}
/** Re-reads the config for the current app (after a save). */
fun reloadConfig() {
configApp = -1
refreshState()
@@ -216,12 +190,9 @@ class SteamTouchControls(
private fun applyColor(color: FloatArray?) {
tint = if (color != null) Color.rgb((color[0] * 255).toInt(), (color[1] * 255).toInt(), (color[2] * 255).toInt()) else Color.WHITE
// Steam Link's opacity: its default layout colour (alpha about 0.4) draws solid white
// outlines; lower values fade them.
alphaScale = ((color?.get(3) ?: 0.45f) * 2.2f).coerceIn(0.15f, 1f)
}
/** Each control's bindings for the action set and layers in use, with edits not saved yet. */
private fun rebuildVisuals() {
val mappings = config.mappings
val preset = SteamTouchConfig.layoutIdOf(actionSet) - 1
@@ -240,7 +211,6 @@ class SteamTouchControls(
}
}
// ---- Geometry ----
private fun unit() = min(width / 1280f, height / 720f)
@@ -248,7 +218,6 @@ class SteamTouchControls(
private fun radiusY(e: Element): Float = baseRadius(e.type) * e.yScale * unit()
private fun baseRadius(type: Int) = when (type) {
// Steam Link's sizes on its 1280x720 reference.
SteamTouchConfig.DPAD -> 112f
SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> 90f
SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> 100f
@@ -263,17 +232,14 @@ class SteamTouchControls(
private fun cx(e: Element) = e.x * width
private fun cy(e: Element) = e.y * height
/** How far (x, y) is from [e]'s centre, in its own radii (it may be an oval). */
private fun reach(e: Element, x: Float, y: Float) = hypot((x - cx(e)) / radius(e), (y - cy(e)) / radiusY(e))
private fun hit(list: List<Element>, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
/** What is drawn and touchable: in mouse mode only the menu button, as on Steam Link. */
private fun live(): List<Element> =
if (shakenAway) emptyList() else if (options.inputMode == SteamTouchConfig.INPUT_MOUSE) elements.filter { it.type == SteamTouchConfig.THUMB } else elements
// ---- Drawing ----
override fun onDraw(canvas: Canvas) {
val shown = if (editing) editElements else live()
@@ -281,7 +247,6 @@ class SteamTouchControls(
val x = cx(e)
val y = cy(e)
canvas.save()
// An oval control: drawn as its circle, stretched to its height.
if (e.yScale != e.xScale && e.xScale > 0f) canvas.scale(1f, e.yScale / e.xScale, x, y)
draw(canvas, e, editing && editElements.indexOf(e) == selected)
canvas.restore()
@@ -297,10 +262,6 @@ class SteamTouchControls(
private fun pressedTypes(): Set<Int> = fingers.values.mapNotNull { it.element?.type }.toSet()
// ---- Steam Link's look (measured from Steam Link 1.3 on the Thor) ----
// Outlines only: 3 px white strokes on a 1280x720 reference, no fill; a pressed control fills
// white with its content dark. Face letters in Steam's colours; Select and Start are ◀ ▶ pills
// beside a solid white Steam disc; bumpers, triggers, the menu and keyboard are rounded squares.
private fun lineWidth() = 3f * unit()
@@ -340,7 +301,6 @@ class SteamTouchControls(
}
}
SteamTouchConfig.STEAM -> {
// The guide button: DroidDeck's split D and orb, in a ring.
if (pressed) canvas.drawCircle(x, y, r, fill)
canvas.drawCircle(x, y, r, stroke)
drawMark(canvas, x, y, r * 0.5f, if (pressed) Color.argb(alpha, 23, 26, 33) else ink, alpha)
@@ -364,7 +324,6 @@ class SteamTouchControls(
}
}
/** Controls drawn as rounded squares on Steam Link; the face buttons and the rest are rings. */
private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT,
SteamTouchConfig.TRIGGER_LEFT, SteamTouchConfig.TRIGGER_RIGHT, SteamTouchConfig.THUMB, SteamTouchConfig.KEYBOARD,
SteamTouchConfig.PASTE, SteamTouchConfig.MACRO_1_FINGER, SteamTouchConfig.MACRO_2_FINGER) ||
@@ -372,8 +331,6 @@ class SteamTouchControls(
private val markD by lazy { androidx.core.graphics.PathParser.createPathFromPathData(MARK_D) }
/** DroidDeck's mark (artwork/droiddeck-mark.svg): the split D in [ink] around the blue orb,
* centred at (x, y), [r] its half height. */
private fun drawMark(canvas: Canvas, x: Float, y: Float, r: Float, ink: Int = onSurface, alpha: Int = 255) {
val k = r / 111.86f
canvas.save()
@@ -384,7 +341,6 @@ class SteamTouchControls(
canvas.restore()
}
/** The Steam logo's mark, drawn: a wheel and a piston rod. */
private fun drawSteamMark(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND }
p.strokeWidth = r * 0.16f
@@ -396,11 +352,6 @@ class SteamTouchControls(
canvas.drawLine(x - r * 0.45f, y + r * 0.28f, x - r * 0.95f, y + r * 0.1f, p)
}
/**
* A button as Steam Link draws it: a ring (or rounded square) outline with its name - face
* letters in Steam's colours. With a binding icon, the icon on a disc of its background colour,
* as Steam draws binding icons; with a binding label, the label.
*/
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
alpha: Int, pressed: Boolean) {
val square = isSquare(type)
@@ -412,7 +363,6 @@ class SteamTouchControls(
val s = r * 0.62f
val custom = binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
if (custom) {
// Colours chosen for this icon: drawn as Steam draws binding icons.
shape(Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = parseColor(binding.background, SteamTouchBindings.DEFAULT_BACKGROUND)
this.alpha = if (pressed) alpha else (alpha * 0.85f).toInt()
@@ -420,7 +370,6 @@ class SteamTouchControls(
canvas.drawBitmap(tinted(binding.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { this.alpha = alpha })
} else {
// Steam's default colours: Steam Link's own look, the icon in the outline's ink.
if (pressed) shape(fill)
val ink = if (pressed) Color.argb(alpha, 23, 26, 33) else stroke.color
canvas.drawBitmap(inked(binding.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
@@ -435,7 +384,6 @@ class SteamTouchControls(
shape(stroke)
if (type == SteamTouchConfig.THUMB) { drawDots(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
if (type == SteamTouchConfig.KEYBOARD) { drawKeyboardGlyph(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
// Steam Link names a control by itself, whatever its binding is labelled ("B", not "Back").
val own = label(type)
val shown = own
text.textSize = when {
@@ -469,14 +417,11 @@ class SteamTouchControls(
private val iconsLoading = HashSet<String>()
// Icons as a mask (their alpha), tinted when drawn.
private val inkedIcons = android.util.LruCache<String, android.graphics.Bitmap>(48)
private fun inked(name: String, icon: android.graphics.Bitmap): android.graphics.Bitmap {
val key = "$name|${icon.width}"
inkedIcons.get(key)?.let { return it }
// Steam's icons are drawn in greys on clear; their dark parts are the glyph's detail, so the
// mask keeps what is opaque and not near white.
val out = icon.copy(android.graphics.Bitmap.Config.ARGB_8888, true)
val px = IntArray(out.width * out.height)
out.getPixels(px, 0, out.width, 0, 0, out.width, out.height)
@@ -491,8 +436,6 @@ class SteamTouchControls(
return out
}
// Icons already in their foreground colour. Drawn plain: a colour filter on the icon bitmap
// itself stopped drawing on the hardware canvas once a dialog had been over the view.
private val tintedIcons = android.util.LruCache<String, android.graphics.Bitmap>(48)
private fun tinted(name: String, icon: android.graphics.Bitmap, foreground: String): android.graphics.Bitmap {
@@ -505,7 +448,6 @@ class SteamTouchControls(
return out
}
/** An icon from the cache, or null while it is (re)loaded; the view redraws when it comes in. */
private fun iconOrLoad(name: String): android.graphics.Bitmap? {
SteamTouchBindings.cachedIcon(appId, name, ICON_PX)?.let { return it }
if (iconsLoading.add(name)) {
@@ -521,17 +463,15 @@ class SteamTouchControls(
private fun parseColor(hex: String, fallback: String) =
try { Color.parseColor(hex.ifEmpty { fallback }) } catch (_: IllegalArgumentException) { Color.parseColor(fallback) }
/** Steam Link's d-pad: four shield-shaped arms pointing at the centre, outlined. */
private fun drawDpad(canvas: Canvas, e: Element, x: Float, y: Float, r: Float) {
val dirs = if (editing) 0 else dpadBits(e)
val armVisuals = visuals[SteamTouchConfig.DPAD].orEmpty()
val isSelected = editing && selected >= 0 && editElements.indexOf(e) == selected
val half = r * 0.36f // half the arm's width
val outer = r // the arm's far end
val inner = r * 0.1f // the point, near the centre
val shoulder = r * 0.42f // where the sides turn into the point
val half = r * 0.36f
val outer = r
val inner = r * 0.1f
val shoulder = r * 0.42f
val corner = r * 0.12f
// Arms in report order: up, down, left, right, as (bit, rotation).
val arms = listOf(DPAD_UP to 0f, DPAD_DOWN to 180f, DPAD_LEFT to 270f, DPAD_RIGHT to 90f)
val oldStroke = stroke.color
for ((armIndex, armEntry) in arms.withIndex()) {
@@ -561,7 +501,6 @@ class SteamTouchControls(
canvas.drawPath(path, stroke)
canvas.restore()
if (icon != null) {
// Upright, in the middle of the arm.
val c = (outer + shoulder) / 2f
val (ax, ay) = when (armIndex) { 0 -> x to y - c; 1 -> x to y + c; 2 -> x - c to y; else -> x + c to y }
val s = half * 0.8f
@@ -595,7 +534,6 @@ class SteamTouchControls(
else -> "?"
}
// ---- The report ----
private fun dpadBits(e: Element): Long {
var bits = 0L
@@ -604,7 +542,6 @@ class SteamTouchControls(
val dy = f.y - cy(e)
if (hypot(dx, dy) < radius(e) * 0.22f) return@forEach
val angle = Math.toDegrees(atan2(-dy, dx).toDouble()).let { if (it < 0) it + 360 else it }
// Eight sectors: each direction covers 67.5°, diagonals press two.
if (angle < 67.5 || angle > 292.5) bits = bits or DPAD_RIGHT
if (angle in 22.5..157.5) bits = bits or DPAD_UP
if (angle in 112.5..247.5) bits = bits or DPAD_LEFT
@@ -633,7 +570,7 @@ class SteamTouchControls(
buttons = buttons or if (right) STICK_RIGHT_TOUCHED else STICK_LEFT_TOUCHED
}
SteamTouchConfig.TRACKPAD_CENTER, SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT -> {
val index = e.type - SteamTouchConfig.TRACKPAD_CENTER // centre, left, right
val index = e.type - SteamTouchConfig.TRACKPAD_CENTER
val nx = ((f.x - (cx(e) - r)) / (2 * r)).coerceIn(0f, 1f)
val ny = ((f.y - (cy(e) - radiusY(e))) / (2 * radiusY(e))).coerceIn(0f, 1f)
pads[2 * index] = (((nx * 65535).toInt().coerceIn(0, 65535)) xor 0x8000).toShort()
@@ -653,7 +590,6 @@ class SteamTouchControls(
invalidate()
}
// ---- Touch ----
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
@@ -694,7 +630,6 @@ class SteamTouchControls(
val f = fingers[event.getPointerId(i)] ?: continue
f.x = event.getX(i)
f.y = event.getY(i)
// A finger on a button can slide onto another, as on Steam Link.
val e = f.element ?: continue
if (BUTTON_BITS.containsKey(e.type)) {
val over = hit(live(), f.x, f.y)
@@ -726,12 +661,9 @@ class SteamTouchControls(
return true
}
// ---- Editing ----
val isEditing get() = editing
/** Moves, resizes and hides controls, action set by action set; Save writes them to the
* game's touch config. */
fun startEditing() {
releaseAll()
editing = true
@@ -744,7 +676,6 @@ class SteamTouchControls(
invalidate()
}
// The action set being edited (its layout id), and the edits of every set visited.
private var editSet = 1
private class EditState(val elements: MutableList<Element>, val hidden: MutableList<Element>)
private val editSets = HashMap<Int, EditState>()
@@ -752,7 +683,6 @@ class SteamTouchControls(
private fun loadEditSet(id: Int) {
editSet = id
val state = editSets.getOrPut(id) {
// The device's action set numbering is the layout id.
val available = config.availableFor(id, emptyList())
val shown = SteamTouchConfig.elementsFor(config, id, emptyList())
val els = available.mapNotNull { type ->
@@ -816,7 +746,6 @@ class SteamTouchControls(
val e = hit(editElements, x, y)
selected = if (e != null) editElements.indexOf(e) else -1
if (e != null) dragOffset = (x - cx(e)) to (y - cy(e))
// The D-pad's icons are per direction: a tap picks the one under the finger.
if (e?.type == SteamTouchConfig.DPAD) {
val dx = x - cx(e)
val dy = y - cy(e)
@@ -832,7 +761,6 @@ class SteamTouchControls(
MotionEvent.ACTION_MOVE -> if (selected >= 0 && !trayOpen) {
val e = editElements[selected]
if (event.pointerCount >= 2 && pinchStart > 0f) {
// A pinch along one axis stretches that axis; a diagonal one scales both.
val sx = abs(event.getX(0) - event.getX(1))
val sy = abs(event.getY(0) - event.getY(1))
val min = 40f * unit()
@@ -850,7 +778,6 @@ class SteamTouchControls(
MotionEvent.ACTION_POINTER_UP -> pinchStart = 0f
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
pinchStart = 0f
// Dropped back on the menu button: back into the tray, as on Steam Link.
val e = editElements.getOrNull(selected)
if (e != null && editMenuButton().contains(cx(e), cy(e)) && e.type != SteamTouchConfig.THUMB) {
hidden += editElements.removeAt(selected).copy(visible = false)
@@ -893,7 +820,6 @@ class SteamTouchControls(
else -> label(type)
}
/** Reset, copy and paste a layout, the layout's colour. */
private fun moreMenu() {
val host = parent as? android.view.ViewGroup ?: return
val density = resources.displayMetrics.density
@@ -918,7 +844,6 @@ class SteamTouchControls(
close = SteamTouchIconPicker.showPanel(host, context.getString(R.string.ctrl_layout), list, listOf(context.getString(R.string.common_close) to {}))
}
/** A copied layout onto this action set: each control the set has takes the copied place. */
private fun pasteLayout(copied: String) {
val placed = copied.split(';').mapNotNull { row ->
val f = row.split(',')
@@ -932,30 +857,21 @@ class SteamTouchControls(
selected = -1
}
// ---- Steam Link's menu ----
/** The menu button: Steam Link's touch menu. */
private fun openMenu() {
releaseAll()
menuOpen = true
invalidate()
}
// ---- Steam Link's panels: the touch menu and the layout tray ----
//
// Drawn here, on this view, to Steam Link's measurements (a 624x400 panel in its reference
// pixels, navy with a blue top rule, blue tiles), so that controls can be dragged out of the tray
// onto the screen as on Steam Link.
private var menuOpen = false
private var trayOpen = false
/** A hit area on a panel and what it does. */
private class Hot(val rect: RectF, val onTap: () -> Unit, val onDown: ((Float, Float) -> Unit)? = null)
private val hots = mutableListOf<Hot>()
private var trayDrag: Element? = null
// DroidDeck's own palette (ui/Theme.kt, the default theme).
private val surface = Color.rgb(18, 20, 23)
private val surfaceVariant = Color.rgb(26, 29, 34)
private val line = Color.rgb(38, 42, 49)
@@ -965,7 +881,6 @@ class SteamTouchControls(
private val accent = Color.rgb(26, 159, 255)
private val onAccent = Color.rgb(3, 17, 31)
/** The panel's rectangle and its scale (screen pixels per reference pixel). */
private fun panelFrame(): Pair<RectF, Float> {
val s = min(width * 0.8f / 624f, height * 0.78f / 400f)
val w = 624f * s
@@ -995,8 +910,6 @@ class SteamTouchControls(
canvas.drawText(str, x, y - (p.descent() + p.ascent()) / 2, p)
}
/** A button in DroidDeck's style: the accent filled for the main action, a quiet outlined
* surface otherwise. */
private fun blueButton(canvas: Canvas, r: RectF, text: String, s: Float, enabled: Boolean = true, primary: Boolean = false, onTap: () -> Unit) {
val radius = 12f * s
if (primary && enabled) {
@@ -1010,7 +923,6 @@ class SteamTouchControls(
if (enabled) hots += Hot(r, onTap)
}
/** A toggle: quiet when off, accent-tinted with an accent glyph when on. */
private fun iconButton(canvas: Canvas, r: RectF, active: Boolean, onTap: () -> Unit, glyph: (Canvas, RectF, Int) -> Unit) {
val radius = 10f * (r.height() / 40f)
canvas.drawRoundRect(r, radius, radius, Paint(Paint.ANTI_ALIAS_FLAG).apply {
@@ -1055,12 +967,10 @@ class SteamTouchControls(
}
}
// -- The touch menu (Steam Link: CVirtualController's choose-mode screen) --
private fun drawMenu(canvas: Canvas) {
val (f, s) = panelFrame()
canvas.panel(f, s)
// Header: power (DroidDeck's own menu: stop, settings), the Steam mark, what is running, close.
iconButton(canvas, ref(f, s, 494f, 18f, 531f, 55f), false, { menuOpen = false; onMenu() }) { c, r, col -> drawPower(c, r, col) }
drawMark(canvas, f.left + 104f * s, f.top + 37f * s, 13f * s)
text(canvas, context.getString(R.string.touch_title), f.left + 124f * s, f.top + 30f * s, 14f * s, onSurface, align = Paint.Align.LEFT)
@@ -1079,7 +989,6 @@ class SteamTouchControls(
tile(canvas, ref(f, s, 271f, 81f, 475f, 271f), s, context.getString(R.string.touch_mouse), mouse, { setModes(controller || mouse, !mouse) }) { c, r, col ->
drawMouse(c, r, col, crossed = false)
}
// Under the controller: gyroscope, fade, vibrate on touch.
iconButton(canvas, ref(f, s, 45f, 278f, 91f, 318f), gyroOn, {
gyroOn = !gyroOn; device.motionEnabled = gyroOn; prefs.edit().putBoolean("gyro", gyroOn).apply()
}) { c, r, col -> drawGyro(c, r, col) }
@@ -1092,7 +1001,6 @@ class SteamTouchControls(
iconButton(canvas, ref(f, s, 204f, 278f, 249f, 318f), feedback, {
feedback = !feedback; prefs.edit().putBoolean("feedback", feedback).apply()
}) { c, r, col -> drawHaptic(c, r, col) }
// Under the mouse: direct touch, trackpad, trackpad speed.
val relative = options.mouseMode == SteamTouchConfig.MOUSE_RELATIVE
iconButton(canvas, ref(f, s, 271f, 278f, 333f, 318f), mouse && !relative, {
setOptions(options.copy(mouseMode = SteamTouchConfig.MOUSE_ABSOLUTE))
@@ -1116,8 +1024,6 @@ class SteamTouchControls(
private val audio by lazy { context.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager }
private var volumeSlider = RectF()
/** Steam Link's audio column: the speaker (mute), its volume slider - the device's media
* volume here - and the microphone, which DroidDeck does not stream, shown off. */
private fun drawVolume(canvas: Canvas, f: RectF, s: Float) {
val stream = android.media.AudioManager.STREAM_MUSIC
val maxVol = audio.getStreamMaxVolume(stream).coerceAtLeast(1)
@@ -1136,7 +1042,6 @@ class SteamTouchControls(
canvas.drawRoundRect(RectF(inner.left, knobY, inner.right, inner.bottom), inner.width() / 2, inner.width() / 2,
Paint(Paint.ANTI_ALIAS_FLAG).apply { color = accent })
canvas.drawCircle(inner.centerX(), knobY, inner.width() / 2 * 1.05f, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = onSurface })
// The mic's slider, dimmed.
val micTrack = ref(f, s, 539f, 133f, 577f, 372f)
canvas.drawRoundRect(micTrack, micTrack.width() / 2, micTrack.width() / 2, Paint(stroke).apply { color = Color.argb(60, 255, 255, 255) })
hots += Hot(track, {}) { _, y -> setVolumeAt(y) }
@@ -1171,7 +1076,6 @@ class SteamTouchControls(
c.drawLine(x - u * 2.4f, y - u * 2.4f, x + u * 2.4f, y + u * 2.4f, glyphPaint(Color.rgb(200, 40, 40), r.height() * 0.07f))
}
/** A mode card: tap to turn it on or off; the accent marks it on. */
private fun tile(canvas: Canvas, r: RectF, s: Float, title: String, on: Boolean, toggle: () -> Unit, art: (Canvas, RectF, Int) -> Unit) {
val radius = 14f * s
canvas.drawRoundRect(r, radius, radius, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = surfaceVariant })
@@ -1179,7 +1083,6 @@ class SteamTouchControls(
color = if (on) accent else line; style = Paint.Style.STROKE; strokeWidth = (if (on) 2f else 1.2f) * s
})
text(canvas, title, r.left + 16f * s, r.top + 22f * s, 14f * s, onSurface, align = Paint.Align.LEFT, maxWidth = r.width() - 72f * s)
// A switch, top right.
val sw = RectF(r.right - 50f * s, r.top + 12f * s, r.right - 14f * s, r.top + 32f * s)
canvas.drawRoundRect(sw, sw.height() / 2, sw.height() / 2, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (on) accent else line2 })
canvas.drawCircle(if (on) sw.right - sw.height() / 2 else sw.left + sw.height() / 2, sw.centerY(), sw.height() * 0.38f,
@@ -1190,7 +1093,6 @@ class SteamTouchControls(
hots += Hot(r, toggle)
}
// -- The layout tray (Steam Link: CVirtualController's tray) --
private fun drawTray(canvas: Canvas) {
val (f, s) = panelFrame()
@@ -1246,7 +1148,6 @@ class SteamTouchControls(
item(SteamTouchConfig.MACRO_0 + i, 519f, 228f + 43f * i, 14f)
item(SteamTouchConfig.MACRO_0 + 4 + i, 562f, 228f + 43f * i, 14f)
}
// The colour wheel: the layout's colour and opacity.
val wheel = ref(f, s, 511f, 91f, 573f, 153f)
canvas.drawCircle(wheel.centerX(), wheel.centerY(), wheel.width() / 2f, Paint(Paint.ANTI_ALIAS_FLAG).apply {
shader = android.graphics.SweepGradient(wheel.centerX(), wheel.centerY(),
@@ -1270,7 +1171,6 @@ class SteamTouchControls(
hots += Hot(RectF(r.left - r.height() * 0.4f, r.top - r.height() * 0.6f, r.right + r.height() * 0.4f, r.bottom + r.height() * 0.6f), onTap)
}
/** A control taken out of the tray: on screen under the finger, following it until it lifts. */
private fun beginTrayDrag(type: Int, x: Float, y: Float) {
val available = config.availableFor(editSet, emptyList())
val existing = editElements.indexOfFirst { it.type == type }
@@ -1286,7 +1186,6 @@ class SteamTouchControls(
invalidate()
}
// -- While editing: Steam Link's menu button, and a small bar for the selected control --
private fun editMenuButton(): RectF {
val r = 37f * unit()
@@ -1340,7 +1239,6 @@ class SteamTouchControls(
invalidate()
}
// -- Glyphs for the menu's buttons --
private fun glyphPaint(col: Int, w: Float) = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = col; style = Paint.Style.STROKE; strokeWidth = w; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND
@@ -1430,8 +1328,6 @@ class SteamTouchControls(
Paint(Paint.ANTI_ALIAS_FLAG).apply { color = col })
}
/** New per-game input options: applied now, and saved into the game's touch layout as Steam
* Link saves them, so they follow the game and the account. */
private fun setOptions(next: SteamTouchConfig.Options) {
pendingOptions = next
options = next
@@ -1449,7 +1345,6 @@ class SteamTouchControls(
}
}
/** The selected control's icon, label and colours (a D-pad direction: the one tapped). */
private fun pickIcon(e: Element) {
val list = visuals[e.type].orEmpty()
val visual = list.getOrNull(if (e.type == SteamTouchConfig.DPAD) selectedArm else 0)
@@ -1470,7 +1365,6 @@ class SteamTouchControls(
}.show()
}
/** The layout's colour and opacity, as Steam Link's colour picker sets them. */
private fun pickColor() {
val current = pendingColor ?: SteamTouchConfig.layoutColor(config, actionSet) ?: floatArrayOf(1f, 1f, 1f, 0.45f)
val density = resources.displayMetrics.density
@@ -1521,8 +1415,6 @@ class SteamTouchControls(
}
val color = pendingColor
val colors = if (color != null) sets.keys.associateWith { color } else emptyMap()
// A picked icon replaces the label, icon and colours of every binding of that input; what
// the binding does stays as it is.
val bindings = pendingBindings.mapValues { (_, picked) ->
{ old: SteamTouchBindings.Binding ->
old.copy(label = picked.label, icon = picked.icon, foreground = picked.foreground, background = picked.background)
@@ -1550,7 +1442,6 @@ class SteamTouchControls(
}
}
/** Called after a save: the client reads the config again when the controller reconnects. */
var onSaved: () -> Unit = {}
companion object {
@@ -1558,7 +1449,6 @@ class SteamTouchControls(
private const val POLL_MS = 150L
const val BIG_PICTURE = 769
private const val ICON_PX = 128
// artwork/droiddeck-mark.svg: the D's two halves, the orb's ring cut out (Wordmark.kt).
private const val MARK_D = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z" +
"M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"
private const val FADE_AFTER_MS = 5000L
@@ -1573,7 +1463,6 @@ class SteamTouchControls(
private const val STICK_RIGHT_TOUCHED = 1L shl 47
private val TRACKPAD_TOUCHED = longArrayOf(1L shl 27, 1L shl 19, 1L shl 20)
/** Steam Link's button bits (CVirtualController's table, by element type). */
private val BUTTON_BITS: Map<Int, Long> = buildMap {
put(SteamTouchConfig.STEAM, 1L shl 13)
put(SteamTouchConfig.JOYSTICK_LEFT_BUTTON, 1L shl 22)
@@ -1591,7 +1480,6 @@ class SteamTouchControls(
for (i in 0 until 8) put(SteamTouchConfig.MACRO_0 + i, 1L shl (32 + i))
put(SteamTouchConfig.MACRO_1_FINGER, 1L shl 48)
put(SteamTouchConfig.MACRO_2_FINGER, 1L shl 49)
// Not bits: the menu and the keyboard are the app's own.
put(SteamTouchConfig.THUMB, 0L)
put(SteamTouchConfig.KEYBOARD, 0L)
put(SteamTouchConfig.PASTE, 0L)
@@ -7,20 +7,8 @@ import java.nio.ByteOrder
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
/**
* Steam's touch controller, as the app's side of it.
*
* libfakeinput offers the Steam client a HID device with the ids of Steam Link's touch controls
* (0000:11fb), and the client builds its own touch controller for it: Steam Input's Mobile Touch
* type, with the game's touch config, action sets, community configs and cloud sync all Steam's
* (docs/development/steam-touch-controller.md). This class is the file the two share
* (fakeinput_steam.cpp: TouchRingFile): the app writes the device's 40-byte input report and
* whether it is plugged in; libfakeinput writes back what the client told the device - the app and
* action set it is on, its layers, rumble.
*/
class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
/** What the client last told the device. */
data class State(
val opened: Int,
val appId: Int,
@@ -29,13 +17,9 @@ class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
val actionSeq: Int,
)
// The input report (Steam Link's CVirtualController, docs/development/steam-touch-controller.md):
// bytes 0-7 buttons, 8-15 sticks, 16-27 trackpads, 28-33 accelerometer, 34-39 gyro.
private val report = ByteArray(REPORT_BYTES)
private var reportSeq = 0L
/** The controls part of the report: button bits, sticks (LX, LY, RX, RY, already in the report's
* units) and trackpads (centre, left, right: x, y each). */
@Synchronized
fun setControls(buttons: Long, sticks: ShortArray, pads: ShortArray) {
val next = report.copyOf()
@@ -45,27 +29,19 @@ class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
publish(next)
}
/** Motion in the Deck's axes and units (PadMotion), which the touch report shares. */
@Synchronized
fun setMotion(accel: ShortArray, gyro: ShortArray) {
// Sent only while the client asks for it (setting report 0x30, which Steam Link reads as
// "gyro on") and the player has not turned motion off - as Steam Link does.
if (!plugged || !gyroRequested || !motionEnabled) return
val next = report.copyOf()
for (i in 0 until 3) {
// Accelerometer: the Deck's 1 g = 16384 is the touch report's ±2 g = ±32767 already.
putShort(next, 28 + 2 * i, accel[i])
// Gyro: the Deck's 2000 °/s = 32768; the touch report's full scale is 1000 °/s
// (Steam Link: rad/s × 180/π / 1000 × 32767).
putShort(next, 34 + 2 * i, (gyro[i] * 2).coerceIn(-32767, 32767).toShort())
}
publish(next)
}
/** Whether the client has asked the device for motion (setting report 0x30 non-zero). */
val gyroRequested get() = buffer.getInt(OFF_SETTING30) != 0
/** The player's motion switch (Steam Link's gyroscope option). */
@Volatile var motionEnabled = true
set(value) {
field = value
@@ -81,7 +57,6 @@ class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
into[at + 1] = (value.toInt() shr 8).toByte()
}
/** Writes the report under the seqlock libfakeinput reads it with. */
private fun publish(next: ByteArray) {
if (next.contentEquals(report)) return
next.copyInto(report)
@@ -122,7 +97,7 @@ class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
private const val TAG = "SteamTouch"
const val REPORT_BYTES = 40
private const val SIZE = 256
private const val MAGIC = 0x31484354 // TCH1
private const val MAGIC = 0x31484354
private const val OFF_REPORT_SEQ = 8
private const val OFF_REPORT = 16
private const val OFF_PLUGGED = 56
@@ -140,10 +115,8 @@ class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
var current: SteamTouchDevice? = null
private set
/** The shared file in the session's pad directory, made fresh each session. */
fun ringFile(fakeInputDir: File) = File(fakeInputDir, "touchctl")
/** Creates the file for a new session (unplugged) and maps it. */
fun prepare(fakeInputDir: File): File? = try {
val file = ringFile(fakeInputDir)
file.delete()
@@ -24,11 +24,6 @@ import android.widget.TextView
import com.droiddeck.launcher.R
import java.util.concurrent.Executors
/**
* Picks a touch control's icon, label and colours the way Steam's configurator does: an icon from
* the game's own `TouchMenuIcons` and Steam's binding icon library, a foreground and a background
* from Steam's palette. [onPicked] gets the binding with the new fields (the action untouched).
*/
class SteamTouchIconPicker(
private val context: Context,
private val host: ViewGroup,
@@ -47,7 +42,6 @@ class SteamTouchIconPicker(
private fun dp(v: Int) = (v * density).toInt()
fun show() {
// Side by side, for a landscape screen: what is picked on the left, the icons on the right.
val root = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; setPadding(dp(16), dp(8), dp(16), 0) }
val left = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }
val label = EditText(context).apply {
@@ -132,8 +126,6 @@ class SteamTouchIconPicker(
}
}
/** The icon as Steam draws it: on a disc of the background colour, filled with the foreground
* through its own alpha. */
private fun render(icon: Bitmap, size: Int): Bitmap {
val out = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(out)
@@ -148,7 +140,6 @@ class SteamTouchIconPicker(
private val loading = HashSet<String>()
private var refreshQueued = false
/** Loads an icon in the background; the grid redraws from the cache once some have come in. */
private fun load(name: String) {
if (!loading.add(name)) return
loader.execute {
@@ -189,7 +180,6 @@ class SteamTouchIconPicker(
return view
}
// One thumbnail per icon and colour, reused when the grid rebinds.
private val thumbs = android.util.LruCache<String, Bitmap>(64)
private fun tinted(name: String, icon: Bitmap): Bitmap {
@@ -204,10 +194,6 @@ class SteamTouchIconPicker(
}
companion object {
/**
* A panel over the session, in the session's own window: a dialog's window of its own left
* new bitmaps and layers undrawn in the session window afterwards on the Thor.
*/
fun showPanel(host: ViewGroup, title: String, content: View, buttons: List<Pair<String, () -> Unit>>, onClose: () -> Unit = {}): () -> Unit {
val context = host.context
val density = context.resources.displayMetrics.density
@@ -217,7 +203,6 @@ class SteamTouchIconPicker(
isClickable = true
isFocusable = true
}
// DroidDeck's panel: dark surface, rounded, a hairline border.
val card = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
background = GradientDrawable().apply {
@@ -266,8 +251,6 @@ class SteamTouchIconPicker(
return { if (scrim.parent != null) close() }
}
/** Steam's binding icon look (steamui: the icon multiplied with its foreground colour,
* background-blend-mode: multiply, keeping the icon's own alpha). */
fun drawSteamIcon(canvas: Canvas, icon: Bitmap, into: android.graphics.RectF, foreground: Int, paint: Paint) {
val tint = Paint(paint).apply { colorFilter = PorterDuffColorFilter(foreground, PorterDuff.Mode.MULTIPLY) }
canvas.drawBitmap(icon, null, into, tint)
@@ -5,30 +5,10 @@ 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
* - one finger held, another slides .. left-button drag, as on a laptop's pad: the held finger is
* the button, the other moves the pointer (a window by its
* title bar or edge, a desktop icon). The sliding finger may
* lift and slide again; lifting the held one drops.
*
* 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
@@ -49,7 +29,6 @@ class TouchpadGestures(
private var twoFingers = false
private var scrollAnchorY = 0f
private var scrolled = false
// Hold-and-slide: the first finger stays as the button, the second moves the pointer.
private var anchorId = -1
private var anchorStartX = 0f
private var anchorStartY = 0f
@@ -106,7 +85,6 @@ class TouchpadGestures(
downAt = event.eventTime
travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false
anchorId = event.getPointerId(0); moverId = -1; holdDrag = 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)
@@ -127,7 +105,6 @@ class TouchpadGestures(
anchorStartX = event.getX(it); anchorStartY = event.getY(it)
}
}
// Mid-drag, a finger coming back only picks the sliding up again.
if (holdDrag) return true
twoFingers = true
secondDownAt = event.eventTime
@@ -140,8 +117,6 @@ class TouchpadGestures(
val mi = if (moverId == -1) -1 else event.findPointerIndex(moverId)
if (ai >= 0 && mi >= 0) {
val mx = event.getX(mi); val my = event.getY(mi)
// One finger still, the other on the move: that is a drag, not a scroll (which
// moves both). Decided once, before anything has scrolled.
if (!holdDrag && !scrolled) {
val anchorMoved = abs(event.getX(ai) - anchorStartX) + abs(event.getY(ai) - anchorStartY)
val moverMoved = abs(mx - moverStartX) + abs(my - moverStartY)
@@ -165,7 +140,6 @@ class TouchpadGestures(
return true
}
} else if (holdDrag) {
// Only the held finger is down: the drag waits for the next slide.
return true
}
if (twoFingers && event.pointerCount >= 2) {
@@ -186,7 +160,6 @@ class TouchpadGestures(
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)
@@ -198,7 +171,6 @@ class TouchpadGestures(
val gone = event.getPointerId(event.actionIndex)
if (holdDrag) {
if (gone == anchorId) {
// The held finger lifted: drop. The other finger carries on as the pointer.
listener.onButton(PointerGestures.BTN_LEFT, false, x, y)
dragging = false; holdDrag = false; twoFingers = false
anchorId = moverId; moverId = -1
@@ -213,13 +185,11 @@ class TouchpadGestures(
}
if (gone == moverId) moverId = -1
if (gone == anchorId) {
// The first finger left a two-finger gesture: the other one is the pointer now.
anchorId = event.getPointerId(if (event.actionIndex == 0) 1 else 0)
event.findPointerIndex(anchorId).takeIf { it >= 0 }?.let {
lastX = event.getX(it); lastY = event.getY(it)
}
}
// The second finger lifting quickly, with nothing scrolled: a right click.
if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TAP_MS && !scrolled) {
click(PointerGestures.BTN_RIGHT)
secondWasTap = false
@@ -232,7 +202,6 @@ class TouchpadGestures(
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) {
click(PointerGestures.BTN_RIGHT)
}