From 31b8adbb556239fb77d9fcaa6da6667c74a8727a Mon Sep 17 00:00:00 2001 From: Delete228 Date: Fri, 6 Nov 2026 23:56:30 +0300 Subject: [PATCH] Guard shared input slots and mouse backend transitions --- .../com/droiddeck/launcher/SessionActivity.kt | 22 +++-- .../droiddeck/launcher/input/InputProfiles.kt | 4 + .../launcher/input/SteamControllerBle.kt | 85 ++++++++++++------- .../launcher/input/InputProfilesTest.kt | 15 ++++ .../launcher/input/SessionInputPointerTest.kt | 60 ++++++++++++- .../launcher/input/SteamControllerBleTest.kt | 81 +++++++++++++++++- docs/development/unified-input-validation.md | 21 +++++ 7 files changed, 244 insertions(+), 44 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index cbcfe07c34..6aa7d5d41f 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -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) } diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputProfiles.kt b/app/src/main/java/com/droiddeck/launcher/input/InputProfiles.kt index abe65da46d..16d41bfd0b 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputProfiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputProfiles.kt @@ -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() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt index a8c66bab22..5b0b69c8f0 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt @@ -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() @@ -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 diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputProfilesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputProfilesTest.kt index 80507a831d..7c03654a98 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputProfilesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputProfilesTest.kt @@ -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))) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt index 3a549267e8..c59139ad94 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt @@ -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(activity, name) private fun state(name: String): MutableState = 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() + val mouse: MutableList = Collections.synchronizedList(mutableListOf()) + @Volatile var beforeWheel: (() -> Unit)? = null @JvmStatic @Implementation fun __staticInitializer__() {} @JvmStatic @Implementation fun writeDeckControls(index: Int, mask: Int, pads: ShortArray, pressure: ShortArray) {} } diff --git a/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt index 2fcbea3ebd..9d05efea50 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt @@ -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(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(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(controller, "onFeatureRead", + ReflectionHelpers.ClassParameter.from(ByteArray::class.java, ByteArray(2))) + ReflectionHelpers.callInstanceMethod(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(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(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(target, "callback") + .onDescriptorWrite(gatt, descriptor, BluetoothGatt.GATT_SUCCESS) + } + + private fun state(bytes: ByteArray, target: SteamControllerBle = controller) = ReflectionHelpers.callInstanceMethod(target, "onState", ReflectionHelpers.ClassParameter.from(ByteArray::class.java, bytes)) @Implements(FakeInputWriter::class) diff --git a/docs/development/unified-input-validation.md b/docs/development/unified-input-validation.md index 60b4d81702..1d68b32a5d 100644 --- a/docs/development/unified-input-validation.md +++ b/docs/development/unified-input-validation.md @@ -77,6 +77,27 @@ The button-capture dialog opened and cancelled on Thor without a crash. No physical BLE-controller check or new latency measurement was made for these follow-ups. +### Replacement-controller and mouse-backend follow-up + +The Triton slot now has a single owner across activity instances. Late reports, +subscription callbacks, feature replies and teardown from a replaced controller +cannot overwrite the current controller's report or connection flag. Every +instance still closes its own routed source. Claiming the slot happens once at +start; a queued or repeated old start cannot take it back. + +Legacy Select-to-Steam also migrates to the Desktop physical profile when there +is no saved Desktop profile. An existing Desktop assignment is preserved. +Mouse backend selection and publication share the button-owner lock with raw +channel open, soft release and destruction. Horizontal and vertical scrolling +use the same path and fall back to Wayland after leaving raw mode. + +The complete input/UI/global-reset run passed **967 tests in 128 suites**. +The focused run passed **28 tests**, including replacement subscription before +old teardown, unstarted-instance teardown, saved/default Desktop migration, and +concurrent scroll versus raw-channel release/destruction. These changes add no +input queue or timer. Physical BLE hardware and latency remain unmeasured for +this follow-up. + ## Input settings polish, 2026-11-06 The final input/UI host run passed **941 tests in 124 suites, zero failures**.