Guard shared input slots and mouse backend transitions

This commit is contained in:
Delete228 committed 2026-11-06 23:56:30 +03:00
1 parent 915f373d82
commit 31b8adbb55
7 files changed
+244 -44

No files matched your search

@@ -193,11 +193,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
override fun scroll(steps: Int) { sendSceneWheel(steps) }
override fun scrollHorizontal(steps: Int) {
val writer = if (evdevMouseActive) mouseWriter else null
if (writer != null) writer.writeMouseWheel(0, steps, 120)
else WaylandCompositor.nativeSendSceneInput(11, 0, steps * 120)
}
override fun scrollHorizontal(steps: Int) { sendSceneWheel(steps, horizontal = true) }
override fun requestMotion() { inputMotion.request() }
override fun command(command: InputCommand) {
uiHandler.post {
@@ -3655,7 +3651,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun sceneScale(rect: android.graphics.RectF): Float =
SessionState.outputSize.first / rect.width()
private fun openEvdevMouse() {
// Clearing button owners emits releases, so backend transitions share their lock with all mouse writes.
private fun openEvdevMouse(): Unit = synchronized(heldButtons) {
if (evdevMouseActive || !evdevMouseOn) return
val writer = mouseWriter ?: com.droiddeck.launcher.input.FakeInputWriter(
File(LinuxRuntime.sessionRoot(this), "dev/input").absolutePath,
@@ -3669,7 +3666,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "raw mouse channel active (pointer locked)")
}
private fun closeEvdevMouse() {
private fun closeEvdevMouse(): Unit = synchronized(heldButtons) {
if (!evdevMouseActive) return
heldButtons.clear()
mouseWriter?.softRelease()
@@ -3677,7 +3674,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "raw mouse channel idle")
}
private fun releaseEvdevMouse() {
private fun releaseEvdevMouse(): Unit = synchronized(heldButtons) {
if (evdevMouseActive) heldButtons.clear()
evdevMouseActive = false
mouseWriter?.destroy()
@@ -3685,13 +3682,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "raw mouse channel removed")
}
private fun sendSceneDelta(dx: Float, dy: Float) {
private fun sendSceneDelta(dx: Float, dy: Float): Unit = synchronized(heldButtons) {
val writer = if (evdevMouseActive) mouseWriter else null
if (writer != null) writer.writeMouseDelta(dx, dy)
else WaylandCompositor.sendPointerDelta(dx, dy)
}
private fun sendSceneButton(code: Int, down: Boolean) {
private fun sendSceneButton(code: Int, down: Boolean): Unit = synchronized(heldButtons) {
val raw = if (down) evdevMouseActive.also { guestButtonsDown[code] = it }
else guestButtonsDown.remove(code) ?: evdevMouseActive
val writer = if (raw) mouseWriter else null
@@ -3699,9 +3696,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
else WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0)
}
private fun sendSceneWheel(steps: Int) {
private fun sendSceneWheel(steps: Int, horizontal: Boolean = false): Unit = synchronized(heldButtons) {
val writer = if (evdevMouseActive) mouseWriter else null
if (writer != null) writer.writeMouseWheel(-steps, 0, 120)
if (writer != null) writer.writeMouseWheel(if (horizontal) 0 else -steps, if (horizontal) steps else 0, 120)
else if (horizontal) WaylandCompositor.nativeSendSceneInput(11, 0, steps * 120)
else WaylandCompositor.nativeSendSceneInput(4, steps, 0)
}
@@ -103,6 +103,10 @@ object InputProfiles {
}
if (old.selectSteam) game = game.withBinding(InputRole.PHYSICAL, InputControl.SELECT, InputAction.Native(InputControl.GUIDE))
if (!p.contains("profile.${InputProfile.GAME}")) saveLegacy(context, game)
if (old.selectSteam && !p.contains("profile.${InputProfile.DESKTOP}")) {
saveLegacy(context, InputProfile.defaults(InputProfile.DESKTOP)
.withBinding(InputRole.PHYSICAL, InputControl.SELECT, InputAction.Native(InputControl.GUIDE)))
}
p.edit().putBoolean("migrated", true).apply()
}
@@ -24,6 +24,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
private val inputLock = router ?: Any()
private var routedInput = router?.let(::TritonInputRouter)
@Volatile private var stopped = false
private var started = false
private val thread = HandlerThread("steam-controller-ble").apply { start() }
private val handler = Handler(thread.looper)
private val outputReports = mutableMapOf<Int, UUID>()
@@ -39,11 +40,27 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
private var outputWritePending = false
private var featureRead = 0L
fun start() = handler.post {
if (stopped || running) return@post
running = true
Log.i(TAG, "looking for a paired Steam Controller")
connect()
fun start(): Unit = synchronized(inputLock) {
if (stopped || started) return@synchronized
started = true
synchronized(slotLock) {
slotOwner = this
connected = false
FakeInputWriter.writeTritonState(SLOT, 0x45, ByteArray(STATE_BYTES))
FakeInputWriter.setTritonConnected(SLOT, false)
}
handler.post {
if (stopped || slotOwner !== this || running) return@post
running = true
Log.i(TAG, "looking for a paired Steam Controller")
connect()
}
}
private inline fun withSlot(block: () -> Unit) = synchronized(inputLock) {
synchronized(slotLock) {
if (!stopped && slotOwner === this) block()
}
}
fun stop() {
@@ -52,9 +69,14 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
stopped = true
routedInput?.close()
routedInput = null
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
connected = false
FakeInputWriter.setTritonConnected(SLOT, false)
synchronized(slotLock) {
if (slotOwner === this) {
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
connected = false
FakeInputWriter.setTritonConnected(SLOT, false)
slotOwner = null
}
}
}
handler.post {
running = false
@@ -65,7 +87,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
}
private fun connect() {
if (stopped || !running || gatt != null) return
if (stopped || slotOwner !== this || !running || gatt != null) return
if (SessionState.suspended) {
handler.postDelayed(::connect, RETRY_MS)
return
@@ -100,9 +122,11 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
outputReports.clear()
synchronized(inputLock) {
if (!stopped) {
connected = false
FakeInputWriter.setTritonConnected(SLOT, false)
release()
withSlot {
connected = false
FakeInputWriter.setTritonConnected(SLOT, false)
}
}
}
g.disconnect()
@@ -137,8 +161,8 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
}
override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
synchronized(inputLock) {
if (stopped || g !== gatt || descriptor.characteristic.uuid != input) return
withSlot {
if (g !== gatt || descriptor.characteristic.uuid != input) return
Log.i(TAG, "subscribed to report 0x%02x (status %d)".format(reportId, status))
connected = status == BluetoothGatt.GATT_SUCCESS
FakeInputWriter.setTritonConnected(SLOT, connected)
@@ -184,7 +208,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
}
private fun subscribe(g: BluetoothGatt) {
if (stopped) return
if (stopped || slotOwner !== this) return
val service = g.getService(SERVICE)
if (service == null) {
Log.w(TAG, "no Valve service on \"${g.device.name}\" (attempt ${discoveries + 1}); services: " +
@@ -228,16 +252,16 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
.onFailure { Log.w(TAG, "could not refresh the service cache", it) }
}
private fun refreshLizardMode() {
if (stopped || !connected) return
private fun refreshLizardMode() = withSlot {
if (!connected) return@withSlot
val msg = ByteArray(FEATURE_BYTES)
msg[0] = 0x87.toByte(); msg[1] = 3; msg[2] = 9
enqueueOutput(REPORT, msg)
handler.postDelayed(::refreshLizardMode, LIZARD_REFRESH_MS)
}
private fun onState(data: ByteArray) = synchronized(inputLock) {
if (stopped || data.size < STATE_BYTES) return@synchronized
private fun onState(data: ByteArray) = withSlot {
if (data.size < STATE_BYTES) return@withSlot
val timing = InputTiming.begin()
FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data)
InputTiming.end(timing)
@@ -246,11 +270,13 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
private fun release() = synchronized(inputLock) {
if (stopped) return@synchronized
routedInput?.release()
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
withSlot {
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
}
}
private fun pollOutput() {
if (stopped || !running || !connected || gatt == null) return
private fun pollOutput() = withSlot {
if (!running || !connected || gatt == null) return@withSlot
FakeInputWriter.readTritonOutput(SLOT, outputSequence)?.let { output ->
outputSequence = ByteBuffer.wrap(output, 0, 8).order(ByteOrder.LITTLE_ENDIAN).long
sendOutputReport(output[8] != 0.toByte(), output.copyOfRange(9, output.size))
@@ -264,8 +290,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
handler.postDelayed(::pollOutput, OUTPUT_POLL_MS)
}
private fun onFeatureRead(value: ByteArray?) = synchronized(inputLock) {
if (stopped) return@synchronized
private fun onFeatureRead(value: ByteArray?) = withSlot {
outputWritePending = false
if (featureRead != 0L) {
if (value == null) Log.w(TAG, "feature read failed")
@@ -293,14 +318,14 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
writeNextOutput()
}
private fun writeNextOutput() {
if (stopped || outputWritePending) return
val g = gatt ?: return
val (uuid, value) = queuedWrites.pollFirst() ?: return
private fun writeNextOutput() = withSlot {
if (outputWritePending) return@withSlot
val g = gatt ?: return@withSlot
val (uuid, value) = queuedWrites.pollFirst() ?: return@withSlot
val characteristic = g.getService(SERVICE)?.getCharacteristic(uuid)
if (characteristic == null) {
Log.w(TAG, "BLE output characteristic $uuid disappeared")
return
return@withSlot
}
if (value == null) {
if (g.readCharacteristic(characteristic)) {
@@ -309,7 +334,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
queuedWrites.addFirst(uuid to null)
handler.postDelayed(::writeNextOutput, OUTPUT_RETRY_MS)
}
return
return@withSlot
}
@Suppress("DEPRECATION")
characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
@@ -325,6 +350,8 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu
}
companion object {
private val slotLock = Any()
@Volatile private var slotOwner: SteamControllerBle? = null
private const val TAG = "SteamControllerBle"
private const val SLOT = 0
private const val RETRY_MS = 5_000L
@@ -28,10 +28,25 @@ class InputProfilesTest {
assertEquals(InputAction.Disabled, game.action(InputRole.PRIMARY, InputControl.X))
assertEquals(InputAction.Native(), game.action(InputRole.PHYSICAL, InputControl.A))
assertEquals(InputAction.Native(InputControl.GUIDE), game.action(InputRole.PHYSICAL, InputControl.SELECT))
assertEquals(InputAction.Native(InputControl.GUIDE), InputProfiles.read(context, InputProfile.DESKTOP)
.action(InputRole.PHYSICAL, InputControl.SELECT))
InputProfiles.reset(context, InputProfile.GAME)
assertEquals(InputAction.Native(), InputProfiles.read(context, InputProfile.GAME).action(InputRole.PRIMARY, InputControl.A))
}
@Test fun migrationPreservesSavedDesktopSelectBinding() {
ControllerPrefs.setSelectSteam(context, true)
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().putString("profile.desktop",
"""{"version":1,"bindings":[{"role":"PHYSICAL","control":"select","action":{"type":"disabled"}}]}""").commit()
assertEquals(InputAction.Disabled, InputProfiles.read(context, InputProfile.DESKTOP)
.action(InputRole.PHYSICAL, InputControl.SELECT))
}
@Test fun migrationKeepsDesktopKeyboardWhenSelectToSteamIsOff() {
assertEquals(InputAction.Command(InputCommand.KEYBOARD), InputProfiles.read(context, InputProfile.DESKTOP)
.action(InputRole.PHYSICAL, InputControl.SELECT))
}
@Test fun bindingsAndDeviceKeysRoundTripWithoutAffectingOtherProfile() {
val game = InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.SECONDARY, InputControl.A, InputAction.Keys(listOf(29, 30)))
@@ -21,6 +21,10 @@ import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
import java.util.Collections
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE, shadows = [SessionInputPointerTest.CompositorShadow::class, SessionInputPointerTest.WriterShadow::class])
@@ -43,6 +47,7 @@ class SessionInputPointerTest {
CompositorShadow.events.clear()
CompositorShadow.keys.clear()
WriterShadow.mouse.clear()
WriterShadow.beforeWheel = null
}
@After fun tearDown() {
@@ -205,6 +210,52 @@ class SessionInputPointerTest {
assertEquals(listOf(Triple(3, 272, 1), Triple(3, 272, 0)), CompositorShadow.events)
}
@Test fun horizontalWheelFinishesBeforeRawMouseDestruction() {
checkWheelTransition(horizontal = true, transition = "releaseEvdevMouse", marker = "destroy")
}
@Test fun verticalWheelFinishesBeforeRawMouseSoftRelease() {
checkWheelTransition(horizontal = false, transition = "closeEvdevMouse", marker = "release")
}
private fun checkWheelTransition(horizontal: Boolean, transition: String, marker: String) {
ReflectionHelpers.setField(activity, "mouseWriter", FakeInputWriter(activity.cacheDir.path, FakeInputWriter.MOUSE_SLOT))
ReflectionHelpers.setField(activity, "evdevMouseActive", true)
val entered = CountDownLatch(1)
val continueWrite = CountDownLatch(1)
val transitioning = CountDownLatch(1)
val finished = CountDownLatch(1)
WriterShadow.beforeWheel = {
entered.countDown()
check(continueWrite.await(5, TimeUnit.SECONDS))
}
val executor = Executors.newFixedThreadPool(2)
fun scroll() { if (horizontal) output.scrollHorizontal(2) else output.scroll(2) }
try {
val writing = executor.submit { scroll() }
assertTrue(entered.await(5, TimeUnit.SECONDS))
val closing = executor.submit {
transitioning.countDown()
invoke(transition)
finished.countDown()
}
assertTrue(transitioning.await(5, TimeUnit.SECONDS))
assertFalse(finished.await(100, TimeUnit.MILLISECONDS))
continueWrite.countDown()
writing.get(5, TimeUnit.SECONDS)
closing.get(5, TimeUnit.SECONDS)
assertEquals(listOf(if (horizontal) "wheel:0:2:120" else "wheel:-2:0:120", marker), WriterShadow.mouse)
scroll()
assertEquals(2, WriterShadow.mouse.size)
assertEquals(listOf(if (horizontal) Triple(11, 0, 240) else Triple(4, 2, 0)), CompositorShadow.events)
} finally {
continueWrite.countDown()
executor.shutdownNow()
executor.awaitTermination(5, TimeUnit.SECONDS)
WriterShadow.beforeWheel = null
}
}
private fun refresh() = invoke("refreshInputProfile")
private fun invoke(name: String) = ReflectionHelpers.callInstanceMethod<Unit>(activity, name)
private fun <T> state(name: String): MutableState<T> = ReflectionHelpers.getField(activity, "$name\$delegate")
@@ -226,10 +277,15 @@ class SessionInputPointerTest {
class WriterShadow {
@Implementation fun writeMouseButton(code: Short, down: Boolean) { mouse += "button:$code:$down" }
@Implementation fun writeMouseDelta(dx: Float, dy: Float) { mouse += "delta:$dx:$dy" }
@Implementation fun writeMouseWheel(vertical: Int, horizontal: Int, value120: Int) { mouse += "wheel:$vertical:$horizontal:$value120" }
@Implementation fun writeMouseWheel(vertical: Int, horizontal: Int, value120: Int) {
beforeWheel?.invoke()
mouse += "wheel:$vertical:$horizontal:$value120"
}
@Implementation fun softRelease() { mouse += "release" }
@Implementation fun destroy() { mouse += "destroy" }
companion object {
val mouse = mutableListOf<String>()
val mouse: MutableList<String> = Collections.synchronizedList(mutableListOf())
@Volatile var beforeWheel: (() -> Unit)? = null
@JvmStatic @Implementation fun __staticInitializer__() {}
@JvmStatic @Implementation fun writeDeckControls(index: Int, mask: Int, pads: ShortArray, pressure: ShortArray) {}
}
@@ -1,5 +1,10 @@
package com.droiddeck.launcher.input
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.os.Handler
import org.junit.After
import org.junit.Assert.*
@@ -13,6 +18,8 @@ import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
import org.robolectric.shadows.ShadowBluetoothGatt
import java.util.UUID
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [SteamControllerBleTest.Writer::class])
@@ -38,6 +45,7 @@ class SteamControllerBleTest {
controller = SteamControllerBle(RuntimeEnvironment.getApplication(), router)
handler = ReflectionHelpers.getField(controller, "handler")
shadowOf(handler.looper).pause()
controller.start()
}
@After fun close() {
@@ -81,7 +89,78 @@ class SteamControllerBleTest {
assertEquals(listOf(57 to true, 57 to false), keys)
}
private fun state(bytes: ByteArray) = ReflectionHelpers.callInstanceMethod<Unit>(controller, "onState",
@Test fun staleControllerCannotClearOrPublishIntoItsReplacementsSlot() {
state(ByteArray(45).apply { this[1] = 1 })
assertEquals(listOf(57 to true), keys)
val replacement = SteamControllerBle(RuntimeEnvironment.getApplication())
val replacementHandler = ReflectionHelpers.getField<Handler>(replacement, "handler")
shadowOf(replacementHandler.looper).pause()
try {
replacement.start()
subscribe(replacement)
val report = ByteArray(45).apply { this[1] = 2 }
state(report, replacement)
val reports = Writer.reports.size
val connections = Writer.connections.toList()
controller.start()
shadowOf(handler.looper).idle()
subscribe(controller)
state(ByteArray(45))
ReflectionHelpers.setField(controller, "featureRead", 7L)
ReflectionHelpers.callInstanceMethod<Unit>(controller, "onFeatureRead",
ReflectionHelpers.ClassParameter.from(ByteArray::class.java, ByteArray(2)))
ReflectionHelpers.callInstanceMethod<Unit>(controller, "disconnect",
ReflectionHelpers.ClassParameter.from(String::class.java, "old link lost"))
controller.stop()
shadowOf(handler.looper).idle()
assertTrue(SteamControllerBle.connected)
assertEquals(connections, Writer.connections)
assertEquals(reports, Writer.reports.size)
assertArrayEquals(report, Writer.reports.last())
assertEquals(0, Writer.features)
assertEquals(listOf(57 to true, 57 to false), keys)
assertNull(ReflectionHelpers.getField<Any?>(controller, "routedInput"))
replacement.stop()
assertFalse(SteamControllerBle.connected)
assertFalse(Writer.connections.last())
assertTrue(Writer.reports.last().all { it == 0.toByte() })
} finally {
replacement.stop()
replacementHandler.looper.quit()
}
}
@Test fun stoppingAnUnstartedControllerPreservesTheActiveSlot() {
subscribe(controller)
val unused = SteamControllerBle(RuntimeEnvironment.getApplication())
try {
val reports = Writer.reports.size
val connections = Writer.connections.toList()
unused.stop()
assertTrue(SteamControllerBle.connected)
assertEquals(connections, Writer.connections)
assertEquals(reports, Writer.reports.size)
} finally {
unused.stop()
ReflectionHelpers.getField<Handler>(unused, "handler").looper.quit()
}
}
private fun subscribe(target: SteamControllerBle) {
val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
val gatt = ShadowBluetoothGatt.newInstance(device)
val input = UUID.fromString("100F6C7A-1735-4313-B402-38567131E5F3")
val characteristic = BluetoothGattCharacteristic(input, BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0)
val descriptor = BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"), 0)
characteristic.addDescriptor(descriptor)
ReflectionHelpers.setField(target, "gatt", gatt)
ReflectionHelpers.setField(target, "input", input)
ReflectionHelpers.setField(target, "reportId", 0x45)
ReflectionHelpers.getField<BluetoothGattCallback>(target, "callback")
.onDescriptorWrite(gatt, descriptor, BluetoothGatt.GATT_SUCCESS)
}
private fun state(bytes: ByteArray, target: SteamControllerBle = controller) = ReflectionHelpers.callInstanceMethod<Unit>(target, "onState",
ReflectionHelpers.ClassParameter.from(ByteArray::class.java, bytes))
@Implements(FakeInputWriter::class)