Steam's touch controller as on-screen controls (beta) (#431)

* feat: Steam's touch controller as on-screen controls (beta)

* fix: Steam touch controls appear once the session makes the device; tidier default layout

* fix: Steam touch layout decoding, saved layouts and new sessions

* docs: Steam's touch controls

* feat: Steam's touch icons, labels and colours on the touch controls; pick and save them like Steam

* feat: Steam touch icon picker as in-session panels; layout colour; docs

* Give each physical controller its own player slot

Every controller fed the one exported pad, so two pads played as one.
The first controller keeps slot 0 (the Deck in a Steam session); further
ones get slots 1-3 as separate Xbox 360 pads, created on first input and
removed on disconnect. In Deck mode only the Steam client sees those
pads and hands them to games through Steam Input. Rumble follows the
slot it names.

* feat: Steam Link's touch menu, per-game input modes, action set editing, add/copy/paste, oval controls, paste control

* feat: Steam touch controls drawn as Steam Link draws them; Steam Link's touch menu and layout tray

* feat: Steam touch controls in DroidDeck's style, D-mark guide button, shake to hide

* refactor: Steam touch controls become an On-screen controls choice instead of a second dropdown

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
This commit is contained in:
Kurt Himebauchandmaxjivi05 authored and GitHub committed 2026-10-09 21:12:46 -04:00
1 parent a6d15bcd0b
commit 0da45e53cb
23 files changed
+4160 -94

No files matched your search

