mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 21:06:09 +00:00
Unify input profiles and configurable controller surfaces
This commit is contained in:
1 parent
906e0d1f7d
commit
ab8f41b80e
33 files changed
+2526
-198
No files matched your search
@@ -5,53 +5,139 @@ object DeckControls {
|
||||
const val R4 = 2
|
||||
const val L5 = 4
|
||||
const val R5 = 8
|
||||
private const val LEFT_TOUCH = 16
|
||||
private const val RIGHT_TOUCH = 32
|
||||
private const val LEFT_CLICK = 64
|
||||
private const val RIGHT_CLICK = 128
|
||||
|
||||
private const val SLOT = 0
|
||||
|
||||
private var controls = 0
|
||||
private val controls = arrayOf(InputControl.L4, InputControl.R4, InputControl.L5, InputControl.R5,
|
||||
InputControl.LEFT_PAD, InputControl.RIGHT_PAD, InputControl.LEFT_CLICK, InputControl.RIGHT_CLICK)
|
||||
private val sources = ArrayList<Source>()
|
||||
private val physical = Source(InputRole.PHYSICAL)
|
||||
private var router: InputRouter? = null
|
||||
private val pads = ShortArray(4)
|
||||
private val pressure = ShortArray(2)
|
||||
|
||||
@Synchronized
|
||||
fun setGrip(bit: Int, down: Boolean) {
|
||||
set(bit, down)
|
||||
fun setRouter(next: InputRouter?) {
|
||||
for (source in sources) source.closeRoutes()
|
||||
router = next
|
||||
for (source in sources) source.configure()
|
||||
publish()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setPad(right: Boolean, touching: Boolean, x: Float = 0f, y: Float = 0f) {
|
||||
val at = if (right) 2 else 0
|
||||
set(if (right) RIGHT_TOUCH else LEFT_TOUCH, touching)
|
||||
pads[at] = if (touching) axis(x) else 0
|
||||
pads[at + 1] = if (touching) axis(y) else 0
|
||||
publish()
|
||||
}
|
||||
fun source(role: InputRole) = Source(role)
|
||||
|
||||
@Synchronized
|
||||
fun setClick(right: Boolean, down: Boolean) {
|
||||
set(if (right) RIGHT_CLICK else LEFT_CLICK, down)
|
||||
pressure[if (right) 1 else 0] = if (down) Short.MAX_VALUE else 0
|
||||
publish()
|
||||
}
|
||||
fun setGrip(bit: Int, down: Boolean) = physical.setGrip(bit, down)
|
||||
|
||||
@Synchronized
|
||||
fun setPad(right: Boolean, touching: Boolean, x: Float = 0f, y: Float = 0f) = physical.setPad(right, touching, x, y)
|
||||
|
||||
@Synchronized
|
||||
fun setClick(right: Boolean, down: Boolean) = physical.setClick(right, down)
|
||||
|
||||
@Synchronized
|
||||
fun releaseAll() {
|
||||
if (controls == 0 && pads.all { it.toInt() == 0 } && pressure.all { it.toInt() == 0 }) return
|
||||
controls = 0
|
||||
pads.fill(0)
|
||||
pressure.fill(0)
|
||||
for (source in sources) source.clear()
|
||||
publish()
|
||||
}
|
||||
|
||||
private fun set(bit: Int, on: Boolean) {
|
||||
controls = if (on) controls or bit else controls and bit.inv()
|
||||
@Synchronized
|
||||
fun suspend() {
|
||||
for (source in sources) source.suspend()
|
||||
publish()
|
||||
}
|
||||
|
||||
private fun axis(value: Float): Short = (value.coerceIn(-1f, 1f) * Short.MAX_VALUE).toInt().toShort()
|
||||
@Synchronized
|
||||
fun refresh() {
|
||||
for (source in sources) source.route()
|
||||
publish()
|
||||
}
|
||||
|
||||
private fun publish() = FakeInputWriter.writeDeckControls(SLOT, controls, pads, pressure)
|
||||
class Source internal constructor(private val role: InputRole) {
|
||||
private val x = FloatArray(8)
|
||||
private val y = FloatArray(8)
|
||||
private val touched = BooleanArray(8)
|
||||
private var routes: Array<InputRouter.Channel>? = null
|
||||
internal var mask = 0
|
||||
internal val axes = ShortArray(4)
|
||||
|
||||
internal fun configure() {
|
||||
routes = router?.let { r -> Array(8) { r.channel(role, controls[it]) } }
|
||||
}
|
||||
|
||||
private fun attach() {
|
||||
if (this !in sources) { sources.add(this); configure() }
|
||||
}
|
||||
|
||||
fun setGrip(bit: Int, down: Boolean) = synchronized(DeckControls) {
|
||||
val at = when (bit) { L4 -> 0; R4 -> 1; L5 -> 2; R5 -> 3; else -> return@synchronized }
|
||||
update(at, if (down) 1f else 0f)
|
||||
}
|
||||
|
||||
fun setPad(right: Boolean, touching: Boolean, x: Float = 0f, y: Float = 0f) = synchronized(DeckControls) {
|
||||
update(if (right) 5 else 4, if (touching) x else 0f, if (touching) y else 0f, touching)
|
||||
}
|
||||
|
||||
fun setClick(right: Boolean, down: Boolean) = synchronized(DeckControls) {
|
||||
update(if (right) 7 else 6, if (down) 1f else 0f)
|
||||
}
|
||||
|
||||
private fun update(at: Int, value: Float, second: Float = 0f, contact: Boolean = false) {
|
||||
val timing = InputTiming.begin()
|
||||
attach()
|
||||
x[at] = value; y[at] = second; touched[at] = contact
|
||||
route()
|
||||
publish()
|
||||
InputTiming.end(timing)
|
||||
}
|
||||
|
||||
internal fun route() {
|
||||
mask = 0
|
||||
axes.fill(0)
|
||||
for (i in controls.indices) {
|
||||
val target = if (routes == null) controls[i] else routes!![i].update(x[i], y[i], touched[i]) ?: continue
|
||||
val at = controls.indexOf(target)
|
||||
if (at < 0) continue
|
||||
if (at == 4 || at == 5) {
|
||||
if (touched[i]) {
|
||||
mask = mask or (1 shl at)
|
||||
axes[(at - 4) * 2] = axis(x[i]); axes[(at - 4) * 2 + 1] = axis(y[i])
|
||||
}
|
||||
} else if (x[i] > 0.5f) mask = mask or (1 shl at)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun clear() {
|
||||
x.fill(0f); y.fill(0f); touched.fill(false); mask = 0; axes.fill(0)
|
||||
routes?.forEach { it.release() }
|
||||
}
|
||||
|
||||
internal fun suspend() {
|
||||
mask = 0; axes.fill(0)
|
||||
routes?.forEach { it.suspend() }
|
||||
}
|
||||
|
||||
fun release() = synchronized(DeckControls) { clear(); publish() }
|
||||
|
||||
internal fun closeRoutes() { routes?.forEach { it.close() }; routes = null }
|
||||
|
||||
fun close() = synchronized(DeckControls) {
|
||||
clear(); closeRoutes(); sources.remove(this); publish()
|
||||
}
|
||||
}
|
||||
|
||||
private fun axis(value: Float) = (value.coerceIn(-1f, 1f) * Short.MAX_VALUE).toInt().toShort()
|
||||
|
||||
private fun publish() {
|
||||
var mask = 0
|
||||
pads.fill(0)
|
||||
for (source in sources) {
|
||||
mask = mask or source.mask
|
||||
for (side in 0..1) if (source.mask and (16 shl side) != 0) {
|
||||
pads[side * 2] = source.axes[side * 2]
|
||||
pads[side * 2 + 1] = source.axes[side * 2 + 1]
|
||||
}
|
||||
}
|
||||
pressure[0] = if (mask and 64 != 0) Short.MAX_VALUE else 0
|
||||
pressure[1] = if (mask and 128 != 0) Short.MAX_VALUE else 0
|
||||
FakeInputWriter.writeDeckControls(0, mask, pads, pressure)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
class HeldInput(private val emit: (Int, Boolean) -> Unit) {
|
||||
private val owners = IntArray(768)
|
||||
|
||||
@Synchronized
|
||||
fun set(source: Int, code: Int, down: Boolean) {
|
||||
if (code !in owners.indices) return
|
||||
val before = owners[code]
|
||||
val after = if (down) before or source else before and source.inv()
|
||||
owners[code] = after
|
||||
if ((before == 0) != (after == 0)) emit(code, after != 0)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun release(source: Int) {
|
||||
for (code in owners.indices) if (owners[code] and source != 0) set(source, code, false)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun clear() {
|
||||
for (code in owners.indices) if (owners[code] != 0) {
|
||||
owners[code] = 0
|
||||
emit(code, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.Choreographer
|
||||
|
||||
class InputMotion(private val router: () -> InputRouter?) : Choreographer.FrameCallback {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var scheduled = false
|
||||
private var lastFrame = 0L
|
||||
private val start = Runnable {
|
||||
if (!scheduled) {
|
||||
scheduled = true
|
||||
lastFrame = System.nanoTime()
|
||||
Choreographer.getInstance().postFrameCallback(this)
|
||||
}
|
||||
}
|
||||
|
||||
fun request() {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) start.run() else handler.post(start)
|
||||
}
|
||||
|
||||
override fun doFrame(frameTimeNanos: Long) {
|
||||
val dt = (frameTimeNanos - lastFrame).coerceAtLeast(0) / 1_000_000_000f
|
||||
lastFrame = frameTimeNanos
|
||||
if (router()?.tick(dt) == true) Choreographer.getInstance().postFrameCallback(this)
|
||||
else scheduled = false
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
handler.removeCallbacks(start)
|
||||
Choreographer.getInstance().removeFrameCallback(this)
|
||||
scheduled = false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
enum class InputRole { PHYSICAL, PRIMARY, SECONDARY }
|
||||
|
||||
enum class InputControl(val id: String, val label: String, val dimensions: Int = 1) {
|
||||
A("a", "A"), B("b", "B"), X("x", "X"), Y("y", "Y"),
|
||||
LB("lb", "L1"), RB("rb", "R1"), SELECT("select", "View / Select"), START("start", "Menu / Start"),
|
||||
L3("l3", "L3"), R3("r3", "R3"), GUIDE("guide", "Steam / Guide"), QAM("qam", "Quick access"),
|
||||
UP("up", "D-pad up"), RIGHT("right", "D-pad right"), DOWN("down", "D-pad down"), LEFT("left", "D-pad left"),
|
||||
LT("lt", "L2"), RT("rt", "R2"), LS("ls", "Left stick", 2), RS("rs", "Right stick", 2),
|
||||
L4("l4", "L4"), R4("r4", "R4"), L5("l5", "L5"), R5("r5", "R5"),
|
||||
LEFT_PAD("left-pad", "Left trackpad", 2), RIGHT_PAD("right-pad", "Right trackpad", 2),
|
||||
LEFT_CLICK("left-click", "Left trackpad click"), RIGHT_CLICK("right-click", "Right trackpad click");
|
||||
|
||||
val isPad: Boolean get() = ordinal <= RS.ordinal
|
||||
val isTrackpad: Boolean get() = this == LEFT_PAD || this == RIGHT_PAD
|
||||
|
||||
companion object {
|
||||
val padControls = entries.filter { it.isPad }.toTypedArray()
|
||||
fun fromId(id: String) = entries.firstOrNull { it.id == id }
|
||||
}
|
||||
}
|
||||
|
||||
enum class InputCommand { MENU, KEYBOARD, STEAM, QUICK_ACCESS }
|
||||
|
||||
sealed interface InputAction {
|
||||
data class Native(val target: InputControl? = null) : InputAction
|
||||
data object Disabled : InputAction
|
||||
data class Keys(val codes: List<Int>) : InputAction
|
||||
data class MouseButton(val code: Int) : InputAction
|
||||
data class Command(val command: InputCommand) : InputAction
|
||||
data class Directions(val up: Int, val right: Int, val down: Int, val left: Int) : InputAction
|
||||
data class Pointer(val speed: Float = 900f) : InputAction
|
||||
data class Scroll(val speed: Float = 10f) : InputAction
|
||||
}
|
||||
|
||||
data class InputProfile(
|
||||
val id: String,
|
||||
val bindings: Map<InputRole, Map<InputControl, InputAction>> = emptyMap(),
|
||||
val keys: List<PhysicalInputBinding> = emptyList(),
|
||||
) {
|
||||
fun action(role: InputRole, control: InputControl): InputAction =
|
||||
bindings[role]?.get(control) ?: InputAction.Native()
|
||||
|
||||
fun withBinding(role: InputRole, control: InputControl, action: InputAction) =
|
||||
copy(bindings = bindings + (role to (bindings[role].orEmpty() + (control to action))))
|
||||
|
||||
companion object {
|
||||
const val GAME = "game"
|
||||
const val DESKTOP = "desktop"
|
||||
|
||||
fun defaults(id: String): InputProfile {
|
||||
if (id != DESKTOP) return InputProfile(GAME)
|
||||
val desktop = mapOf(
|
||||
InputControl.LS to InputAction.Pointer(), InputControl.RS to InputAction.Scroll(),
|
||||
InputControl.A to InputAction.MouseButton(272), InputControl.B to InputAction.MouseButton(273),
|
||||
InputControl.X to InputAction.Keys(listOf(28)), InputControl.Y to InputAction.Keys(listOf(1)),
|
||||
InputControl.UP to InputAction.Keys(listOf(103)), InputControl.RIGHT to InputAction.Keys(listOf(106)),
|
||||
InputControl.DOWN to InputAction.Keys(listOf(108)), InputControl.LEFT to InputAction.Keys(listOf(105)),
|
||||
InputControl.LT to InputAction.MouseButton(273), InputControl.RT to InputAction.MouseButton(272),
|
||||
InputControl.LB to InputAction.Keys(listOf(29)), InputControl.RB to InputAction.Keys(listOf(56)),
|
||||
InputControl.SELECT to InputAction.Command(InputCommand.KEYBOARD),
|
||||
InputControl.START to InputAction.Command(InputCommand.MENU),
|
||||
InputControl.LEFT_PAD to InputAction.Scroll(), InputControl.RIGHT_PAD to InputAction.Pointer(),
|
||||
InputControl.LEFT_CLICK to InputAction.MouseButton(273), InputControl.RIGHT_CLICK to InputAction.MouseButton(272),
|
||||
)
|
||||
return InputProfile(DESKTOP, InputRole.entries.associateWith { desktop })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun InputAction.validFor(control: InputControl): Boolean = when (this) {
|
||||
is InputAction.Native -> target == null || (control.isPad == target.isPad && control.dimensions == target.dimensions &&
|
||||
(!control.isTrackpad && !target.isTrackpad || control.isTrackpad && target.isTrackpad))
|
||||
is InputAction.Keys -> codes.isNotEmpty() && codes.size <= 8 && codes.distinct().size == codes.size && codes.all { it in 1..255 }
|
||||
is InputAction.MouseButton -> code in 272..276
|
||||
is InputAction.Directions -> control.dimensions == 2 && listOf(up, right, down, left).all { it in 1..255 }
|
||||
is InputAction.Pointer -> control.dimensions == 2 && speed.isFinite() && speed in 100f..3000f
|
||||
is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f
|
||||
else -> true
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
object InputProfiles {
|
||||
const val AUTO = "auto"
|
||||
private const val VERSION = 1
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
|
||||
|
||||
fun selection(context: Context): String = prefs(context).getString("selected", AUTO)
|
||||
?.takeIf { it in listOf(AUTO, InputProfile.GAME, InputProfile.DESKTOP) } ?: AUTO
|
||||
|
||||
fun select(context: Context, id: String) {
|
||||
require(id in listOf(AUTO, InputProfile.GAME, InputProfile.DESKTOP))
|
||||
prefs(context).edit().putString("selected", id).apply()
|
||||
}
|
||||
|
||||
fun active(context: Context, desktop: Boolean): InputProfile {
|
||||
val selected = selection(context)
|
||||
return read(context, if (selected != AUTO) selected else if (desktop) InputProfile.DESKTOP else InputProfile.GAME)
|
||||
}
|
||||
|
||||
fun read(context: Context, id: String): InputProfile {
|
||||
migrate(context)
|
||||
var result = InputProfile.defaults(id)
|
||||
val stored = prefs(context).getString("profile.$id", null) ?: return result
|
||||
val document = runCatching { JSONObject(stored) }.getOrNull() ?: return result
|
||||
if (document.optInt("version") != VERSION) return result
|
||||
val bindings = document.optJSONArray("bindings") ?: return result
|
||||
for (i in 0 until minOf(bindings.length(), 256)) {
|
||||
val entry = bindings.optJSONObject(i) ?: continue
|
||||
val role = runCatching { InputRole.valueOf(entry.getString("role")) }.getOrNull() ?: continue
|
||||
val control = InputControl.fromId(entry.optString("control")) ?: continue
|
||||
val action = decode(entry.optJSONObject("action") ?: continue) ?: continue
|
||||
if (action.validFor(control)) result = result.withBinding(role, control, action)
|
||||
}
|
||||
val keys = document.optJSONArray("keys")
|
||||
if (keys != null) result = result.copy(keys = (0 until minOf(keys.length(), 64)).mapNotNull { i ->
|
||||
runCatching {
|
||||
val item = keys.getJSONObject(i)
|
||||
val action = decode(item.getJSONObject("action")) ?: return@mapNotNull null
|
||||
if (!action.validFor(InputControl.A) || action is InputAction.Native && action.target != null) return@mapNotNull null
|
||||
val key = PhysicalInputKey(item.getString("device"), item.getString("name"), item.getInt("keyCode"), item.getInt("scanCode"))
|
||||
if (key.device.isBlank() || key.keyCode < 0 || key.scanCode < 0) return@mapNotNull null
|
||||
PhysicalInputBinding(key, action)
|
||||
}.getOrNull()
|
||||
}.distinctBy { Triple(it.key.device, it.key.keyCode, it.key.scanCode) })
|
||||
return result
|
||||
}
|
||||
|
||||
fun save(context: Context, profile: InputProfile) {
|
||||
val bindings = JSONArray()
|
||||
for ((role, controls) in profile.bindings) for ((control, action) in controls) {
|
||||
require(action.validFor(control))
|
||||
bindings.put(JSONObject().put("role", role.name).put("control", control.id).put("action", encode(action)))
|
||||
}
|
||||
val keys = JSONArray()
|
||||
for (binding in profile.keys) keys.put(JSONObject().put("device", binding.key.device).put("name", binding.key.name)
|
||||
.put("keyCode", binding.key.keyCode).put("scanCode", binding.key.scanCode).put("action", encode(binding.action)))
|
||||
prefs(context).edit().putString("profile.${profile.id}", JSONObject()
|
||||
.put("version", VERSION).put("id", profile.id).put("bindings", bindings).put("keys", keys).toString()).apply()
|
||||
}
|
||||
|
||||
fun reset(context: Context, id: String) { prefs(context).edit().remove("profile.$id").apply() }
|
||||
|
||||
fun resetAll(context: Context) {
|
||||
prefs(context).edit().clear().putBoolean("migrated", true).apply()
|
||||
}
|
||||
|
||||
private fun migrate(context: Context) {
|
||||
val p = prefs(context)
|
||||
if (p.getBoolean("migrated", false)) return
|
||||
var game = InputProfile.defaults(InputProfile.GAME)
|
||||
val old = ControllerPrefs.read(context)
|
||||
for ((id, target) in old.mapping) {
|
||||
val source = InputControl.fromId(id) ?: continue
|
||||
val action = if (target == ControllerPrefs.OFF) InputAction.Disabled
|
||||
else InputAction.Native(InputControl.fromId(target) ?: continue)
|
||||
if (target != id) game = game.withBinding(InputRole.PRIMARY, source, action)
|
||||
}
|
||||
if (old.selectSteam) game = game.withBinding(InputRole.PHYSICAL, InputControl.SELECT, InputAction.Native(InputControl.GUIDE))
|
||||
if (!p.contains("profile.${InputProfile.GAME}")) save(context, game)
|
||||
p.edit().putBoolean("migrated", true).apply()
|
||||
}
|
||||
|
||||
private fun encode(action: InputAction): JSONObject = JSONObject().apply {
|
||||
when (action) {
|
||||
is InputAction.Native -> { put("type", "native"); action.target?.let { put("target", it.id) } }
|
||||
InputAction.Disabled -> put("type", "disabled")
|
||||
is InputAction.Keys -> { put("type", "keys"); put("codes", JSONArray(action.codes)) }
|
||||
is InputAction.MouseButton -> { put("type", "button"); put("code", action.code) }
|
||||
is InputAction.Command -> { put("type", "command"); put("command", action.command.name) }
|
||||
is InputAction.Directions -> { put("type", "directions"); put("codes", JSONArray(listOf(action.up, action.right, action.down, action.left))) }
|
||||
is InputAction.Pointer -> { put("type", "pointer"); put("speed", action.speed.toDouble()) }
|
||||
is InputAction.Scroll -> { put("type", "scroll"); put("speed", action.speed.toDouble()) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun decode(json: JSONObject): InputAction? = runCatching {
|
||||
when (json.getString("type")) {
|
||||
"native" -> InputAction.Native(if (json.has("target")) InputControl.fromId(json.getString("target")) ?: return null else null)
|
||||
"disabled" -> InputAction.Disabled
|
||||
"keys" -> InputAction.Keys(json.getJSONArray("codes").let { a -> (0 until a.length()).map { a.getInt(it) } })
|
||||
"button" -> InputAction.MouseButton(json.getInt("code"))
|
||||
"command" -> InputAction.Command(InputCommand.valueOf(json.getString("command")))
|
||||
"directions" -> json.getJSONArray("codes").let { InputAction.Directions(it.getInt(0), it.getInt(1), it.getInt(2), it.getInt(3)) }
|
||||
"pointer" -> InputAction.Pointer(json.getDouble("speed").toFloat())
|
||||
"scroll" -> InputAction.Scroll(json.getDouble("speed").toFloat())
|
||||
else -> null
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
interface InputOutput {
|
||||
fun key(code: Int, down: Boolean)
|
||||
fun button(code: Int, down: Boolean)
|
||||
fun pointer(dx: Float, dy: Float)
|
||||
fun scroll(steps: Int)
|
||||
fun command(command: InputCommand)
|
||||
fun requestMotion()
|
||||
}
|
||||
|
||||
class InputRouter(private val output: InputOutput) {
|
||||
private val keys = IntArray(256)
|
||||
private val buttons = IntArray(5)
|
||||
private val channels = ArrayList<Channel>()
|
||||
private val pads = ArrayList<PadSource>()
|
||||
private var profile = InputProfile.defaults(InputProfile.GAME)
|
||||
private var moving = false
|
||||
private var wheel = 0f
|
||||
private var enabled = true
|
||||
private val snapshots = ArrayList<() -> Unit>()
|
||||
|
||||
@Synchronized
|
||||
fun beforeProfileChange(snapshot: () -> Unit) { snapshots.add(snapshot) }
|
||||
|
||||
@Synchronized
|
||||
fun removeSnapshot(snapshot: () -> Unit) { snapshots.remove(snapshot) }
|
||||
|
||||
@Synchronized
|
||||
fun setEnabled(on: Boolean) {
|
||||
if (enabled == on) return
|
||||
if (!on) releaseAll()
|
||||
enabled = on
|
||||
for (pad in pads) pad.refreshIdentity()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setProfile(next: InputProfile) {
|
||||
if (profile == next) return
|
||||
for (snapshot in snapshots) snapshot()
|
||||
for (pad in pads) pad.snapshot()
|
||||
profile = next
|
||||
for (channel in channels) channel.configure(next.action(channel.role, channel.control))
|
||||
for (pad in pads) pad.refreshIdentity()
|
||||
wheel = 0f
|
||||
moving = false
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun pad(role: InputRole): PadSource = PadSource(role).also { pads.add(it) }
|
||||
|
||||
@Synchronized
|
||||
fun channel(role: InputRole, control: InputControl, fixedAction: InputAction? = null): Channel = Channel(role, control, fixedAction).also {
|
||||
channels.add(it)
|
||||
it.configure(profile.action(role, control))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun releaseAll() {
|
||||
for (snapshot in snapshots) snapshot()
|
||||
for (pad in pads) pad.snapshot()
|
||||
for (channel in channels) channel.suspend()
|
||||
for (pad in pads) pad.refreshIdentity()
|
||||
wheel = 0f
|
||||
moving = false
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun tick(seconds: Float): Boolean {
|
||||
if (!enabled) return false
|
||||
var x = 0f
|
||||
var y = 0f
|
||||
var scroll = 0f
|
||||
for (channel in channels) {
|
||||
if (channel.blocked || channel.control.isTrackpad) continue
|
||||
val cx = if (abs(channel.x) > 0.12f) channel.x else 0f
|
||||
val cy = if (abs(channel.y) > 0.12f) channel.y else 0f
|
||||
when (val action = channel.action) {
|
||||
is InputAction.Pointer -> { x += cx * action.speed; y += cy * action.speed }
|
||||
is InputAction.Scroll -> scroll -= cy * action.speed
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
val dt = seconds.coerceIn(0f, 0.05f)
|
||||
if (x != 0f || y != 0f) output.pointer(x * dt, y * dt)
|
||||
wheel += scroll * dt
|
||||
flushWheel()
|
||||
moving = x != 0f || y != 0f || scroll != 0f
|
||||
return moving
|
||||
}
|
||||
|
||||
private fun flushWheel() {
|
||||
val steps = wheel.toInt()
|
||||
if (steps != 0) { wheel -= steps; output.scroll(steps) }
|
||||
}
|
||||
|
||||
private fun key(code: Int, down: Boolean) {
|
||||
val was = keys[code]
|
||||
keys[code] = (was + if (down) 1 else -1).coerceAtLeast(0)
|
||||
if ((was == 0) != (keys[code] == 0)) output.key(code, down)
|
||||
}
|
||||
|
||||
private fun button(code: Int, down: Boolean) {
|
||||
val at = code - 272
|
||||
val was = buttons[at]
|
||||
buttons[at] = (was + if (down) 1 else -1).coerceAtLeast(0)
|
||||
if ((was == 0) != (buttons[at] == 0)) output.button(code, down)
|
||||
}
|
||||
|
||||
inner class Channel internal constructor(val role: InputRole, val control: InputControl, private val fixedAction: InputAction?) {
|
||||
var action: InputAction = InputAction.Native()
|
||||
private set
|
||||
internal var x = 0f
|
||||
internal var y = 0f
|
||||
internal var contact = false
|
||||
internal var blocked = false
|
||||
private var held = false
|
||||
private val directions = BooleanArray(4)
|
||||
|
||||
internal fun configure(next: InputAction) {
|
||||
suspend()
|
||||
action = (fixedAction ?: next).takeIf { it.validFor(control) } ?: InputAction.Native()
|
||||
}
|
||||
|
||||
internal fun observe(value: Float, second: Float = 0f, touching: Boolean = false) {
|
||||
x = value; y = second; contact = touching
|
||||
}
|
||||
|
||||
internal fun nativeIdentity(): Boolean = enabled && !blocked && (action as? InputAction.Native)?.target == null && action is InputAction.Native
|
||||
|
||||
internal fun suspend() {
|
||||
releaseOutputs()
|
||||
blocked = contact || abs(x) > 0.12f || abs(y) > 0.12f
|
||||
}
|
||||
|
||||
fun release() = synchronized(this@InputRouter) {
|
||||
releaseOutputs()
|
||||
x = 0f; y = 0f; contact = false; blocked = false
|
||||
}
|
||||
|
||||
fun close() = synchronized(this@InputRouter) {
|
||||
release()
|
||||
channels.remove(this)
|
||||
}
|
||||
|
||||
fun update(value: Float, second: Float = 0f, touching: Boolean = false): InputControl? = synchronized(this@InputRouter) {
|
||||
val oldX = x
|
||||
val oldY = y
|
||||
val oldContact = contact
|
||||
x = value.coerceIn(-1f, 1f)
|
||||
y = second.coerceIn(-1f, 1f)
|
||||
contact = touching
|
||||
if (!enabled) {
|
||||
blocked = contact || abs(x) > 0.12f || abs(y) > 0.12f
|
||||
return@synchronized null
|
||||
}
|
||||
if (blocked) {
|
||||
if (!contact && abs(x) <= 0.12f && abs(y) <= 0.12f) blocked = false
|
||||
return@synchronized null
|
||||
}
|
||||
when (val a = action) {
|
||||
is InputAction.Native -> return@synchronized a.target ?: control
|
||||
is InputAction.Disabled -> Unit
|
||||
is InputAction.Pointer -> {
|
||||
if (control.isTrackpad) {
|
||||
if (contact && oldContact) output.pointer((x - oldX) * a.speed, -(y - oldY) * a.speed)
|
||||
} else requestMotion()
|
||||
}
|
||||
is InputAction.Scroll -> {
|
||||
if (control.isTrackpad) {
|
||||
if (contact && oldContact) { wheel += (y - oldY) * a.speed; flushWheel() }
|
||||
} else requestMotion()
|
||||
}
|
||||
is InputAction.Directions -> {
|
||||
val vertical = if (control.isTrackpad) -y else y
|
||||
direction(0, -vertical, a.up); direction(1, x, a.right)
|
||||
direction(2, vertical, a.down); direction(3, -x, a.left)
|
||||
}
|
||||
else -> {
|
||||
val down = if (control.isTrackpad) contact else maxOf(abs(x), abs(y)) > if (held) 0.35f else 0.55f
|
||||
if (held != down) {
|
||||
held = down
|
||||
when (a) {
|
||||
is InputAction.Keys -> if (down) a.codes.forEach { key(it, true) } else a.codes.asReversed().forEach { key(it, false) }
|
||||
is InputAction.MouseButton -> button(a.code, down)
|
||||
is InputAction.Command -> if (down) output.command(a.command)
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
null
|
||||
}
|
||||
|
||||
private fun requestMotion() {
|
||||
if (!moving && (abs(x) > 0.12f || abs(y) > 0.12f)) { moving = true; output.requestMotion() }
|
||||
}
|
||||
|
||||
private fun direction(at: Int, value: Float, code: Int) {
|
||||
val down = value > if (directions[at]) 0.35f else 0.55f
|
||||
if (directions[at] != down) { directions[at] = down; key(code, down) }
|
||||
}
|
||||
|
||||
private fun releaseOutputs() {
|
||||
when (val a = action) {
|
||||
is InputAction.Keys -> if (held) a.codes.asReversed().forEach { key(it, false) }
|
||||
is InputAction.MouseButton -> if (held) button(a.code, false)
|
||||
is InputAction.Directions -> {
|
||||
val codes = intArrayOf(a.up, a.right, a.down, a.left)
|
||||
for (i in directions.indices) if (directions[i]) key(codes[i], false)
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
held = false
|
||||
directions.fill(false)
|
||||
}
|
||||
}
|
||||
|
||||
inner class PadSource internal constructor(role: InputRole) {
|
||||
private val routes = Array(InputControl.padControls.size) { channel(role, InputControl.padControls[it]) }
|
||||
private val result = PadState()
|
||||
private var last: PadState? = null
|
||||
private var identity = true
|
||||
private var nativeCandidate = true
|
||||
|
||||
init { refreshIdentity() }
|
||||
|
||||
internal fun refreshIdentity() {
|
||||
nativeCandidate = routes.all { (it.action as? InputAction.Native)?.target == null && it.action is InputAction.Native }
|
||||
identity = enabled && nativeCandidate && routes.none { it.blocked }
|
||||
}
|
||||
|
||||
internal fun snapshot() {
|
||||
val raw = last ?: return
|
||||
for (route in routes) {
|
||||
route.x = raw.value(route.control)
|
||||
route.y = raw.secondValue(route.control)
|
||||
}
|
||||
}
|
||||
|
||||
fun route(raw: PadState): PadState = synchronized(this@InputRouter) {
|
||||
last = raw
|
||||
if (identity) return@synchronized raw
|
||||
result.clear()
|
||||
for (route in routes) {
|
||||
val x = raw.value(route.control)
|
||||
val y = raw.secondValue(route.control)
|
||||
val target = route.update(x, y) ?: continue
|
||||
result.add(target, x, y)
|
||||
}
|
||||
if (nativeCandidate && enabled && routes.none { it.blocked }) identity = true
|
||||
result
|
||||
}
|
||||
|
||||
fun release() = synchronized(this@InputRouter) {
|
||||
for (route in routes) route.release()
|
||||
last = null
|
||||
result.clear()
|
||||
refreshIdentity()
|
||||
}
|
||||
|
||||
fun close() = synchronized(this@InputRouter) {
|
||||
release()
|
||||
for (route in routes) route.close()
|
||||
pads.remove(this)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val padButtons = intArrayOf(PadState.A, PadState.B, PadState.X, PadState.Y, PadState.LB, PadState.RB,
|
||||
PadState.SELECT, PadState.START, PadState.L3, PadState.R3, PadState.GUIDE, PadState.QAM)
|
||||
|
||||
internal fun PadState.value(control: InputControl): Float = when (control) {
|
||||
InputControl.UP -> if (up) 1f else 0f
|
||||
InputControl.RIGHT -> if (right) 1f else 0f
|
||||
InputControl.DOWN -> if (down) 1f else 0f
|
||||
InputControl.LEFT -> if (left) 1f else 0f
|
||||
InputControl.LT -> leftTrigger
|
||||
InputControl.RT -> rightTrigger
|
||||
InputControl.LS -> leftX
|
||||
InputControl.RS -> rightX
|
||||
else -> if (control.ordinal < padButtons.size && isDown(padButtons[control.ordinal])) 1f else 0f
|
||||
}
|
||||
|
||||
internal fun PadState.secondValue(control: InputControl): Float = when (control) {
|
||||
InputControl.LS -> leftY
|
||||
InputControl.RS -> rightY
|
||||
else -> 0f
|
||||
}
|
||||
|
||||
internal fun PadState.add(control: InputControl, x: Float, y: Float = 0f) {
|
||||
when (control) {
|
||||
InputControl.UP -> up = up || x > 0.5f
|
||||
InputControl.RIGHT -> right = right || x > 0.5f
|
||||
InputControl.DOWN -> down = down || x > 0.5f
|
||||
InputControl.LEFT -> left = left || x > 0.5f
|
||||
InputControl.LT -> leftTrigger = maxOf(leftTrigger, x)
|
||||
InputControl.RT -> rightTrigger = maxOf(rightTrigger, x)
|
||||
InputControl.LS -> if (x * x + y * y > leftX * leftX + leftY * leftY) { leftX = x; leftY = y }
|
||||
InputControl.RS -> if (x * x + y * y > rightX * rightX + rightY * rightY) { rightX = x; rightY = y }
|
||||
else -> if (control.ordinal < padButtons.size && x > 0.5f) press(padButtons[control.ordinal], true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
data class InputSurfaceElement(val control: InputControl, val x: Float, val y: Float, val width: Float, val height: Float) {
|
||||
fun bounded() = copy(x = x.coerceIn(0f, 0.9f), y = y.coerceIn(0f, 0.9f),
|
||||
width = width.coerceIn(0.1f, 1f - x.coerceIn(0f, 0.9f)), height = height.coerceIn(0.1f, 1f - y.coerceIn(0f, 0.9f)))
|
||||
}
|
||||
|
||||
object InputSurfaceLayout {
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("input-surfaces", Context.MODE_PRIVATE)
|
||||
|
||||
fun defaults() = listOf(
|
||||
InputSurfaceElement(InputControl.LEFT_PAD, 0.02f, 0.02f, 0.46f, 0.65f),
|
||||
InputSurfaceElement(InputControl.RIGHT_PAD, 0.52f, 0.02f, 0.46f, 0.65f),
|
||||
InputSurfaceElement(InputControl.A, 0.02f, 0.72f, 0.20f, 0.25f),
|
||||
InputSurfaceElement(InputControl.B, 0.26f, 0.72f, 0.20f, 0.25f),
|
||||
InputSurfaceElement(InputControl.SELECT, 0.52f, 0.72f, 0.20f, 0.25f),
|
||||
InputSurfaceElement(InputControl.START, 0.76f, 0.72f, 0.22f, 0.25f),
|
||||
)
|
||||
|
||||
fun read(context: Context, profile: String): List<InputSurfaceElement> {
|
||||
val text = prefs(context).getString(profile, null) ?: return defaults()
|
||||
return runCatching {
|
||||
val doc = JSONObject(text)
|
||||
require(doc.getInt("version") == 1)
|
||||
val elements = doc.getJSONArray("elements")
|
||||
(0 until minOf(elements.length(), 28)).mapNotNull { i ->
|
||||
val item = elements.optJSONObject(i) ?: return@mapNotNull null
|
||||
val control = InputControl.fromId(item.optString("control")) ?: return@mapNotNull null
|
||||
val values = listOf("x", "y", "w", "h").map { item.optDouble(it, Double.NaN).toFloat() }
|
||||
if (values.any { !it.isFinite() }) return@mapNotNull null
|
||||
InputSurfaceElement(control, values[0], values[1], values[2], values[3]).bounded()
|
||||
}.distinctBy { it.control }
|
||||
}.getOrElse { defaults() }
|
||||
}
|
||||
|
||||
fun save(context: Context, profile: String, layout: List<InputSurfaceElement>) {
|
||||
val array = JSONArray()
|
||||
for (element in layout.distinctBy { it.control }.take(28)) {
|
||||
val e = element.bounded()
|
||||
array.put(JSONObject().put("control", e.control.id).put("x", e.x.toDouble()).put("y", e.y.toDouble())
|
||||
.put("w", e.width.toDouble()).put("h", e.height.toDouble()))
|
||||
}
|
||||
prefs(context).edit().putString(profile, JSONObject().put("version", 1).put("elements", array).toString()).apply()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import java.util.Locale
|
||||
|
||||
object InputTiming {
|
||||
@JvmField @Volatile var enabled = false
|
||||
private val samples = LongArray(4096)
|
||||
private var count = 0L
|
||||
private var next = 0
|
||||
|
||||
@JvmStatic fun begin(): Long = if (enabled) System.nanoTime() else 0L
|
||||
|
||||
@JvmStatic fun end(start: Long) {
|
||||
if (start == 0L) return
|
||||
val elapsed = System.nanoTime() - start
|
||||
synchronized(this) {
|
||||
samples[next] = elapsed
|
||||
next = (next + 1) % samples.size
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized fun reset() { count = 0; next = 0; samples.fill(0) }
|
||||
|
||||
@Synchronized fun report(): String {
|
||||
val size = minOf(count, samples.size.toLong()).toInt()
|
||||
if (size == 0) return "No input samples"
|
||||
val values = samples.copyOf(size).sortedArray()
|
||||
fun percentile(p: Double) = values[((size - 1) * p).toInt()] / 1000.0
|
||||
return String.format(Locale.ROOT, "Dispatch to publication (µs): p50 %.1f, p95 %.1f, p99 %.1f; %d samples, last %d retained",
|
||||
percentile(.5), percentile(.95), percentile(.99), count, size)
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,7 @@ class OnScreenControls(
|
||||
}
|
||||
|
||||
private fun applySettings() {
|
||||
for (control in controls) control.target = settings.mapping[control.id] ?: control.id
|
||||
for (control in controls) control.target = if (pad?.hasInputRouter() == true) control.id else settings.mapping[control.id] ?: control.id
|
||||
val tint = settings.tint
|
||||
val alpha = settings.opacity / 100f
|
||||
fun shade(a: Int, f: Float) = Color.argb((a * alpha).toInt(), (Color.red(tint) * f).toInt(), (Color.green(tint) * f).toInt(), (Color.blue(tint) * f).toInt())
|
||||
@@ -210,6 +210,7 @@ class OnScreenControls(
|
||||
|
||||
override fun onDetachedFromWindow() {
|
||||
releaseAll()
|
||||
pad?.releaseTouch(this)
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
|
||||
@@ -673,12 +674,27 @@ class OnScreenControls(
|
||||
private fun apply() {
|
||||
val bridge = pad
|
||||
if (bridge == null || editing) { invalidate(); return }
|
||||
if (bridge.hasInputRouter()) {
|
||||
bridge.applyTouch(this, InputRole.PRIMARY) { state ->
|
||||
state.clear()
|
||||
for (control in controls) {
|
||||
if (!isVisible(control)) continue
|
||||
if (control.stick >= 0) {
|
||||
if (control.stick == 0) { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius }
|
||||
else { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius }
|
||||
if (settings.stickClick) state.press(if (control.stick == 0) PadState.L3 else PadState.R3, control.clicked)
|
||||
} else write(state, control.id, control.pressedBy != -1)
|
||||
}
|
||||
}
|
||||
invalidate()
|
||||
return
|
||||
}
|
||||
val qamHeld = controls.any { it.id == "qam" && it.pressedBy != -1 }
|
||||
if (buttonsOnly) {
|
||||
bridge.setSystemButtons(controls.any { it.id == "guide" && it.pressedBy != -1 }, qamHeld)
|
||||
} else {
|
||||
bridge.setSystemButtons(false, qamHeld)
|
||||
bridge.applyTouch { state ->
|
||||
bridge.applyTouch(this, InputRole.PRIMARY) { state ->
|
||||
val used = HashSet<String>()
|
||||
val held = HashSet<String>()
|
||||
for (control in controls) {
|
||||
@@ -718,6 +734,7 @@ class OnScreenControls(
|
||||
"l3" -> state.press(PadState.L3, down)
|
||||
"r3" -> state.press(PadState.R3, down)
|
||||
"guide" -> state.press(PadState.GUIDE, down)
|
||||
"qam" -> state.press(PadState.QAM, down)
|
||||
"lt" -> state.leftTrigger = if (down) 1f else 0f
|
||||
"rt" -> state.rightTrigger = if (down) 1f else 0f
|
||||
"up" -> state.up = down
|
||||
|
||||
@@ -52,6 +52,19 @@ public final class PadBridge {
|
||||
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
|
||||
private final PadState[] playerStates = new PadState[SLOTS];
|
||||
private final PadState effectiveState = new PadState();
|
||||
private final PadState combinedState = new PadState();
|
||||
private InputRouter inputRouter;
|
||||
private final InputRouter.PadSource[] physicalRoutes = new InputRouter.PadSource[SLOTS];
|
||||
private final java.util.IdentityHashMap<Object, TouchSource> touchSources = new java.util.IdentityHashMap<>();
|
||||
private final Object defaultTouchSource = new Object();
|
||||
|
||||
private static final class TouchSource {
|
||||
final PadState raw = new PadState();
|
||||
final PadState passthrough = new PadState();
|
||||
final InputRole role;
|
||||
InputRouter.PadSource route;
|
||||
TouchSource(InputRole role) { this.role = role; }
|
||||
}
|
||||
private final Handler mainHandler = new Handler(Looper.getMainLooper());
|
||||
private boolean open;
|
||||
private volatile boolean selectSteam;
|
||||
@@ -64,6 +77,9 @@ public final class PadBridge {
|
||||
private int chordButton = -1;
|
||||
private boolean chordButtonPressed;
|
||||
private boolean qamTapPressed;
|
||||
private boolean guideTapPressed;
|
||||
private int guideTapGeneration;
|
||||
private boolean routedQamPressed;
|
||||
private int qamChordGeneration;
|
||||
private volatile Runnable onPlayerInput;
|
||||
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
|
||||
@@ -107,6 +123,32 @@ public final class PadBridge {
|
||||
selectSteam = on;
|
||||
}
|
||||
|
||||
public synchronized void setInputRouter(InputRouter router) {
|
||||
if (inputRouter == router) return;
|
||||
for (InputRouter.PadSource route : physicalRoutes) if (route != null) route.close();
|
||||
for (TouchSource source : touchSources.values()) if (source.route != null) source.route.close();
|
||||
inputRouter = router;
|
||||
for (int slot = 0; slot < SLOTS; slot++) physicalRoutes[slot] = router == null ? null : router.pad(InputRole.PHYSICAL);
|
||||
for (TouchSource source : touchSources.values()) source.route = router == null ? null : router.pad(source.role);
|
||||
}
|
||||
|
||||
public synchronized boolean hasInputRouter() { return inputRouter != null; }
|
||||
|
||||
public synchronized void setInputProfile(InputProfile profile) {
|
||||
if (inputRouter == null) return;
|
||||
inputRouter.setProfile(profile);
|
||||
publish();
|
||||
for (int slot = 1; slot < SLOTS; slot++) if (playerWriters[slot] != null) publish(slot);
|
||||
}
|
||||
|
||||
public synchronized void setInputEnabled(boolean enabled) {
|
||||
if (inputRouter == null) return;
|
||||
inputRouter.setEnabled(enabled);
|
||||
publish();
|
||||
for (int slot = 1; slot < SLOTS; slot++) if (playerWriters[slot] != null) publish(slot);
|
||||
DeckControls.INSTANCE.refresh();
|
||||
}
|
||||
|
||||
public void setExcluded(java.util.function.IntPredicate devices) {
|
||||
excluded = devices;
|
||||
}
|
||||
@@ -129,9 +171,15 @@ public final class PadBridge {
|
||||
|
||||
private void resetBuiltin() {
|
||||
routedTouch.clear();
|
||||
for (TouchSource source : touchSources.values()) {
|
||||
source.raw.clear();
|
||||
if (source.route != null) source.route.release();
|
||||
}
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
qamTapPressed = false;
|
||||
guideTapPressed = false;
|
||||
guideTapGeneration++;
|
||||
qamChordActive = false;
|
||||
chordButtonPressed = false;
|
||||
qamChordGeneration++;
|
||||
@@ -149,6 +197,14 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void stop() {
|
||||
guideTapPressed = false;
|
||||
guideTapGeneration++;
|
||||
if (inputRouter != null) inputRouter.releaseAll();
|
||||
for (TouchSource source : touchSources.values()) if (source.route != null) source.route.close();
|
||||
touchSources.clear();
|
||||
for (InputRouter.PadSource route : physicalRoutes) if (route != null) route.close();
|
||||
Arrays.fill(physicalRoutes, null);
|
||||
inputRouter = null;
|
||||
releaseBackPaddles();
|
||||
activeControllerId = NO_CONTROLLER;
|
||||
for (int slot = 0; slot < SLOTS; slot++) {
|
||||
@@ -287,6 +343,7 @@ public final class PadBridge {
|
||||
if (slot < 0) return false;
|
||||
int side = JoyCon.side(event.getDevice());
|
||||
if (side >= 0 && partners[slot] != NO_CONTROLLER && JoyCon.isRail(side, event.getScanCode())) return true;
|
||||
long timing = InputTiming.begin();
|
||||
PadState pad = stateFor(slot);
|
||||
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
|
||||
switch (event.getKeyCode()) {
|
||||
@@ -297,7 +354,7 @@ 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:
|
||||
if (selectSteam) pad.press(PadState.GUIDE, pressed);
|
||||
if (selectSteam && inputRouter == null) pad.press(PadState.GUIDE, pressed);
|
||||
else pad.press(6, pressed);
|
||||
break;
|
||||
case KeyEvent.KEYCODE_BACK: pad.press(6, pressed); break;
|
||||
@@ -326,6 +383,7 @@ public final class PadBridge {
|
||||
statButtons++;
|
||||
scheduleStats();
|
||||
publish(slot);
|
||||
InputTiming.end(timing);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -334,6 +392,7 @@ public final class PadBridge {
|
||||
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
|
||||
int slot = slotFor(event.getDevice());
|
||||
if (slot < 0) return false;
|
||||
long timing = InputTiming.begin();
|
||||
PadState pad = stateFor(slot);
|
||||
noteDevice(event.getDevice(), slot);
|
||||
statAxes++;
|
||||
@@ -353,6 +412,7 @@ public final class PadBridge {
|
||||
}
|
||||
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
|
||||
publish(slot);
|
||||
InputTiming.end(timing);
|
||||
return true;
|
||||
}
|
||||
pad.leftX = axis(event, MotionEvent.AXIS_X);
|
||||
@@ -386,6 +446,7 @@ public final class PadBridge {
|
||||
notePlayerInput();
|
||||
}
|
||||
publish(slot);
|
||||
InputTiming.end(timing);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -407,32 +468,33 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void applyTouch(java.util.function.Consumer<PadState> mutation) {
|
||||
applyTouch(defaultTouchSource, InputRole.PRIMARY, mutation);
|
||||
}
|
||||
|
||||
public synchronized void applyTouch(Object owner, InputRole role, java.util.function.Consumer<PadState> mutation) {
|
||||
if (!builtinPad) return;
|
||||
if (touchRoute != null && touchRoute.active()) {
|
||||
mutation.accept(routedTouch);
|
||||
touchRoute.accept(routedTouch);
|
||||
boolean changed = false;
|
||||
for (int button : ROUTED_PASS_THROUGH) {
|
||||
boolean down = routedTouch.isDown(button);
|
||||
if (state.isDown(button) == down) continue;
|
||||
state.press(button, down);
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
activeControllerId = NO_CONTROLLER;
|
||||
slotControllers.set(0, NO_CONTROLLER);
|
||||
publish();
|
||||
}
|
||||
return;
|
||||
long timing = InputTiming.begin();
|
||||
TouchSource source = touchSources.get(owner);
|
||||
if (source == null) {
|
||||
source = new TouchSource(role);
|
||||
if (inputRouter != null) source.route = inputRouter.pad(role);
|
||||
touchSources.put(owner, source);
|
||||
}
|
||||
routedTouch.clear();
|
||||
mutation.accept(state);
|
||||
mutation.accept(source.raw);
|
||||
activeControllerId = NO_CONTROLLER;
|
||||
slotControllers.set(0, NO_CONTROLLER);
|
||||
notePlayerInput();
|
||||
statOnScreen++;
|
||||
scheduleStats();
|
||||
publish();
|
||||
InputTiming.end(timing);
|
||||
}
|
||||
|
||||
public synchronized void releaseTouch(Object owner) {
|
||||
TouchSource source = touchSources.remove(owner);
|
||||
if (source == null) return;
|
||||
if (source.route != null) source.route.close();
|
||||
publish();
|
||||
}
|
||||
|
||||
public synchronized void applyExternal(java.util.function.Consumer<PadState> mutation, boolean changed) {
|
||||
@@ -457,13 +519,24 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
public synchronized void releaseAll() {
|
||||
guideTapGeneration++;
|
||||
routedQamPressed = false;
|
||||
systemGuidePressed = false;
|
||||
systemQamPressed = false;
|
||||
guideTapPressed = false;
|
||||
qamTapPressed = false;
|
||||
qamChordActive = false;
|
||||
chordButtonPressed = false;
|
||||
qamChordGeneration++;
|
||||
if (inputRouter != null) inputRouter.releaseAll();
|
||||
if (inputRouter == null) for (TouchSource source : touchSources.values()) source.raw.clear();
|
||||
routedTouch.clear();
|
||||
releaseBackPaddles();
|
||||
state.clear();
|
||||
DeckControls.INSTANCE.suspend();
|
||||
if (inputRouter == null) state.clear();
|
||||
publish();
|
||||
for (int slot = 1; slot < SLOTS; slot++) {
|
||||
if (playerWriters[slot] == null) continue;
|
||||
playerStates[slot].clear();
|
||||
if (inputRouter == null) playerStates[slot].clear();
|
||||
publish(slot);
|
||||
}
|
||||
}
|
||||
@@ -491,6 +564,20 @@ public final class PadBridge {
|
||||
chordHandler.postDelayed(() -> releaseQamTap(generation), QAM_A_HOLD_MS);
|
||||
}
|
||||
|
||||
public synchronized void triggerSteamMenu() {
|
||||
if (!builtinPad || guideTapPressed) return;
|
||||
guideTapPressed = true;
|
||||
int generation = ++guideTapGeneration;
|
||||
publish();
|
||||
chordHandler.postDelayed(() -> {
|
||||
synchronized (PadBridge.this) {
|
||||
if (generation != guideTapGeneration) return;
|
||||
guideTapPressed = false;
|
||||
publish();
|
||||
}
|
||||
}, 90);
|
||||
}
|
||||
|
||||
private synchronized void releaseQamTap(int generation) {
|
||||
if (generation != qamChordGeneration || !qamTapPressed) return;
|
||||
qamTapPressed = false;
|
||||
@@ -606,6 +693,7 @@ public final class PadBridge {
|
||||
}
|
||||
|
||||
private void free(int slot) {
|
||||
if (physicalRoutes[slot] != null) physicalRoutes[slot].release();
|
||||
Log.i(TAG, "player " + (slot + 1) + " (id " + owners[slot] + ") left");
|
||||
owners[slot] = NO_CONTROLLER;
|
||||
partners[slot] = NO_CONTROLLER;
|
||||
@@ -658,6 +746,7 @@ public final class PadBridge {
|
||||
publish();
|
||||
return;
|
||||
}
|
||||
PadState output = physicalRoutes[slot] == null ? playerStates[slot] : physicalRoutes[slot].route(playerStates[slot]);
|
||||
FakeInputWriter player = playerWriters[slot];
|
||||
if (player == null) {
|
||||
player = new FakeInputWriter(fakeInputDir.getAbsolutePath(), slot);
|
||||
@@ -667,22 +756,47 @@ public final class PadBridge {
|
||||
}
|
||||
playerWriters[slot] = player;
|
||||
}
|
||||
player.writePad(playerStates[slot]);
|
||||
player.writePad(output);
|
||||
}
|
||||
|
||||
private void publish() {
|
||||
if (!builtinPad && !open && owners[0] == NO_CONTROLLER && partners[0] == NO_CONTROLLER) return;
|
||||
PadState output = physicalRoutes[0] == null ? state : physicalRoutes[0].route(state);
|
||||
if (!touchSources.isEmpty()) {
|
||||
combinedState.copyFrom(output);
|
||||
routedTouch.clear();
|
||||
boolean epic = touchRoute != null && touchRoute.active();
|
||||
for (TouchSource source : touchSources.values()) {
|
||||
PadState touch = source.route == null ? source.raw : source.route.route(source.raw);
|
||||
if (epic) {
|
||||
routedTouch.merge(touch);
|
||||
source.passthrough.clear();
|
||||
for (int button : ROUTED_PASS_THROUGH) source.passthrough.press(button, touch.isDown(button));
|
||||
combinedState.merge(source.passthrough);
|
||||
} else combinedState.merge(touch);
|
||||
}
|
||||
if (epic) touchRoute.accept(routedTouch);
|
||||
output = combinedState;
|
||||
}
|
||||
boolean guide = systemGuidePressed || qamChordActive || guideTapPressed;
|
||||
boolean routedQam = output.isDown(PadState.QAM);
|
||||
boolean routedQamStarted = routedQam && !routedQamPressed;
|
||||
routedQamPressed = routedQam;
|
||||
if (routedQamStarted && !nativeQam()) {
|
||||
startChord(PadState.A);
|
||||
return;
|
||||
}
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed);
|
||||
if (!open && !start()) {
|
||||
statDropped++;
|
||||
return;
|
||||
}
|
||||
boolean guide = systemGuidePressed || qamChordActive;
|
||||
boolean qam = nativeQam() && (systemQamPressed || qamTapPressed);
|
||||
if (!guide && !qam) {
|
||||
writer.writePad(state);
|
||||
if (!guide && !qam && (!routedQam || nativeQam())) {
|
||||
writer.writePad(output);
|
||||
return;
|
||||
}
|
||||
effectiveState.copyFrom(state);
|
||||
effectiveState.copyFrom(output);
|
||||
if (!nativeQam()) effectiveState.press(PadState.QAM, false);
|
||||
if (guide) effectiveState.press(PadState.GUIDE, true);
|
||||
if (qam) effectiveState.press(PadState.QAM, true);
|
||||
if (chordButtonPressed) effectiveState.press(chordButton, true);
|
||||
|
||||
@@ -36,6 +36,19 @@ class PadState {
|
||||
buttons = 0
|
||||
}
|
||||
|
||||
fun merge(other: PadState) {
|
||||
buttons = buttons or other.buttons
|
||||
up = up || other.up; right = right || other.right; down = down || other.down; left = left || other.left
|
||||
leftTrigger = maxOf(leftTrigger, other.leftTrigger)
|
||||
rightTrigger = maxOf(rightTrigger, other.rightTrigger)
|
||||
if (other.leftX * other.leftX + other.leftY * other.leftY > leftX * leftX + leftY * leftY) {
|
||||
leftX = other.leftX; leftY = other.leftY
|
||||
}
|
||||
if (other.rightX * other.rightX + other.rightY * other.rightY > rightX * rightX + rightY * rightY) {
|
||||
rightX = other.rightX; rightY = other.rightY
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val A = 0
|
||||
const val B = 1
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import androidx.annotation.StringRes
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
data class PcKey(
|
||||
val label: String,
|
||||
val code: Int,
|
||||
val weight: Float = 1f,
|
||||
val shifted: String? = null,
|
||||
@StringRes val labelRes: Int = 0,
|
||||
)
|
||||
|
||||
internal fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted)
|
||||
|
||||
internal fun k(@StringRes labelRes: Int, code: Int, weight: Float = 1f) = PcKey("", code, weight, null, labelRes)
|
||||
|
||||
val PC_KEY_ROWS: List<List<PcKey>> = listOf(
|
||||
listOf(
|
||||
k(R.string.pckb_key_esc, 1), k("F1", 59), k("F2", 60), k("F3", 61), k("F4", 62), k("F5", 63), k("F6", 64),
|
||||
k("F7", 65), k("F8", 66), k("F9", 67), k("F10", 68), k("F11", 87), k("F12", 88),
|
||||
k(R.string.pckb_key_ins, 110), k(R.string.pckb_key_del, 111), k(R.string.pckb_key_home, 102), k(R.string.pckb_key_end, 107), k(R.string.pckb_key_pgup, 104), k(R.string.pckb_key_pgdn, 109),
|
||||
),
|
||||
listOf(
|
||||
k("`", 41, shifted = "~"), k("1", 2, shifted = "!"), k("2", 3, shifted = "@"), k("3", 4, shifted = "#"),
|
||||
k("4", 5, shifted = "$"), k("5", 6, shifted = "%"), k("6", 7, shifted = "^"), k("7", 8, shifted = "&"),
|
||||
k("8", 9, shifted = "*"), k("9", 10, shifted = "("), k("0", 11, shifted = ")"), k("-", 12, shifted = "_"),
|
||||
k("=", 13, shifted = "+"), k(R.string.pckb_key_backspace, 14, 2f),
|
||||
),
|
||||
listOf(
|
||||
k(R.string.pckb_key_tab, 15, 1.5f), k("q", 16), k("w", 17), k("e", 18), k("r", 19), k("t", 20), k("y", 21),
|
||||
k("u", 22), k("i", 23), k("o", 24), k("p", 25), k("[", 26, shifted = "{"), k("]", 27, shifted = "}"),
|
||||
k("\\", 43, 1.5f, shifted = "|"),
|
||||
),
|
||||
listOf(
|
||||
k(R.string.pckb_key_caps, 58, 1.75f), k("a", 30), k("s", 31), k("d", 32), k("f", 33), k("g", 34), k("h", 35),
|
||||
k("j", 36), k("k", 37), k("l", 38), k(";", 39, shifted = ":"), k("'", 40, shifted = "\""),
|
||||
k(R.string.pckb_key_enter, 28, 2.25f),
|
||||
),
|
||||
listOf(
|
||||
k(R.string.pckb_key_shift, 42, 2.25f), k("z", 44), k("x", 45), k("c", 46), k("v", 47), k("b", 48), k("n", 49),
|
||||
k("m", 50), k(",", 51, shifted = "<"), k(".", 52, shifted = ">"), k("/", 53, shifted = "?"),
|
||||
k(R.string.pckb_key_shift, 54, 1.75f), k("↑", 103),
|
||||
),
|
||||
listOf(
|
||||
k(R.string.pckb_key_ctrl, 29, 1.5f), k(R.string.pckb_key_super, 125, 1.25f), k(R.string.pckb_key_alt, 56, 1.25f), k(R.string.pckb_key_space, 57, 6.25f),
|
||||
k(R.string.pckb_key_altgr, 100, 1.25f), k(R.string.pckb_key_ctrl, 97, 1.25f), k("←", 105), k("↓", 108), k("→", 106),
|
||||
),
|
||||
)
|
||||
|
||||
val PC_MODIFIERS: Set<Int> = setOf(42, 54, 29, 97, 56, 100, 125)
|
||||
|
||||
val PC_KEYS: Map<Int, PcKey> = PC_KEY_ROWS.flatten().associateBy { it.code }
|
||||
|
||||
fun pcKeyLabel(context: Context, code: Int): String {
|
||||
val key = PC_KEYS[code] ?: return code.toString()
|
||||
val text = if (key.labelRes != 0) context.getString(key.labelRes) else key.label
|
||||
return if (text.length == 1 && text[0].isLetter()) text.uppercase() else text
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
|
||||
data class PhysicalInputKey(val device: String, val name: String, val keyCode: Int, val scanCode: Int) {
|
||||
val label: String get() = "$name · ${KeyEvent.keyCodeToString(keyCode).removePrefix("KEYCODE_")} ($scanCode)"
|
||||
|
||||
companion object {
|
||||
fun identity(device: InputDevice) = "${device.vendorId}:${device.productId}:${device.descriptor.ifBlank { device.name }}"
|
||||
|
||||
fun capture(event: KeyEvent): PhysicalInputKey? {
|
||||
val device = event.device ?: return null
|
||||
if (device.isVirtual || PadBridge.isSystemVirtualInputName(device.name)) return null
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE,
|
||||
KeyEvent.KEYCODE_HOME, KeyEvent.KEYCODE_POWER, KeyEvent.KEYCODE_SLEEP,
|
||||
KeyEvent.KEYCODE_WAKEUP, KeyEvent.KEYCODE_APP_SWITCH -> return null
|
||||
}
|
||||
if (event.keyCode == KeyEvent.KEYCODE_UNKNOWN && event.scanCode <= 0) return null
|
||||
return PhysicalInputKey(identity(device), device.name, event.keyCode, event.scanCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class PhysicalInputBinding(val key: PhysicalInputKey, val action: InputAction)
|
||||
|
||||
class PhysicalInputBindings(private val router: InputRouter) {
|
||||
private class Entry(val binding: PhysicalInputBinding, val channel: InputRouter.Channel) {
|
||||
var heldDevice = -1
|
||||
var suppressed = false
|
||||
}
|
||||
private var entries = emptyList<Entry>()
|
||||
private val released = ArrayList<Entry>()
|
||||
private val devices = HashMap<Int, String>()
|
||||
|
||||
fun configure(bindings: List<PhysicalInputBinding>) {
|
||||
if (entries.map { it.binding } == bindings) return
|
||||
for (entry in entries) {
|
||||
entry.channel.close()
|
||||
if (entry.heldDevice != -1) released.add(entry)
|
||||
}
|
||||
entries = bindings.map { Entry(it, router.channel(InputRole.PHYSICAL, InputControl.A, it.action)) }
|
||||
}
|
||||
|
||||
fun onKey(event: KeyEvent, enabled: Boolean): Boolean {
|
||||
if (event.action != KeyEvent.ACTION_DOWN && event.action != KeyEvent.ACTION_UP) return false
|
||||
for (i in released.indices.reversed()) {
|
||||
val old = released[i]
|
||||
if (old.heldDevice == event.deviceId && old.binding.key.keyCode == event.keyCode && old.binding.key.scanCode == event.scanCode) {
|
||||
if (event.action == KeyEvent.ACTION_UP) released.removeAt(i)
|
||||
return true
|
||||
}
|
||||
}
|
||||
for (entry in entries) {
|
||||
val key = entry.binding.key
|
||||
if (key.keyCode != event.keyCode || key.scanCode != event.scanCode) continue
|
||||
if (entry.heldDevice != -1 && entry.heldDevice == event.deviceId) {
|
||||
if (event.action == KeyEvent.ACTION_UP) {
|
||||
entry.channel.update(0f); entry.heldDevice = -1; entry.suppressed = false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (!enabled || event.action != KeyEvent.ACTION_DOWN || entry.binding.action is InputAction.Native) continue
|
||||
val identity = devices[event.deviceId] ?: event.device?.let { PhysicalInputKey.identity(it) }?.also { devices[event.deviceId] = it } ?: continue
|
||||
if (identity != key.device) continue
|
||||
entry.heldDevice = event.deviceId
|
||||
entry.suppressed = event.repeatCount != 0
|
||||
if (!entry.suppressed) entry.channel.update(1f)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun release() {
|
||||
for (entry in entries) {
|
||||
entry.channel.release()
|
||||
if (entry.heldDevice != -1) entry.suppressed = true
|
||||
}
|
||||
}
|
||||
|
||||
fun disconnected(id: Int) {
|
||||
devices.remove(id)
|
||||
released.removeAll { it.heldDevice == id }
|
||||
for (entry in entries) if (entry.heldDevice == id) { entry.channel.release(); entry.heldDevice = -1 }
|
||||
}
|
||||
|
||||
fun close() { entries.forEach { it.channel.close() }; entries = emptyList(); released.clear(); devices.clear() }
|
||||
}
|
||||
@@ -10,6 +10,7 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
|
||||
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
|
||||
TERMINAL("terminal", R.string.second_mode_terminal),
|
||||
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
|
||||
CUSTOM_CONTROLS("custom-controls", R.string.input_custom_controls),
|
||||
}
|
||||
|
||||
data class SecondScreenDisplay(val id: Int, val label: String)
|
||||
|
||||
@@ -20,7 +20,8 @@ import java.util.ArrayDeque
|
||||
import java.util.UUID
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
class SteamControllerBle(private val context: Context) {
|
||||
class SteamControllerBle(private val context: Context, router: InputRouter? = null) {
|
||||
private val routedInput = router?.let(::TritonInputRouter)
|
||||
private val thread = HandlerThread("steam-controller-ble").apply { start() }
|
||||
private val handler = Handler(thread.looper)
|
||||
private val outputReports = mutableMapOf<Int, UUID>()
|
||||
@@ -47,6 +48,7 @@ class SteamControllerBle(private val context: Context) {
|
||||
running = false
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
disconnect("session ended")
|
||||
routedInput?.close()
|
||||
thread.quitSafely()
|
||||
}
|
||||
|
||||
@@ -217,10 +219,13 @@ class SteamControllerBle(private val context: Context) {
|
||||
|
||||
private fun onState(data: ByteArray) {
|
||||
if (data.size < STATE_BYTES) return
|
||||
FakeInputWriter.writeTritonState(SLOT, reportId, data)
|
||||
val timing = InputTiming.begin()
|
||||
FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data)
|
||||
InputTiming.end(timing)
|
||||
}
|
||||
|
||||
private fun release() {
|
||||
routedInput?.release()
|
||||
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class TritonInputRouter(private val router: InputRouter) {
|
||||
private val channels = InputControl.entries.map { router.channel(InputRole.PHYSICAL, it) }.toTypedArray()
|
||||
private var last: ByteArray? = null
|
||||
private var buffer = ByteArray(45)
|
||||
private val snapshot: () -> Unit = { last?.let { read(it, false) } }
|
||||
|
||||
init { router.beforeProfileChange(snapshot) }
|
||||
|
||||
fun route(data: ByteArray): ByteArray = synchronized(router) {
|
||||
if (data.size < 45) return@synchronized data
|
||||
last = data
|
||||
if (channels.all { it.nativeIdentity() }) return@synchronized data
|
||||
if (buffer.size != data.size) buffer = ByteArray(data.size)
|
||||
data.copyInto(buffer)
|
||||
putBits(buffer, bits(data) and CONTROL_BITS.inv())
|
||||
for (offset in 5..27 step 2) putShort(buffer, offset, 0)
|
||||
read(data, true)
|
||||
buffer
|
||||
}
|
||||
|
||||
private fun read(data: ByteArray, emit: Boolean) {
|
||||
val bits = bits(data)
|
||||
for (control in InputControl.entries) {
|
||||
val channel = channels[control.ordinal]
|
||||
val offset = offset(control)
|
||||
val pair = control.dimensions == 2
|
||||
val x = if (offset != 0) axis(data, offset) else if (bits and bit(control) != 0) 1f else 0f
|
||||
val y = if (pair) axis(data, offset + 2) * if (control.isTrackpad) 1f else -1f else 0f
|
||||
val contact = control.isTrackpad && bits and bit(control) != 0
|
||||
if (!emit) { channel.observe(x, y, contact); continue }
|
||||
val target = channel.update(x, y, contact) ?: continue
|
||||
val targetOffset = offset(target)
|
||||
if (targetOffset != 0) {
|
||||
val value = shortValue(x)
|
||||
if (target.dimensions == 2) {
|
||||
val second = shortValue(y * if (target.isTrackpad) 1f else -1f)
|
||||
val oldX = short(buffer, targetOffset).toLong()
|
||||
val oldY = short(buffer, targetOffset + 2).toLong()
|
||||
if (value.toLong() * value + second.toLong() * second >= oldX * oldX + oldY * oldY) {
|
||||
putShort(buffer, targetOffset, value)
|
||||
putShort(buffer, targetOffset + 2, second)
|
||||
}
|
||||
val touch = if (control.isTrackpad) contact else bits and bit(control) != 0
|
||||
if (touch) putBits(buffer, bits(buffer) or bit(target))
|
||||
} else {
|
||||
if (value >= short(buffer, targetOffset)) putShort(buffer, targetOffset, value)
|
||||
if (bits and bit(control) != 0) putBits(buffer, bits(buffer) or bit(target))
|
||||
}
|
||||
} else if (x > 0.5f) putBits(buffer, bits(buffer) or bit(target))
|
||||
if (target == InputControl.LEFT_CLICK || target == InputControl.RIGHT_CLICK) {
|
||||
val pressureOffset = if (target == InputControl.LEFT_CLICK) 21 else 27
|
||||
val from = if (control == InputControl.LEFT_CLICK) 21 else if (control == InputControl.RIGHT_CLICK) 27 else 0
|
||||
if (from != 0) putShort(buffer, pressureOffset, short(data, from))
|
||||
else if (x > 0.5f) putShort(buffer, pressureOffset, 32767)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun release() = synchronized(router) { channels.forEach { it.release() }; last = null }
|
||||
fun close() = synchronized(router) { release(); channels.forEach { it.close() }; router.removeSnapshot(snapshot) }
|
||||
|
||||
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
|
||||
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
|
||||
private fun putBits(data: ByteArray, value: Int) { for (i in 0..3) data[i + 1] = (value ushr (i * 8)).toByte() }
|
||||
private fun short(data: ByteArray, offset: Int) = ((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
|
||||
private fun axis(data: ByteArray, offset: Int): Float = short(data, offset).let { it / if (it < 0) 32768f else 32767f }
|
||||
private fun shortValue(value: Float) = (value * if (value < 0f) 32768f else 32767f).roundToInt().coerceIn(-32768, 32767)
|
||||
private fun putShort(data: ByteArray, offset: Int, value: Int) { data[offset] = value.toByte(); data[offset + 1] = (value shr 8).toByte() }
|
||||
|
||||
companion object {
|
||||
private const val CONTROL_BITS = 0x0fffffff
|
||||
private fun bit(c: InputControl): Int = when (c) {
|
||||
InputControl.A -> 0x1; InputControl.B -> 0x2; InputControl.X -> 0x4; InputControl.Y -> 0x8
|
||||
InputControl.QAM -> 0x10; InputControl.R3 -> 0x20; InputControl.START -> 0x40
|
||||
InputControl.R4 -> 0x80; InputControl.R5 -> 0x100; InputControl.RB -> 0x200
|
||||
InputControl.DOWN -> 0x400; InputControl.RIGHT -> 0x800; InputControl.LEFT -> 0x1000; InputControl.UP -> 0x2000
|
||||
InputControl.SELECT -> 0x4000; InputControl.L3 -> 0x8000; InputControl.GUIDE -> 0x10000
|
||||
InputControl.L4 -> 0x20000; InputControl.L5 -> 0x40000; InputControl.LB -> 0x80000
|
||||
InputControl.RS -> 0x100000; InputControl.RIGHT_PAD -> 0x200000; InputControl.RIGHT_CLICK -> 0x400000
|
||||
InputControl.RT -> 0x800000; InputControl.LS -> 0x1000000; InputControl.LEFT_PAD -> 0x2000000
|
||||
InputControl.LEFT_CLICK -> 0x4000000; InputControl.LT -> 0x8000000
|
||||
}
|
||||
private fun offset(c: InputControl): Int = when (c) {
|
||||
InputControl.LT -> 5; InputControl.RT -> 7; InputControl.LS -> 9; InputControl.RS -> 13
|
||||
InputControl.LEFT_PAD -> 17; InputControl.RIGHT_PAD -> 23
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user