@@ -10,6 +10,8 @@ import android.view.MotionEvent;
import com.droiddeck.launcher.session.SessionState;
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.
@@ -25,11 +27,14 @@ import java.io.File;
* 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";
/** Slot 0 is the one the session exports; extra slots would each show as another pad. */
private static final int SLOT = 0;
/** Player slots: the session prepares a ring for each (SessionService). */
public static final int SLOTS = 4;
private static final float DEAD_ZONE = 0.12f;
// 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
@@ -50,8 +55,13 @@ public final class PadBridge {
chordHandler = new Handler(thread.getLooper());
}
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];
private final PadState effectiveState = new PadState();
private final Handler mainHandler = new Handler(Looper.getMainLooper());
private boolean open;
@@ -79,29 +89,50 @@ public final class PadBridge {
/** 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 the pad, or
* {@link #NO_CONTROLLER}. Every pad feeds the one exported slot, so this is how a game's rumble
* on that slot finds the motors in the player's hands (RumbleComponent).
* 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);
}
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;
}
public PadBridge(File fakeInputDir) {
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), SLOT);
this.fakeInputDir = fakeInputDir;
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), 0);
Arrays.fill(owners, NO_CONTROLLER);
for (int slot = 1; slot < SLOTS; slot++) playerStates[slot] = new PadState();
}
/** Opens the ring; safe to call more than once. */
public synchronized boolean start() {
if (!open) {
open = writer.open();
Log.i(TAG, "ring slot " + SLOT + (open ? " open" : " NOT open"));
Log.i(TAG, "ring slot 0" + (open ? " open" : " NOT open"));
}
return open;
}
public synchronized void stop() {
activeControllerId = NO_CONTROLLER;
for (int slot = 0; slot < SLOTS; slot++) {
owners[slot] = NO_CONTROLLER;
slotControllers.set(slot, NO_CONTROLLER);
if (playerWriters[slot] != null) {
playerWriters[slot].destroy();
playerWriters[slot] = null;
}
if (playerStates[slot] != null) playerStates[slot].clear();
}
systemGuidePressed = false;
systemQamPressed = false;
qamChordActive = false;
@@ -179,37 +210,39 @@ public final class PadBridge {
/** @return true when the event was a pad button and has been consumed. */
public synchronized boolean onKeyEvent(KeyEvent event) {
if (!isControllerKey(event)) return false;
noteDevice(event.getDevice());
int slot = slotFor(event.getDevice());
PadState pad = stateFor(slot);
noteDevice(event.getDevice(), slot);
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BUTTON_A: state.press(0, pressed); break;
case KeyEvent.KEYCODE_BUTTON_B: state.press(1, pressed); break;
case KeyEvent.KEYCODE_BUTTON_X: state.press(2, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Y: state.press(3, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L1: state.press(4, pressed); break;
case KeyEvent.KEYCODE_BUTTON_R1: state.press(5, pressed); break;
case KeyEvent.KEYCODE_BUTTON_A: pad.press(0, pressed); break;
case KeyEvent.KEYCODE_BUTTON_B: pad.press(1, pressed); break;
case KeyEvent.KEYCODE_BUTTON_X: pad.press(2, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Y: pad.press(3, pressed); break;
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:
case KeyEvent.KEYCODE_BACK: state.press(6, pressed); break;
case KeyEvent.KEYCODE_BACK: pad.press(6, pressed); break;
case KeyEvent.KEYCODE_BUTTON_START:
case KeyEvent.KEYCODE_MENU: state.press(7, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: state.press(8, pressed); break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: state.press(9, pressed); break;
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: state.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L2: state.leftTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_BUTTON_R2: state.rightTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_DPAD_UP: state.up = pressed; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: state.right = pressed; break;
case KeyEvent.KEYCODE_DPAD_DOWN: state.down = pressed; break;
case KeyEvent.KEYCODE_DPAD_LEFT: state.left = pressed; break;
case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_BUTTON_R2: pad.rightTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_DPAD_UP: pad.up = pressed; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: pad.right = pressed; break;
case KeyEvent.KEYCODE_DPAD_DOWN: pad.down = pressed; break;
case KeyEvent.KEYCODE_DPAD_LEFT: pad.left = pressed; break;
default: return false;
}
if (pressed) notePlayerInput();
statButtons++;
scheduleStats();
publish();
publish(slot);
return true;
}
@@ -217,33 +250,35 @@ public final class PadBridge {
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isFromController(event.getDevice())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
noteDevice(event.getDevice());
int slot = slotFor(event.getDevice());
PadState pad = stateFor(slot);
noteDevice(event.getDevice(), slot);
statAxes++;
scheduleStats();
state.leftX = axis(event, MotionEvent.AXIS_X);
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.
state.leftY = axis(event, MotionEvent.AXIS_Y);
state.rightX = axis(event, MotionEvent.AXIS_Z);
state.rightY = axis(event, MotionEvent.AXIS_RZ);
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);
state.leftTrigger = lt;
state.rightTrigger = rt;
pad.leftTrigger = lt;
pad.rightTrigger = rt;
float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X);
float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y);
state.up = hatY < -0.5f;
state.right = hatX > 0.5f;
state.down = hatY > 0.5f;
state.left = hatX < -0.5f;
if (Math.max(Math.max(Math.abs(state.leftX), Math.abs(state.leftY)), Math.max(Math.abs(state.rightX), Math.abs(state.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || state.up || state.right || state.down || state.left) {
pad.up = hatY < -0.5f;
pad.right = hatX > 0.5f;
pad.down = hatY > 0.5f;
pad.left = hatX < -0.5f;
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
notePlayerInput();
}
publish();
publish(slot);
return true;
}
@@ -254,6 +289,7 @@ public final class PadBridge {
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
mutation.accept(state);
activeControllerId = NO_CONTROLLER;
slotControllers.set(0, NO_CONTROLLER);
notePlayerInput();
statOnScreen++;
scheduleStats();
@@ -278,6 +314,18 @@ public final class PadBridge {
public synchronized void releaseAll() {
state.clear();
publish();
for (int slot = 1; slot < SLOTS; slot++) {
if (playerWriters[slot] == null) continue;
playerStates[slot].clear();
publish(slot);
}
}
/** 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);
}
}
/** Opens the client's Quick Access menu: a tap of the Deck's button, or the Guide-then-A chord. */
@@ -333,16 +381,56 @@ 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;
for (int slot = 1; slot < SLOTS; slot++) {
if (owners[slot] == id) return slot;
}
for (int slot = 0; slot < SLOTS; slot++) {
if (owners[slot] != NO_CONTROLLER && InputDevice.getDevice(owners[slot]) == null) free(slot);
}
for (int slot = 0; slot < SLOTS; slot++) {
if (owners[slot] != NO_CONTROLLER) continue;
owners[slot] = id;
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") is player " + (slot + 1));
return slot;
}
return 0;
}
private PadState stateFor(int slot) {
return slot == 0 ? state : playerStates[slot];
}
private void free(int slot) {
Log.i(TAG, "player " + (slot + 1) + " (id " + owners[slot] + ") left");
owners[slot] = NO_CONTROLLER;
slotControllers.set(slot, NO_CONTROLLER);
if (slot == 0) {
state.clear();
publish();
return;
}
playerStates[slot].clear();
if (playerWriters[slot] != null) {
playerWriters[slot].destroy();
playerWriters[slot] = null;
}
}
/** Per event, so the common case - the same pad as last time - is a single compare. */
private void noteDevice(InputDevice device) {
private void noteDevice(InputDevice device, int slot) {
activeControllerId = device.getId();
slotControllers.set(slot, device.getId());
if (device.getId() == lastDeviceId) return;
lastDeviceId = device.getId();
statDevice = device.getName();
if (seenDevices.add(device.getId())) {
Log.i(TAG, String.format(java.util.Locale.ROOT, "first input from \"%s\" (%04x:%04x, id %d, sources 0x%x); ring %s, deck pad %b",
Log.i(TAG, String.format(java.util.Locale.ROOT, "first input from \"%s\" (%04x:%04x, id %d, sources 0x%x); slot %d, ring %s, deck pad %b",
device.getName(), device.getVendorId(), device.getProductId(), device.getId(), device.getSources(),
open ? "open" : "not open yet", SessionState.getDeckPad()));
slot, open ? "open" : "not open yet", SessionState.getDeckPad()));
}
}
@@ -362,6 +450,23 @@ public final class PadBridge {
statButtons = statAxes = statOnScreen = statDropped = 0;
}
private void publish(int slot) {
if (slot == 0) {
publish();
return;
}
FakeInputWriter player = playerWriters[slot];
if (player == null) {
player = new FakeInputWriter(fakeInputDir.getAbsolutePath(), slot);
if (!player.open()) {
statDropped++;
return;
}
playerWriters[slot] = player;
}
player.writePad(playerStates[slot]);
}
private void publish() {
if (!open && !start()) {
statDropped++;
@@ -60,6 +60,7 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
Handler(worker.looper).post {
gyro.fill(0)
FakeInputWriter.writeMotion(SLOT, accel, gyro)
SteamTouchDevice.current?.setMotion(accel, gyro)
}
worker.quitSafely()
}
@@ -85,6 +86,7 @@ class PadMotion(private val context: Context, private val rotation: () -> Int) :
target[1] = counts(-z * scale)
target[2] = counts(y * scale)
FakeInputWriter.writeMotion(SLOT, accel, gyro)
SteamTouchDevice.current?.setMotion(accel, gyro)
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
@@ -0,0 +1,285 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Bitmap
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",
"#AD3A00", "#AD0000", "#AD0051", "#AD007F", "#AD00AD", "#6800AD", "#4800AD",
)
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, "
else "$action, $label, $icon, ${listOf(foreground, background).filter { it.isNotEmpty() }.joinToString(" ")}"
val hasIcon get() = icon.isNotEmpty()
}
fun parse(binding: String): Binding {
val parts = binding.split(',').map { it.trim() }
val colors = parts.getOrNull(3).orEmpty().split(' ').filter { it.startsWith("#") }
return Binding(parts.getOrNull(0).orEmpty(), parts.getOrNull(1).orEmpty(), parts.getOrNull(2).orEmpty(),
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")
SteamTouchConfig.X -> listOf("button_diamond" to "button_x")
SteamTouchConfig.Y -> listOf("button_diamond" to "button_y")
SteamTouchConfig.SELECT -> listOf("switch" to "button_menu")
SteamTouchConfig.START -> listOf("switch" to "button_escape")
SteamTouchConfig.BUMPER_LEFT -> listOf("switch" to "left_bumper")
SteamTouchConfig.BUMPER_RIGHT -> listOf("switch" to "right_bumper")
SteamTouchConfig.TRIGGER_LEFT -> listOf("left_trigger" to "click")
SteamTouchConfig.TRIGGER_RIGHT -> listOf("right_trigger" to "click")
SteamTouchConfig.JOYSTICK_LEFT_BUTTON -> listOf("joystick" to "click")
SteamTouchConfig.JOYSTICK_RIGHT_BUTTON -> listOf("right_joystick" to "click")
SteamTouchConfig.MACRO_1_FINGER -> listOf("switch" to "button_macro_1finger")
SteamTouchConfig.MACRO_2_FINGER -> listOf("switch" to "button_macro_2finger")
SteamTouchConfig.DPAD -> DPAD_INPUTS.map { "dpad" to it }
in SteamTouchConfig.MACRO_0..SteamTouchConfig.MACRO_0 + 7 -> listOf("switch" to "button_macro${type - SteamTouchConfig.MACRO_0}")
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())
return inputsOf(type).map { (source, input) ->
stack.firstNotNullOfOrNull { p -> groupFor(p, source)?.let { Ref(it, input) } }
}
}
private fun groupFor(preset: KeyValues.Node, source: String): String? =
preset.child("group_source_bindings")?.entries?.firstOrNull { (_, v) ->
val parts = (v as? String)?.split(' ') ?: return@firstOrNull false
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
val activator = activators.child("Full_Press") ?: activators.entries.firstNotNullOfOrNull { it.second as? KeyValues.Node }
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
return when (words[0]) {
"xinput_button" -> XINPUT_GLYPHS[arg] ?: arg
"key_press" -> KEY_GLYPHS[arg] ?: arg.take(4)
"mouse_button" -> when (arg) { "LEFT" -> "LMB"; "RIGHT" -> "RMB"; "MIDDLE" -> "MMB"; else -> "M" + arg.take(2) }
"mouse_wheel" -> if (arg.contains("UP")) "▲" else "▼"
else -> null
}
}
private val XINPUT_GLYPHS = mapOf(
"SHOULDER_LEFT" to "LB", "SHOULDER_RIGHT" to "RB", "TRIGGER_LEFT" to "LT", "TRIGGER_RIGHT" to "RT",
"JOYSTICK_LEFT" to "L3", "JOYSTICK_RIGHT" to "R3", "START" to "☰", "SELECT" to "⧉", "BACK" to "⧉",
"DPAD_UP" to "▲", "DPAD_DOWN" to "▼", "DPAD_LEFT" to "◀", "DPAD_RIGHT" to "▶",
)
private val KEY_GLYPHS = mapOf(
"RETURN" to "⏎", "SPACE" to "␣", "ESCAPE" to "Esc", "TAB" to "Tab", "BACKSPACE" to "⌫",
"LEFT_SHIFT" to "⇧", "RIGHT_SHIFT" to "⇧", "LEFT_CONTROL" to "Ctrl", "RIGHT_CONTROL" to "Ctrl",
"LEFT_ALT" to "Alt", "RIGHT_ALT" to "Alt", "UP_ARROW" to "↑", "DOWN_ARROW" to "↓",
"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) ->
Vdf.value(tokens, s, e, "id") == ref.groupId
} ?: return null
val inputs = Vdf.blocks(tokens, group.first, group.second, "inputs").firstOrNull() ?: return null
val input = Vdf.blocks(tokens, inputs.first, inputs.second, ref.input).firstOrNull() ?: return null
val targets = (input.first until input.second).filter { i ->
tokens[i].text.equals("binding", true) && tokens[i].quoted && i + 1 < input.second && tokens[i + 1].quoted
}.map { tokens[it + 1] }
if (targets.isEmpty()) return null
val out = StringBuilder(text)
for (t in targets.sortedByDescending { it.start }) out.replace(t.start, t.end, change(parse(t.text)).compose())
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)
fun tokens(text: String): List<Token> {
val out = mutableListOf<Token>()
var i = 0
while (i < text.length) {
val c = text[i]
when {
c.isWhitespace() -> i++
c == '/' && i + 1 < text.length && text[i + 1] == '/' -> while (i < text.length && text[i] != '\n') i++
c == '{' || c == '}' -> { out += Token(c.toString(), false, i, i + 1); i++ }
c == '"' -> {
val start = i + 1
i++
while (i < text.length && text[i] != '"') { if (text[i] == '\\') i++; i++ }
out += Token(text.substring(start, minOf(i, text.length)), true, start, minOf(i, text.length))
i++
}
else -> {
val start = i
while (i < text.length && !text[i].isWhitespace() && text[i] != '{' && text[i] != '}' && text[i] != '"') i++
out += Token(text.substring(start, i), false, start, i)
}
}
}
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
var depth = 0
while (i < to) {
val t = tokens[i]
if (t.text == "{" && !t.quoted) depth++
else if (t.text == "}" && !t.quoted) depth--
else if (depth == 0 && t.quoted && t.text.equals(key, true) && i + 1 < to && tokens[i + 1].text == "{" && !tokens[i + 1].quoted) {
val open = i + 1
var d = 0
var j = open
while (j < to) {
if (tokens[j].text == "{" && !tokens[j].quoted) d++
if (tokens[j].text == "}" && !tokens[j].quoted) { d--; if (d == 0) break }
j++
}
found += (open + 1) to j
i = j + 1
continue
}
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) {
var d = 0
var j = top
while (j < to) {
if (tokens[j].text == "{" && !tokens[j].quoted) d++
if (tokens[j].text == "}" && !tokens[j].quoted) { d--; if (d == 0) break }
j++
}
return blocks(tokens, top + 1, j, key)
}
}
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
while (i < to) {
val t = tokens[i]
if (t.text == "{" && !t.quoted) depth++
else if (t.text == "}" && !t.quoted) depth--
else if (depth == 0 && t.quoted && t.text.equals(key, true) && i + 1 < to && tokens[i + 1].quoted) return tokens[i + 1].text
i++
}
return null
}
}
// ---- Icons ----
private val cache = object : LruCache<String, Bitmap>(24 * 1024 * 1024) {
override fun sizeOf(key: String, value: Bitmap) = value.byteCount
}
private val missing = HashSet<String>()
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")
installDir?.let { File(SteamTouchConfig.steamRoot(context), "steamapps/common/$it/TouchMenuIcons") }?.takeIf { it.isDirectory }
} catch (_: Exception) {
null
}
fun iconFile(context: Context, appId: Int, name: String): File? {
if (name.isEmpty() || name.contains('/')) return null
gameIconsDir(context, appId)?.let { File(it, name) }?.takeIf { it.isFile }?.let { return it }
File(libraryDir(context), name).takeIf { it.isFile }?.let { return it }
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 }
if (key in missing) return null
val file = iconFile(context, appId, name)
val bitmap = file?.let {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(it.path, bounds)
var sample = 1
while (bounds.outWidth / (sample * 2) >= size) sample *= 2
BitmapFactory.decodeFile(it.path, BitmapFactory.Options().apply { inSampleSize = sample })
}
if (bitmap == null) missing += key else cache.put(key, bitmap)
return bitmap
}
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()
return own + library.filter { it !in own }
}
}
@@ -0,0 +1,654 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
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
const val JOYSTICK_LEFT_BUTTON = 3
const val JOYSTICK_RIGHT = 4
const val JOYSTICK_RIGHT_BUTTON = 5
const val DPAD = 6
const val A = 7
const val B = 8
const val X = 9
const val Y = 10
const val SELECT = 11
const val START = 12
const val TRIGGER_LEFT = 13
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 TRACKPAD_CENTER = 25
const val TRACKPAD_LEFT = 26
const val TRACKPAD_RIGHT = 27
const val KEYBOARD = 28
const val MACRO_1_FINGER = 30
const val MACRO_2_FINGER = 31
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)
while (p.more()) {
val start = p.pos
val (field, wire) = p.key()
p.skip(wire)
if (field !in 2..4) out.write(rest, start, p.pos - start)
}
tag(out, 2, 0); varint(out, inputMode.toLong())
if (mouseMode != 0) { tag(out, 3, 0); varint(out, mouseMode.toLong()) }
tag(out, 4, 5); fixed(out, trackpadSensitivity)
return out.toByteArray()
}
companion object {
fun decode(rest: ByteArray): Options {
var input = INPUT_CONTROLLER
var mouse = 0
var sensitivity = 1f
val p = Proto(rest)
while (p.more()) {
val (field, wire) = p.key()
when {
field == 2 && wire == 0 -> input = p.varint().toInt()
field == 3 && wire == 0 -> mouse = p.varint().toInt()
field == 4 && wire == 5 -> sensitivity = p.float()
else -> p.skip(wire)
}
}
return Options(input, mouse, sensitivity)
}
}
}
const val INPUT_MOUSE = 1
const val INPUT_CONTROLLER = 2
const val INPUT_BOTH = 3
const val MOUSE_ABSOLUTE = 2
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) ->
(v as? KeyValues.Node)?.let { key to (it.string("title") ?: key) }
}?.toMap().orEmpty()
val sets = mappings.children("preset").mapNotNull { preset ->
val id = preset.string("id")?.toIntOrNull() ?: return@mapNotNull null
val name = preset.string("name") ?: ""
(id + 1) to (titles[name]?.takeUnless { it.startsWith("#") } ?: name.ifEmpty { "Set ${id + 1}" })
}.sortedBy { it.first }
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")
} catch (_: Exception) {
null
}
fun steamRoot(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
fun configDir(context: Context): File? {
val base = File(steamRoot(context), "steamapps/common/Steam Controller Configs")
val account = accountId(context)
if (account != null) File(base, "$account/config").takeIf { it.isDirectory }?.let { return it }
return base.listFiles()?.filter { it.name.all(Char::isDigit) && File(it, "config").isDirectory }
?.maxByOrNull { it.lastModified() }?.let { File(it, "config") }
}
/** 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")
val entries = node?.entries?.mapNotNull { (k, v) -> (v as? KeyValues.Node)?.let { k to it } }.orEmpty()
val chosen = entries.firstOrNull { it.second.string("MostRecent") == "1" } ?: entries.firstOrNull()
chosen?.first?.toLongOrNull()?.minus(76561197960265728L)
} catch (_: Exception) {
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) }
if (file == null) {
Log.i(TAG, "steam touch: app $appId has no touch config on disk; default layout")
return Config(null, null, null, emptyMap())
}
return try {
val text = file.readText()
val kv = KeyValues.parse(text.removePrefix(""))
val mappings = kv.child("controller_mappings") ?: kv
val layouts = mappings.string("touch_layout")?.let { hex -> decodeLayouts(hexToBytes(hex)) }
Log.i(TAG, "steam touch: app $appId uses ${file.path} (${layouts?.layouts?.size ?: 0} layouts)")
Config(file, text, layouts, availability(mappings), mappings)
} catch (e: Exception) {
Log.w(TAG, "steam touch: ${file.path} unreadable: $e")
Config(file, null, null, emptyMap())
}
}
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 ->
val start = maxOf(0L, raf.length() - 2_000_000L)
raf.seek(start)
val bytes = ByteArray((raf.length() - start).toInt())
raf.readFully(bytes)
String(bytes)
}
val touchIndex = Regex("""!! Controller (\d+) attributes:\s*\n\s*Type: 43""").findAll(tail).lastOrNull()?.groupValues?.get(1)
if (touchIndex == null) null else {
val loaded = Regex("""Loaded Config for [^\n]*? Path for App ID $appId, Controller $touchIndex: ([^\n]+)""")
.findAll(tail).lastOrNull()?.groupValues?.get(1)?.trim()
loaded?.let { guestPath -> File(LinuxRuntime.rootDir(context), guestPath.trimStart('/').replace("//", "/")) }
}
} catch (_: Exception) {
null
}
private fun autosaveConfig(dir: File, appId: Int): File? = try {
val set = KeyValues.parse(File(dir, CONFIGSET).readText()).child("controller_config")?.child(appId.toString())
if (set?.string("autosave") == "1") File(dir, "$appId/controller_mobile_touch.vdf").takeIf { it.isFile } else null
} catch (_: Exception) {
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 {
set == null -> null
set.string("autosave") == "1" -> File(dir, "$appId/controller_mobile_touch.vdf")
set.string("template") != null -> File(steamRoot(context), "controller_base/templates/" + set.string("template"))
else -> null
}?.takeIf { it.isFile }
} catch (_: Exception) {
null
}
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 }
?.map { it.first }?.toSet().orEmpty()
}
return mappings.children("preset").associate { preset ->
val id = preset.string("id")?.toIntOrNull() ?: 0
val set = mutableSetOf<Int>()
preset.child("group_source_bindings")?.entries?.forEach { (groupId, value) ->
val parts = (value as? String)?.split(' ') ?: return@forEach
if (parts.getOrNull(1) != "active" || parts.contains("modeshift")) return@forEach
val bound = groups[groupId].orEmpty()
when (parts[0]) {
"button_diamond" -> mapOf("button_a" to A, "button_b" to B, "button_x" to X, "button_y" to Y)
.forEach { (input, element) -> if (input in bound) set += element }
"dpad" -> set += DPAD
"joystick" -> { set += JOYSTICK_LEFT; if ("click" in bound) set += JOYSTICK_LEFT_BUTTON }
"right_joystick" -> { set += JOYSTICK_RIGHT; if ("click" in bound) set += JOYSTICK_RIGHT_BUTTON }
"left_trigger" -> set += TRIGGER_LEFT
"right_trigger" -> set += TRIGGER_RIGHT
"left_trackpad" -> set += TRACKPAD_LEFT
"right_trackpad" -> set += TRACKPAD_RIGHT
"center_trackpad" -> set += TRACKPAD_CENTER
"switch" -> bound.forEach { input ->
when (input) {
"button_escape" -> set += START
"button_menu" -> set += SELECT
"left_bumper" -> set += BUMPER_LEFT
"right_bumper" -> set += BUMPER_RIGHT
"button_macro_1finger" -> set += MACRO_1_FINGER
"button_macro_2finger" -> set += MACRO_2_FINGER
else -> Regex("button_macro(\\d)").matchEntire(input)?.let { set += MACRO_0 + it.groupValues[1].toInt() }
}
}
}
}
id to set.toSet()
}
}
private fun hasBinding(input: KeyValues.Node): Boolean =
input.child("activators")?.entries?.any { (_, activator) ->
(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
val faceY = if (rightStick) -0.30f else 0f
val p: Pair<Float, Float> = when (type) {
THUMB -> 75f / 1280 to 75f / 720
STEAM -> 636f / 1280 to 75f / 720
SELECT -> 516f / 1280 to 75f / 720
START -> 756f / 1280 to 75f / 720
KEYBOARD -> 1205f / 1280 to 75f / 720
PASTE -> 1115f / 1280 to 75f / 720
DPAD -> if (leftStick) 0.147f to 0.47f else 200f / 1280 to 525f / 720
A -> 1083f / 1280 to 607f / 720 + faceY
B -> 1163f / 1280 to 527f / 720 + faceY
X -> 1003f / 1280 to 527f / 720 + faceY
Y -> 1083f / 1280 to 447f / 720 + faceY
JOYSTICK_LEFT -> 0.137f to 0.76f
JOYSTICK_RIGHT -> 0.85f to 0.76f
JOYSTICK_LEFT_BUTTON -> 0.29f to 0.88f
JOYSTICK_RIGHT_BUTTON -> 0.71f to 0.88f
BUMPER_LEFT -> 0.06f to 0.205f
TRIGGER_LEFT -> 0.16f to 0.205f
BUMPER_RIGHT -> 0.94f to 0.205f
TRIGGER_RIGHT -> 0.84f to 0.205f
TRACKPAD_LEFT -> 0.3f to 0.55f
TRACKPAD_CENTER -> 0.5f to 0.55f
TRACKPAD_RIGHT -> 0.7f to 0.55f
MACRO_1_FINGER -> 0.42f to 0.92f
MACRO_2_FINGER -> 0.58f to 0.92f
in MACRO_0..MACRO_0 + 7 -> (0.3f + 0.057f * (type - MACRO_0)) to 0.22f
else -> return null
}
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))
val placed = layout?.elements?.associateBy { it.type }.orEmpty()
val optional = OPTIONAL.filter { placed[it]?.visible == true && it !in available }
return (available + optional).mapNotNull { type ->
val own = placed[type]
when {
own != null && !own.visible -> null
own != null -> own
else -> defaultElement(type, available)
}
}.sortedBy { it.type }
}
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,
config: Config,
actionSet: Int,
elements: List<Element>,
color: FloatArray? = null,
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,
config: Config,
sets: Map<Int, List<Element>>,
colors: Map<Int, FloatArray> = emptyMap(),
bindings: Map<SteamTouchBindings.Ref, (SteamTouchBindings.Binding) -> SteamTouchBindings.Binding> = emptyMap(),
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
}
val target = File(dir, "$appId/controller_mobile_touch.vdf")
val old = config.layouts
val keep = old?.layouts?.filter { it.actionSet !in sets.keys }.orEmpty()
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 layouts = Layouts((keep + written).sortedBy { it.actionSet }, options?.encodeInto(rest) ?: rest)
val hex = bytesToHex(encodeLayouts(layouts))
val line = "\t\"touch_layout\"\t\t\"$hex\""
val existing = Regex("""\n\s*"touch_layout"\s+"[0-9a-fA-F]*"""")
val text = if (existing.containsMatchIn(source)) source.replace(existing, "\n$line")
else source.replaceFirst(Regex("""("controller_type"\s+"controller_mobile_touch"[^\n]*)"""), "$1\n$line")
if (!text.contains("touch_layout")) return null
target.parentFile?.mkdirs()
val tmp = File(target.path + ".tmp")
tmp.writeText(text)
if (!tmp.renameTo(target)) return null
selectAutosave(dir, appId)
Log.i(TAG, "steam touch: saved layouts ${sets.keys} for app $appId to ${target.path}")
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"
val entry = "\t\"$appId\"\n\t{\n\t\t\"autosave\"\t\t\"1\"\n\t}"
val block = Regex("""\n\s*"$appId"\s*\{[^}]*\}""")
val next = if (block.containsMatchIn(text)) text.replace(block, "\n$entry")
else text.substring(0, text.lastIndexOf('}')).trimEnd() + "\n$entry\n}\n"
File(file.path + ".tmp").apply { writeText(next) }.renameTo(file)
}
// ---- touch_layout: CVirtualControllerLayouts ----
fun decodeLayouts(bytes: ByteArray): Layouts {
val layouts = mutableListOf<Layout>()
val rest = ByteArrayOutputStream()
val p = Proto(bytes)
while (p.more()) {
val start = p.pos
val (field, wire) = p.key()
if (field == 1 && wire == 2) layouts += decodeLayout(p.bytes())
else { p.skip(wire); rest.write(bytes, start, p.pos - start) }
}
return Layouts(layouts, rest.toByteArray())
}
private fun decodeLayout(bytes: ByteArray): Layout {
var actionSet = 0
var version: Int? = null
var color: FloatArray? = null
val elements = mutableListOf<Element>()
val p = Proto(bytes)
while (p.more()) {
val (field, wire) = p.key()
when {
field == 1 && wire == 0 -> version = p.varint().toInt()
field == 2 && wire == 0 -> actionSet = p.varint().toInt()
field == 4 && wire == 2 -> elements += decodeElement(p.bytes())
field == 5 && wire == 2 -> color = decodeColor(p.bytes())
else -> p.skip(wire)
}
}
return Layout(actionSet, elements, color, version)
}
private fun decodeElement(bytes: ByteArray): Element {
var type = -1
var visible = false
var x = 0f
var y = 0f
var sx = 1f
var sy = 1f
val p = Proto(bytes)
while (p.more()) {
val (field, wire) = p.key()
when {
field == 1 && wire == 0 -> type = p.varint().toInt()
field == 2 && wire == 0 -> visible = p.varint() != 0L
field == 3 && wire == 5 -> x = p.float()
field == 4 && wire == 5 -> y = p.float()
field == 5 && wire == 5 -> sx = p.float()
field == 6 && wire == 5 -> sy = p.float()
else -> p.skip(wire)
}
}
return Element(type, visible, x, y, sx, sy)
}
private fun decodeColor(bytes: ByteArray): FloatArray {
val c = floatArrayOf(1f, 1f, 1f, 1f)
val p = Proto(bytes)
while (p.more()) {
val (field, wire) = p.key()
if (field in 1..4 && wire == 5) c[field - 1] = p.float() else p.skip(wire)
}
return c
}
fun encodeLayouts(layouts: Layouts): ByteArray {
val out = ByteArrayOutputStream()
layouts.layouts.forEach { layout ->
val l = ByteArrayOutputStream()
layout.version?.let { tag(l, 1, 0); varint(l, it.toLong()) }
tag(l, 2, 0); varint(l, layout.actionSet.toLong())
layout.elements.forEach { e ->
val m = ByteArrayOutputStream()
tag(m, 1, 0); varint(m, e.type.toLong())
tag(m, 2, 0); varint(m, if (e.visible) 1 else 0)
tag(m, 3, 5); fixed(m, e.x)
tag(m, 4, 5); fixed(m, e.y)
tag(m, 5, 5); fixed(m, e.xScale)
tag(m, 6, 5); fixed(m, e.yScale)
tag(l, 4, 2); bytes(l, m.toByteArray())
}
layout.color?.let { c ->
val m = ByteArrayOutputStream()
for (i in 0 until 4) { tag(m, i + 1, 5); fixed(m, c[i]) }
tag(l, 5, 2); bytes(l, m.toByteArray())
}
tag(out, 1, 2); bytes(out, l.toByteArray())
}
out.write(layouts.rest)
return out.toByteArray()
}
private fun tag(out: ByteArrayOutputStream, field: Int, wire: Int) = varint(out, (field shl 3 or wire).toLong())
private fun varint(out: ByteArrayOutputStream, value: Long) {
var v = value
while (true) {
if (v and 0x7fL.inv() == 0L) { out.write(v.toInt()); return }
out.write((v and 0x7f or 0x80).toInt())
v = v ushr 7
}
}
private fun fixed(out: ByteArrayOutputStream, f: Float) {
val bits = java.lang.Float.floatToIntBits(f)
for (i in 0 until 4) out.write(bits ushr (8 * i) and 0xff)
}
private fun bytes(out: ByteArrayOutputStream, b: ByteArray) { varint(out, b.size.toLong()); out.write(b) }
private class Proto(val data: ByteArray) {
var pos = 0
fun varint(): Long {
var shift = 0
var result = 0L
while (pos < data.size) {
val b = data[pos++].toInt() and 0xff
result = result or ((b and 0x7f).toLong() shl shift)
if (b and 0x80 == 0) break
shift += 7
}
return result
}
fun float(): Float {
var bits = 0
for (i in 0 until 4) bits = bits or ((data[pos + i].toInt() and 0xff) shl (8 * i))
pos += 4
return java.lang.Float.intBitsToFloat(bits)
}
fun bytes(): ByteArray {
val n = varint().toInt()
return data.copyOfRange(pos, pos + n).also { pos += n }
}
fun skip(wire: Int) {
when (wire) {
0 -> varint()
1 -> pos += 8
2 -> pos += varint().toInt()
5 -> pos += 4
else -> pos = data.size
}
}
fun more() = pos < data.size
fun key(): Pair<Int, Int> = varint().toInt().let { (it ushr 3) to (it and 7) }
}
fun hexToBytes(hex: String) = ByteArray(hex.length / 2) { hex.substring(2 * it, 2 * it + 2).toInt(16).toByte() }
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?
fun children(key: String): List<Node> = entries.filter { it.first.equals(key, true) && it.second is Node }.map { it.second as Node }
fun string(key: String): String? = entries.firstOrNull { it.first.equals(key, true) && it.second is String }?.second as String?
}
companion object {
fun parse(text: String): Node {
val tokens = tokenize(text)
var i = 0
fun node(): Node {
val n = Node()
while (i < tokens.size) {
val t = tokens[i++]
if (t == "}" ) return n
if (t == "{") continue
if (i >= tokens.size) break
val next = tokens[i]
if (next == "{") { i++; n.entries += t to node() } else { i++; n.entries += t to next }
}
return n
}
return node()
}
private fun tokenize(text: String): List<String> {
val out = mutableListOf<String>()
var i = 0
while (i < text.length) {
val c = text[i]
when {
c.isWhitespace() -> i++
c == '/' && i + 1 < text.length && text[i + 1] == '/' -> while (i < text.length && text[i] != '\n') i++
c == '{' || c == '}' -> { out += c.toString(); i++ }
c == '"' -> {
val sb = StringBuilder()
i++
while (i < text.length && text[i] != '"') {
if (text[i] == '\\' && i + 1 < text.length) {
i++
sb.append(when (text[i]) { 'n' -> '\n'; 't' -> '\t'; else -> text[i] })
} else sb.append(text[i])
i++
}
i++
out += sb.toString()
}
c == '[' -> { while (i < text.length && text[i] != ']') i++; i++ }
else -> {
val start = i
while (i < text.length && !text[i].isWhitespace() && text[i] != '{' && text[i] != '}' && text[i] != '"') i++
out += text.substring(start, i)
}
}
}
return out
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,171 @@
package com.droiddeck.launcher.input
import android.util.Log
import java.io.File
import java.io.RandomAccessFile
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,
val actionSet: Int,
val layers: List<Int>,
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()
for (i in 0 until 8) next[i] = (buttons ushr (8 * i)).toByte()
for (i in 0 until 4) putShort(next, 8 + 2 * i, sticks[i])
for (i in 0 until 6) putShort(next, 16 + 2 * i, pads[i])
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
if (!value) synchronized(this) {
val next = report.copyOf()
for (i in 28 until 40) next[i] = 0
publish(next)
}
}
private fun putShort(into: ByteArray, at: Int, value: Short) {
into[at] = value.toInt().toByte()
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)
buffer.putLong(OFF_REPORT_SEQ, ++reportSeq)
for (i in 0 until REPORT_BYTES) buffer.put(OFF_REPORT + i, report[i])
buffer.putLong(OFF_REPORT_SEQ, ++reportSeq)
}
var plugged: Boolean
get() = buffer.getInt(OFF_PLUGGED) != 0
set(value) {
if (value == plugged) return
if (!value) synchronized(this) { publish(ByteArray(REPORT_BYTES)) }
buffer.putInt(OFF_PLUGGED, if (value) 1 else 0)
Log.i(TAG, "steam touch: " + if (value) "plugged in" else "unplugged")
}
fun setBattery(percent: Int) = buffer.putInt(OFF_BATTERY, percent.coerceIn(0, 100))
fun state(): State {
repeat(8) {
val seq = buffer.getLong(OFF_STATE_SEQ)
if (seq and 1L != 0L) return@repeat
val count = buffer.getInt(OFF_LAYER_COUNT).coerceIn(0, 8)
val read = State(
opened = buffer.getInt(OFF_OPENED),
appId = buffer.getInt(OFF_APPID),
actionSet = buffer.getInt(OFF_ACTION_SET),
layers = (0 until count).map { buffer.getInt(OFF_LAYERS + 4 * it) },
actionSeq = buffer.getInt(OFF_ACTION_SEQ),
)
if (seq == buffer.getLong(OFF_STATE_SEQ)) return read
}
return State(0, 0, 0, emptyList(), -1)
}
companion object {
private const val TAG = "SteamTouch"
const val REPORT_BYTES = 40
private const val SIZE = 256
private const val MAGIC = 0x31484354 // TCH1
private const val OFF_REPORT_SEQ = 8
private const val OFF_REPORT = 16
private const val OFF_PLUGGED = 56
private const val OFF_BATTERY = 60
private const val OFF_STATE_SEQ = 64
private const val OFF_OPENED = 72
private const val OFF_APPID = 76
private const val OFF_ACTION_SET = 80
private const val OFF_LAYER_COUNT = 84
private const val OFF_LAYERS = 88
private const val OFF_SETTING30 = 132
private const val OFF_ACTION_SEQ = 136
@Volatile
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()
RandomAccessFile(file, "rw").use { raf ->
raf.setLength(SIZE.toLong())
val map = raf.channel.map(FileChannel.MapMode.READ_WRITE, 0, SIZE.toLong()).order(ByteOrder.LITTLE_ENDIAN)
map.putInt(4, 1)
map.putInt(0, MAGIC)
current = SteamTouchDevice(map)
}
file.setReadable(true, false)
file.setWritable(true, false)
file
} catch (e: Exception) {
Log.w(TAG, "steam touch: no shared file: $e")
current = null
null
}
fun release() {
current?.plugged = false
current = null
}
}
}
@@ -0,0 +1,274 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.GradientDrawable
import android.os.Handler
import android.os.Looper
import android.text.InputType
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.EditText
import android.widget.GridView
import android.widget.HorizontalScrollView
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
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,
private val appId: Int,
private val title: String,
private val current: SteamTouchBindings.Binding,
private val onPicked: (SteamTouchBindings.Binding) -> Unit,
) {
private val main = Handler(Looper.getMainLooper())
private val loader = Executors.newFixedThreadPool(2)
private var icon = current.icon
private var foreground = current.foreground.ifEmpty { SteamTouchBindings.DEFAULT_FOREGROUND }
private var background = current.background.ifEmpty { SteamTouchBindings.DEFAULT_BACKGROUND }
private val density = context.resources.displayMetrics.density
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 {
hint = "Label (optional)"
setText(current.label)
inputType = InputType.TYPE_CLASS_TEXT
setSingleLine()
}
left.addView(label)
val preview = ImageView(context)
val names = SteamTouchBindings.iconNames(context, appId)
val grid = GridView(context).apply {
numColumns = GridView.AUTO_FIT
columnWidth = dp(56)
stretchMode = GridView.STRETCH_COLUMN_WIDTH
verticalSpacing = dp(6)
horizontalSpacing = dp(6)
}
val adapter = IconAdapter(names)
grid.adapter = adapter
grid.setOnItemClickListener { _, _, position, _ ->
icon = names[position]
adapter.notifyDataSetChanged()
updatePreview(preview)
}
left.addView(LinearLayout(context).apply {
gravity = Gravity.CENTER_VERTICAL
setPadding(0, dp(8), 0, 0)
addView(preview, LinearLayout.LayoutParams(dp(56), dp(56)))
addView(TextView(context).apply {
text = if (names.isEmpty()) "Steam's icons were not found" else "${names.size} icons from Steam"
setPadding(dp(12), 0, 0, 0)
})
})
left.addView(paletteRow("Icon colour", { foreground }) { foreground = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
left.addView(paletteRow("Button colour", { background }) { background = it; adapter.notifyDataSetChanged(); updatePreview(preview) })
root.addView(left, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f))
root.addView(grid, LinearLayout.LayoutParams(0, dp(250), 1.2f).apply { marginStart = dp(16) })
updatePreview(preview)
showPanel(host, title, root, listOf(
"No icon" to {
onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = "", foreground = "", background = ""))
},
"Cancel" to {},
"Use" to {
onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = icon,
foreground = if (icon.isEmpty()) "" else foreground, background = if (icon.isEmpty()) "" else background))
},
)) { loader.shutdown() }
}
private fun paletteRow(name: String, value: () -> String, onPick: (String) -> Unit): View {
val row = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }
val swatches = mutableListOf<View>()
fun refresh() = swatches.forEachIndexed { i, v ->
(v.background as GradientDrawable).setStroke(dp(if (SteamTouchBindings.PALETTE[i].equals(value(), true)) 3 else 1),
if (SteamTouchBindings.PALETTE[i].equals(value(), true)) Color.rgb(102, 192, 244) else Color.GRAY)
}
SteamTouchBindings.PALETTE.forEach { hex ->
val swatch = View(context).apply {
background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(Color.parseColor(hex)) }
setOnClickListener { onPick(hex); refresh() }
}
swatches += swatch
row.addView(swatch, LinearLayout.LayoutParams(dp(30), dp(30)).apply { marginEnd = dp(6) })
}
refresh()
return LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
setPadding(0, dp(8), 0, 0)
addView(TextView(context).apply { text = name })
addView(HorizontalScrollView(context).apply { addView(row) })
}
}
private fun updatePreview(view: ImageView) {
if (icon.isEmpty()) { view.setImageDrawable(null); view.background = null; return }
loader.execute {
val bitmap = SteamTouchBindings.icon(context, appId, icon, 128)?.let { render(it, dp(56)) }
main.post { view.setImageBitmap(bitmap) }
}
}
/** 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)
val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
paint.color = Color.parseColor(background)
canvas.drawCircle(size / 2f, size / 2f, size / 2f, paint)
drawSteamIcon(canvas, icon, android.graphics.RectF(size * 0.18f, size * 0.18f, size * 0.82f, size * 0.82f), Color.parseColor(foreground), paint)
return out
}
private inner class IconAdapter(val names: List<String>) : BaseAdapter() {
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 {
SteamTouchBindings.icon(context, appId, name, 96)
main.post {
loading.remove(name)
if (refreshQueued) return@post
refreshQueued = true
main.postDelayed({ refreshQueued = false; notifyDataSetChanged() }, 120)
}
}
}
override fun getCount() = names.size
override fun getItem(position: Int) = names[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = (convertView as? ImageView) ?: ImageView(context).apply {
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(56))
setPadding(dp(8), dp(8), dp(8), dp(8))
}
val name = names[position]
view.tag = name
view.background = GradientDrawable().apply {
cornerRadius = dp(8).toFloat()
setColor(Color.parseColor(background))
if (name == icon) setStroke(dp(3), Color.rgb(102, 192, 244))
}
view.colorFilter = null
val cached = SteamTouchBindings.cachedIcon(appId, name, 96)
if (cached != null) {
val t = tinted(name, cached)
if ((view.drawable as? android.graphics.drawable.BitmapDrawable)?.bitmap !== t) view.setImageBitmap(t)
} else {
view.setImageDrawable(null)
load(name)
}
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 {
val key = "$name|$foreground"
thumbs.get(key)?.let { return it }
val out = Bitmap.createBitmap(icon.width, icon.height, Bitmap.Config.ARGB_8888)
drawSteamIcon(Canvas(out), icon, android.graphics.RectF(0f, 0f, icon.width.toFloat(), icon.height.toFloat()),
Color.parseColor(foreground), Paint(Paint.FILTER_BITMAP_FLAG))
thumbs.put(key, out)
return out
}
}
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
fun dp(v: Int) = (v * density).toInt()
val scrim = android.widget.FrameLayout(context).apply {
setBackgroundColor(Color.argb(140, 0, 0, 0))
isClickable = true
isFocusable = true
}
// DroidDeck's panel: dark surface, rounded, a hairline border.
val card = LinearLayout(context).apply {
orientation = LinearLayout.VERTICAL
background = GradientDrawable().apply {
cornerRadius = dp(18).toFloat(); setColor(Color.rgb(18, 20, 23)); setStroke(dp(1), Color.rgb(38, 42, 49))
}
setPadding(dp(12), dp(14), dp(12), dp(10))
isClickable = true
}
card.addView(TextView(context).apply {
text = title
textSize = 15f
setTypeface(android.graphics.Typeface.DEFAULT_BOLD)
gravity = Gravity.CENTER
setTextColor(Color.WHITE)
setPadding(dp(16), 0, dp(16), dp(4))
})
card.addView(content)
val row = LinearLayout(context).apply { gravity = Gravity.CENTER; setPadding(dp(8), dp(10), dp(8), 0) }
fun close() {
(scrim.parent as? ViewGroup)?.removeView(scrim)
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
imm.hideSoftInputFromWindow(host.windowToken, 0)
onClose()
}
buttons.forEachIndexed { i, (name, action) ->
row.addView(TextView(context).apply {
text = name
gravity = Gravity.CENTER
textSize = 14f
setTextColor(Color.WHITE)
val primary = i == buttons.size - 1
setTextColor(if (primary) Color.rgb(3, 17, 31) else Color.rgb(242, 244, 247))
background = GradientDrawable().apply {
cornerRadius = dp(12).toFloat()
if (primary) setColor(Color.rgb(26, 159, 255)) else { setColor(Color.rgb(26, 29, 34)); setStroke(dp(1), Color.rgb(52, 58, 67)) }
}
setPadding(dp(20), dp(10), dp(20), dp(10))
setOnClickListener { close(); action() }
}, LinearLayout.LayoutParams(0, dp(44), 1f).apply { marginStart = dp(6); marginEnd = dp(6) })
}
card.addView(row)
val width = minOf(dp(640), (context.resources.displayMetrics.widthPixels * 0.9f).toInt())
scrim.addView(card, android.widget.FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER))
scrim.setOnClickListener { close() }
host.addView(scrim, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
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)
}
}
}