From 915f373d82111fec01d17a47d870a8055d9a91da Mon Sep 17 00:00:00 2001 From: Delete228 Date: Fri, 6 Nov 2026 19:53:40 +0300 Subject: [PATCH] Harden input migration and session lifecycle Keep migration binding IDs stable, preserve unreadable libraries before recovery, and retain forward-version protection. Release keyboard owners on focus loss, handle unavailable settings displays, and allow controller confirmation or cancellation after physical key capture. Stop BLE routing and publication synchronously before asynchronous disconnect. Add regression coverage and record local and Thor validation. --- .../com/droiddeck/launcher/SessionActivity.kt | 2 +- .../launcher/input/InputLibraries.kt | 34 ++++++- .../launcher/input/SteamControllerBle.kt | 67 ++++++++----- .../launcher/ui/InputBindingWidgets.kt | 54 +++++++--- .../launcher/ui/InputDisplayContent.kt | 13 ++- .../launcher/ui/InputSettingsPage.kt | 1 + .../launcher/ui/PhysicalShortcutsDialog.kt | 2 +- app/src/main/res/values/input_library.xml | 1 + app/src/main/res/values/input_strings.xml | 2 + .../launcher/input/InputLibraryTest.kt | 20 ++++ .../input/LegacyScreenKeyMigrationTest.kt | 27 +++++ .../launcher/input/SessionInputPointerTest.kt | 10 ++ .../launcher/input/SteamControllerBleTest.kt | 98 +++++++++++++++++++ .../launcher/ui/InputCaptureDialogTest.kt | 84 ++++++++++++++++ .../launcher/ui/InputSettingsTest.kt | 16 +++ docs/development/unified-input-validation.md | 32 +++++- 16 files changed, 414 insertions(+), 49 deletions(-) create mode 100644 app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/ui/InputCaptureDialogTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 4be3d31cdc..cbcfe07c34 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -4224,7 +4224,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { mouseBackInput.cancel() heldButtons.release(1 or 2 or 8 or 16) guestKeysDown.toList().forEach { sendGuestKey(it, false) } - heldKeys.release(8) + heldKeys.release(8 or 16 or 32) } private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) { diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt index 0baf28e18c..7352800e28 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt @@ -6,10 +6,12 @@ import android.util.DisplayMetrics import android.view.Display import org.json.JSONArray import org.json.JSONObject +import java.util.UUID object InputLibraries { private const val VERSION = 6 private const val KEY = "library" + private const val RECOVERY = "library-recovery." const val OVERLAY = "builtin.overlay" const val DECK = "builtin.deck" const val TRACKPAD = "builtin.trackpad" @@ -46,11 +48,24 @@ object InputLibraries { fun hasPendingScreenKeyMigration(context: Context) = !prefs(context).contains(LegacyScreenKeyMigration.BACKUP) && LegacyScreenKeyMigration.snapshot(context) != null + fun hasLibraryRecovery(context: Context) = prefs(context).all.keys.any { it.startsWith(RECOVERY) } + @Synchronized fun update(context: Context, change: (InputLibrary) -> InputLibrary): InputLibrary { - val stored = prefs(context).getString(KEY, null) - require(stored == null || decode(stored) != null) { "The saved input library cannot be edited by this version." } - return change(read(context)).validate().also { write(context, it) } + val p = prefs(context) + val stored = p.getString(KEY, null) + val invalid = stored != null && decode(stored) == null + require(!invalid || runCatching { JSONObject(stored!!).getInt("version") }.getOrNull()?.let { it <= VERSION } != false) { + "The saved input library cannot be edited by this version." + } + val updated = change(read(context)).validate() + if (invalid) { + val encoded = encode(updated) + require(encoded.length <= 2_000_000) { "The input library is too large to save." } + check(p.edit().putString(RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8)), stored) + .putString(KEY, encoded).commit()) { "Could not save the input library and its recovery copy." } + } else write(context, updated) + return updated } private fun write(context: Context, library: InputLibrary) { @@ -106,7 +121,7 @@ object InputLibraries { val key = part.bindings to layout.id val id = migrated.getOrPut(key) { val old = library.preset(part.bindings) - val newId = newInputId() + val newId = migrationBindingId(result, old.id, layout.id) val keyboard = elements.filter { it.id == "builtin:keyboard" }.associate { it.id to InputAction.Command(InputCommand.KEYBOARD) } val clicks = if (settings.stickClick) old.clicks else old.clicks + elements.filter { it.hasClick }.associate { it.id to InputAction.Disabled } result = result.withPreset(old.copy(id = newId, layoutId = layout.id, elements = old.elements + keyboard, clicks = clicks)) @@ -141,7 +156,7 @@ object InputLibraries { val layout = replacements[part.layout] ?: return@mapValues part val id = migrated.getOrPut(part.bindings to layout.id) { val old = library.preset(part.bindings) - val id = newInputId() + val id = migrationBindingId(result, old.id, layout.id) val original = library.layouts.first { it.id == layout.id } val stockLayout = layout.copy(id = if (original.template == InputLayoutTemplate.TRACKPAD) TRACKPAD else DECK) result = result.withPreset(old.copy(id = id, layoutId = layout.id, @@ -159,6 +174,15 @@ object InputLibraries { return result.validate() } + private fun migrationBindingId(library: InputLibrary, binding: String, layout: String): String { + val seed = JSONArray(listOf(binding, layout)).toString().toByteArray(Charsets.UTF_8) + val base = "migrated.bindings." + UUID.nameUUIDFromBytes(seed) + var id = base + var suffix = 0 + while (library.bindings.any { it.id == id }) id = "$base.${++suffix}" + return id + } + private fun scopeLayouts(library: InputLibrary): InputLibrary = library.copy(layouts = library.layouts.map { layout -> val roles = library.profiles.flatMap { p -> p.parts.filterValues { it.layout == layout.id }.keys } + library.selections.values.flatMap { s -> s.parts.filterValues { library.preset(it).layoutId == layout.id }.keys } 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 a7c57a39cf..a8c66bab22 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamControllerBle.kt @@ -21,7 +21,9 @@ import java.util.UUID @SuppressLint("MissingPermission") class SteamControllerBle(private val context: Context, router: InputRouter? = null) { - private val routedInput = router?.let(::TritonInputRouter) + private val inputLock = router ?: Any() + private var routedInput = router?.let(::TritonInputRouter) + @Volatile private var stopped = false private val thread = HandlerThread("steam-controller-ble").apply { start() } private val handler = Handler(thread.looper) private val outputReports = mutableMapOf() @@ -38,22 +40,32 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu private var featureRead = 0L fun start() = handler.post { - if (running) return@post + if (stopped || running) return@post running = true Log.i(TAG, "looking for a paired Steam Controller") connect() } - fun stop() = handler.post { - running = false - handler.removeCallbacksAndMessages(null) - disconnect("session ended") - routedInput?.close() - thread.quitSafely() + fun stop() { + synchronized(inputLock) { + if (stopped) return + stopped = true + routedInput?.close() + routedInput = null + FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES)) + connected = false + FakeInputWriter.setTritonConnected(SLOT, false) + } + handler.post { + running = false + handler.removeCallbacksAndMessages(null) + disconnect("session ended") + thread.quitSafely() + } } private fun connect() { - if (!running || gatt != null) return + if (stopped || !running || gatt != null) return if (SessionState.suspended) { handler.postDelayed(::connect, RETRY_MS) return @@ -86,11 +98,15 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu featureRead = 0L queuedWrites.clear() outputReports.clear() - connected = false - FakeInputWriter.setTritonConnected(SLOT, false) + synchronized(inputLock) { + if (!stopped) { + connected = false + FakeInputWriter.setTritonConnected(SLOT, false) + release() + } + } g.disconnect() g.close() - release() Log.i(TAG, "disconnected: $why") listener?.invoke() } @@ -121,10 +137,12 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu } override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { - 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) + synchronized(inputLock) { + if (stopped || 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) + } listener?.invoke() if (connected) { refreshLizardMode() @@ -166,6 +184,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu } private fun subscribe(g: BluetoothGatt) { + if (stopped) return val service = g.getService(SERVICE) if (service == null) { Log.w(TAG, "no Valve service on \"${g.device.name}\" (attempt ${discoveries + 1}); services: " + @@ -210,27 +229,28 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu } private fun refreshLizardMode() { - if (!connected) return + if (stopped || !connected) return 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) { - if (data.size < STATE_BYTES) return + private fun onState(data: ByteArray) = synchronized(inputLock) { + if (stopped || data.size < STATE_BYTES) return@synchronized val timing = InputTiming.begin() FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data) InputTiming.end(timing) } - private fun release() { + private fun release() = synchronized(inputLock) { + if (stopped) return@synchronized routedInput?.release() FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES)) } private fun pollOutput() { - if (!running || !connected || gatt == null) return + if (stopped || !running || !connected || gatt == null) return 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)) @@ -244,7 +264,8 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu handler.postDelayed(::pollOutput, OUTPUT_POLL_MS) } - private fun onFeatureRead(value: ByteArray?) { + private fun onFeatureRead(value: ByteArray?) = synchronized(inputLock) { + if (stopped) return@synchronized outputWritePending = false if (featureRead != 0L) { if (value == null) Log.w(TAG, "feature read failed") @@ -273,7 +294,7 @@ class SteamControllerBle(private val context: Context, router: InputRouter? = nu } private fun writeNextOutput() { - if (outputWritePending) return + if (stopped || outputWritePending) return val g = gatt ?: return val (uuid, value) = queuedWrites.pollFirst() ?: return val characteristic = g.getService(SERVICE)?.getCharacteristic(uuid) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputBindingWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputBindingWidgets.kt index eb0337193b..a8eb95b347 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputBindingWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputBindingWidgets.kt @@ -1,14 +1,14 @@ package com.droiddeck.launcher.ui -import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Column import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester -import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource +import androidx.compose.ui.window.DialogProperties import com.droiddeck.launcher.R import com.droiddeck.launcher.input.* @@ -37,19 +37,43 @@ internal fun commandLabel(command: InputCommand) = stringResource(when (command) @Composable internal fun InputCaptureDialog(onDismiss: () -> Unit, onPick: (PhysicalInputKey) -> Unit) { - val focus = remember { FocusRequester() } + val confirmFocus = remember { FocusRequester() } var captured by remember { mutableStateOf(null) } + var capturedDevice by remember { mutableIntStateOf(-1) } + var ready by remember { mutableStateOf(false) } AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(R.string.input_capture)) }, - modifier = Modifier.onPreviewKeyEvent { - val event = it.nativeKeyEvent - val key = PhysicalInputKey.capture(event) - if (key != null) { - if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) captured = key - true - } else false - }.focusRequester(focus).focusable(), - text = { Text(captured?.label ?: stringResource(R.string.input_capture_hint)) }, - confirmButton = { TextButton(enabled = captured != null, onClick = { captured?.let(onPick) }) { Text(stringResource(R.string.ctrl_edit)) } }, - dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.gesture_cancel)) } }) - LaunchedEffect(Unit) { focus.requestFocus() } + properties = DialogProperties(dismissOnBackPress = ready), + text = { + CaptureShortcutKeys { event -> + if (ready) { + if (event.keyCode == android.view.KeyEvent.KEYCODE_BACK || event.keyCode == android.view.KeyEvent.KEYCODE_BUTTON_B) { + if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) onDismiss() + true + } else false + } else { + val key = PhysicalInputKey.capture(event) + if (key == null) false else { + if (captured == null && event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) { + captured = key + capturedDevice = event.deviceId + } else if (captured == key && capturedDevice == event.deviceId && event.action == android.view.KeyEvent.ACTION_UP) ready = true + true + } + } + } + Column { + Text(captured?.label ?: stringResource(R.string.input_capture_hint)) + if (captured != null) Text(stringResource(R.string.input_capture_confirm)) + } + }, + confirmButton = { + TextButton(enabled = ready, modifier = Modifier.focusRequester(confirmFocus) + .controllerConfirm(ready) { captured?.let(onPick) }, onClick = { captured?.let(onPick) }) { Text(stringResource(R.string.ctrl_edit)) } + LaunchedEffect(ready) { if (ready) confirmFocus.requestFocus() } + }, + dismissButton = { + TextButton(modifier = Modifier.controllerConfirm { onDismiss() }, onClick = onDismiss) { Text(stringResource(R.string.gesture_cancel)) } + if (ready) TextButton(modifier = Modifier.controllerConfirm { captured = null; ready = false }, + onClick = { captured = null; ready = false }) { Text(stringResource(R.string.input_capture_retry)) } + }) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputDisplayContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputDisplayContent.kt index a65134b7d6..65bcd52be6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputDisplayContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputDisplayContent.kt @@ -47,10 +47,19 @@ internal fun InputDisplayContent(host: ComponentActivity, display: Display, onDi override fun dismiss() { compose?.disposeComposition(); compose = null; super.dismiss() } } presentation.setOnCancelListener { dismiss() } - presentation.show() + fun showPresentation() { + if (!display.isValid) { dismiss(); return } + try { + presentation.show() + } catch (_: WindowManager.InvalidDisplayException) { + presentation.dismiss() + dismiss() + } + } + showPresentation() val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_STOP) presentation.hide() - if (event == Lifecycle.Event.ON_START) presentation.show() + if (event == Lifecycle.Event.ON_START) showPresentation() } host.lifecycle.addObserver(observer) onDispose { host.lifecycle.removeObserver(observer); presentation.dismiss() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt index c1eed9db94..53c777be35 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSettingsPage.kt @@ -167,6 +167,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe } } if (InputLibraries.hasPendingScreenKeyMigration(context)) InputHint(stringResource(R.string.input_import_failed)) + if (InputLibraries.hasLibraryRecovery(context)) InputHint(stringResource(R.string.input_library_recovered)) if (library.profiles.any { it.id.startsWith("migrated.screenkeys.") }) Text(stringResource(R.string.input_imported_keys_hint), Modifier.padding(16.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) SettingsGroup(stringResource(R.string.input_profiles)) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialog.kt index a30cbbfe92..243b1a0bc8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhysicalShortcutsDialog.kt @@ -189,7 +189,7 @@ internal fun PhysicalShortcutsDialog( } @Composable -private fun CaptureShortcutKeys(onKey: (KeyEvent) -> Boolean) { +internal fun CaptureShortcutKeys(onKey: (KeyEvent) -> Boolean) { val currentOnKey by rememberUpdatedState(onKey) val window = (LocalView.current.parent as DialogWindowProvider).window DisposableEffect(window) { diff --git a/app/src/main/res/values/input_library.xml b/app/src/main/res/values/input_library.xml index fc419258a2..d463478069 100644 --- a/app/src/main/res/values/input_library.xml +++ b/app/src/main/res/values/input_library.xml @@ -1,5 +1,6 @@ + Unreadable input settings were preserved in a recovery copy. You can continue editing the restored profiles. This built-in layout keeps its existing controls. Create a custom layout to add, move or resize elements. Properties Click properties diff --git a/app/src/main/res/values/input_strings.xml b/app/src/main/res/values/input_strings.xml index 77c79ba054..765191d9e2 100644 --- a/app/src/main/res/values/input_strings.xml +++ b/app/src/main/res/values/input_strings.xml @@ -41,6 +41,8 @@ Custom controls Device-specific buttons Assign a physical button + Release the button, then choose Edit, Retry, or Cancel. B or Back cancels after release. + Retry Press a button, including a back button reported as a keyboard key. Volume and Android system keys are reserved. The assignment applies only to this device. Remove assignment Input diagnostics diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt index 813ec2a07b..773b4ff030 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt @@ -127,6 +127,26 @@ class InputLibraryTest { assertEquals(future, prefs.getString("library", null)) } + @Test fun unreadableLibrariesKeepStableEditorReferencesUntilAnEditPreservesRecoveryData() { + val valid = InputLibraries.encode(InputLibraries.read(context)) + val invalidValues = listOf("{broken", org.json.JSONObject(valid).put("selected", "missing").toString()) + for (raw in invalidValues) { + prefs.edit().putString("library", raw).commit() + val first = InputLibraries.read(context) + val second = InputLibraries.read(context) + assertEquals(first, second) + val id = first.profile("game").binding(InputRole.PRIMARY) + assertEquals(first.preset(id), second.preset(id)) + assertEquals(raw, prefs.getString("library", null)) + val updated = InputLibraries.update(context) { it.copy(selected = "desktop") } + assertEquals("desktop", InputLibraries.read(context).selected) + assertEquals(updated, InputLibraries.read(context)) + assertTrue(prefs.all.filterKeys { it.startsWith("library-recovery.") }.containsValue(raw)) + } + assertTrue(InputLibraries.hasLibraryRecovery(context)) + assertEquals(invalidValues.toSet(), prefs.all.filterKeys { it.startsWith("library-recovery.") }.values.toSet()) + } + @Test fun resettingAProfileDoesNotResetSharedBindingsOrAccumulatePrivateCopies() { var library = InputLibraries.read(context).duplicateProfile("desktop", "Editor", "editor", sharePhysical = true) val common = library.preset(library.profile("desktop").binding(InputRole.PHYSICAL)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/LegacyScreenKeyMigrationTest.kt b/app/src/test/java/com/droiddeck/launcher/input/LegacyScreenKeyMigrationTest.kt index f01e501bc9..6d72190ce4 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/LegacyScreenKeyMigrationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/LegacyScreenKeyMigrationTest.kt @@ -65,4 +65,31 @@ class LegacyScreenKeyMigrationTest { assertEquals("28:NaN,0.5,44", ControllerPrefs.prefs(context).getString("screenKeys", null)) assertFalse(prefs.contains(LegacyScreenKeyMigration.BACKUP)) } + + @Test fun failedScreenKeyMigrationKeepsUpgradedBindingIdsStableForEditorLookup() { + val original = InputLibraries.read(context).chooseLayout("game", InputRole.SECONDARY, InputLibraries.DECK) + val fixed = original.copy(layouts = original.layouts.map { + when (it.id) { + InputLibraries.OVERLAY -> it.copy(elements = emptyList(), template = InputLayoutTemplate.OVERLAY) + InputLibraries.DECK -> it.copy(elements = emptyList(), template = InputLayoutTemplate.DECK) + else -> it + } + }, bindings = original.bindings.map { + if (it.layoutId in setOf(InputLibraries.OVERLAY, InputLibraries.DECK)) it.copy(elements = emptyMap(), clicks = emptyMap()) else it + }) + val raw = JSONObject(InputLibraries.encode(fixed)).put("version", 2).toString() + prefs.edit().putString("library", raw).commit() + ControllerPrefs.prefs(context).edit().putString("screenKeys", "28:NaN,0.5,44").commit() + val first = InputLibraries.read(context) + val second = InputLibraries.read(context) + assertEquals(first, second) + for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY)) { + val id = first.profile("game").binding(role) + assertEquals(first.preset(id), second.preset(id)) + assertTrue(second.layout("game", role)!!.editable) + } + assertEquals(raw, prefs.getString("library", null)) + assertTrue(InputLibraries.hasPendingScreenKeyMigration(context)) + assertEquals("28:NaN,0.5,44", ControllerPrefs.prefs(context).getString("screenKeys", null)) + } } 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 f145d58e6d..3a549267e8 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt @@ -171,6 +171,16 @@ class SessionInputPointerTest { assertTrue(CompositorShadow.events.isEmpty()) } + @Test fun focusCleanupReleasesHardwareAndKeyboardKeysWithoutReleasingAnotherOwner() { + val held = ReflectionHelpers.getField(activity, "heldKeys") + output.key(29, true) + for ((owner, code) in listOf(8 to 30, 16 to 31, 32 to 32, 16 to 29)) held.set(owner, code, true) + ReflectionHelpers.callInstanceMethod(activity, "releaseHeldGuestInput") + assertEquals(setOf(30 to 0, 31 to 0, 32 to 0), CompositorShadow.keys.filter { it.second == 0 }.toSet()) + output.key(29, false) + assertEquals(29 to 0, CompositorShadow.keys.last()) + } + @Test fun horizontalWheelUsesTheSameDirectionInBothMouseBackends() { output.scrollHorizontal(2) assertEquals(listOf(Triple(11, 0, 240)), CompositorShadow.events) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt new file mode 100644 index 0000000000..2fcbea3ebd --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SteamControllerBleTest.kt @@ -0,0 +1,98 @@ +package com.droiddeck.launcher.input + +import android.os.Handler +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE, shadows = [SteamControllerBleTest.Writer::class]) +class SteamControllerBleTest { + private val keys = ArrayList>() + private val router = InputRouter(object : InputOutput { + override fun key(code: Int, down: Boolean) { keys += code to down } + override fun button(code: Int, down: Boolean) {} + override fun pointer(dx: Float, dy: Float) {} + override fun scroll(steps: Int) {} + override fun command(command: InputCommand) {} + override fun requestMotion() {} + }) + private lateinit var controller: SteamControllerBle + private lateinit var handler: Handler + + @Before fun setUp() { + Writer.reports.clear() + Writer.connections.clear() + Writer.features = 0 + router.setProfile(InputProfile.defaults(InputProfile.GAME) + .withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Keys(listOf(57)))) + controller = SteamControllerBle(RuntimeEnvironment.getApplication(), router) + handler = ReflectionHelpers.getField(controller, "handler") + shadowOf(handler.looper).pause() + } + + @After fun close() { + controller.stop() + handler.looper.quit() + } + + @Test fun stopReleasesAndDetachesInputBeforeQueuedCallbacksCanPublish() { + state(ByteArray(45).apply { this[1] = 1 }) + assertEquals(listOf(57 to true), keys) + handler.post { state(ByteArray(45).apply { this[1] = 1 }) } + controller.stop() + assertEquals(listOf(57 to true, 57 to false), keys) + assertNull(ReflectionHelpers.getField(controller, "routedInput")) + assertTrue(Writer.reports.last().all { it == 0.toByte() }) + val reports = Writer.reports.size + val connections = Writer.connections.toList() + shadowOf(handler.looper).idle() + state(ByteArray(45)) + state(ByteArray(45).apply { this[1] = 1 }) + ReflectionHelpers.callInstanceMethod(controller, "release") + ReflectionHelpers.setField(controller, "featureRead", 7L) + ReflectionHelpers.callInstanceMethod(controller, "onFeatureRead", ReflectionHelpers.ClassParameter.from(ByteArray::class.java, ByteArray(2))) + controller.stop() + assertEquals(reports, Writer.reports.size) + assertEquals(connections, Writer.connections) + assertEquals(0, Writer.features) + assertEquals(listOf(57 to true, 57 to false), keys) + } + + @Test fun stoppingBeforeQueuedStartPreservesAnotherSourcesHeldKey() { + val other = router.channel(InputRole.PRIMARY, InputControl.B, InputAction.Keys(listOf(57))) + other.update(1f) + state(ByteArray(45).apply { this[1] = 1 }) + controller.start() + controller.stop() + shadowOf(handler.looper).idle() + assertFalse(ReflectionHelpers.getField(controller, "running")) + assertEquals(listOf(57 to true), keys) + other.close() + assertEquals(listOf(57 to true, 57 to false), keys) + } + + private fun state(bytes: ByteArray) = ReflectionHelpers.callInstanceMethod(controller, "onState", + ReflectionHelpers.ClassParameter.from(ByteArray::class.java, bytes)) + + @Implements(FakeInputWriter::class) + class Writer { + companion object { + val reports = ArrayList() + val connections = ArrayList() + var features = 0 + @JvmStatic @Implementation fun writeTritonState(slot: Int, reportId: Int, report: ByteArray) { reports += report.copyOf() } + @JvmStatic @Implementation fun setTritonConnected(slot: Int, connected: Boolean) { connections += connected } + @JvmStatic @Implementation fun writeTritonFeatureReply(slot: Int, request: Long, report: ByteArray?) { features++ } + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputCaptureDialogTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputCaptureDialogTest.kt new file mode 100644 index 0000000000..3afeba08bf --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputCaptureDialogTest.kt @@ -0,0 +1,84 @@ +package com.droiddeck.launcher.ui + +import android.hardware.input.InputManager +import android.view.InputDevice +import android.view.KeyCharacterMap +import android.view.KeyEvent +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.test.* +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.PadBridgeRoutingTest +import com.droiddeck.launcher.input.PhysicalInputKey +import org.junit.Assert.* +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.InputDeviceBuilder +import org.robolectric.shadows.ShadowDialog + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w960dp-h640dp-land", shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class]) +class InputCaptureDialogTest { + @get:Rule val compose = createRobolectricComposeRule() + private val context get() = RuntimeEnvironment.getApplication() + private val open = mutableStateOf(true) + private var selected: PhysicalInputKey? = null + private lateinit var device: InputDevice + + @Before fun setUp() { + device = InputDeviceBuilder.newBuilder().setId(10).setName("Thor buttons") + .setDescriptor("thor-extra").setSources(InputDevice.SOURCE_KEYBOARD) + .setKeyboardType(InputDevice.KEYBOARD_TYPE_ALPHABETIC) + .setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build() + shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device) + compose.setContent { DroidDeckTheme { + if (open.value) InputCaptureDialog({ open.value = false }) { selected = it; open.value = false } + } } + } + + @Test fun physicalBackCanBeCapturedAndConfirmedWithControllerA() { + send(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_DOWN) + compose.onNodeWithText(context.getString(R.string.ctrl_edit)).assertIsNotEnabled() + assertTrue(open.value) + send(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_UP) + compose.onNodeWithText(context.getString(R.string.ctrl_edit)).assertIsEnabled() + assertNull(selected) + send(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN) + assertEquals(KeyEvent.KEYCODE_BACK, selected?.keyCode) + assertFalse(open.value) + } + + @Test fun controllerBCanBeCapturedAndAnotherPressCancelsWithoutSaving() { + send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_DOWN) + send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_UP) + assertTrue(open.value) + send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_DOWN) + assertFalse(open.value) + assertNull(selected) + } + + @Test fun retryAllowsAnotherButtonAndConsumesItsReleaseBeforeConfirmation() { + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN) + send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP) + compose.onNodeWithText(context.getString(R.string.input_capture_retry)).performClick() + send(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN) + send(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP) + assertNull(selected) + assertTrue(open.value) + send(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN) + assertEquals(KeyEvent.KEYCODE_BUTTON_A, selected?.keyCode) + } + + private fun send(code: Int, action: Int) { + compose.runOnIdle { + assertTrue(ShadowDialog.getLatestDialog().window!!.callback.dispatchKeyEvent( + KeyEvent(100L, 100L, action, code, 0, 0, device.id, 700, 0, InputDevice.SOURCE_KEYBOARD))) + } + compose.waitForIdle() + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt index d5ca908c6c..0f171a7721 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSettingsTest.kt @@ -288,6 +288,22 @@ class InputSettingsTest { } finally { ShadowDisplayManager.removeDisplay(displayId) } } + @Test @Config(sdk = [34]) fun unavailableDisplayDismissesSettingsWithoutCrashing() { + val displayId = ShadowDisplayManager.addDisplay("w640dp-h480dp", ReflectionHelpers.getStaticField(Display::class.java, "TYPE_EXTERNAL")) + val display = context.getSystemService(DisplayManager::class.java).getDisplay(displayId) + shadowOf(display).setFlags(Display.FLAG_PRESENTATION) + ShadowDisplayManager.removeDisplay(displayId) + val open = mutableStateOf(true) + compose.setContent { DroidDeckTheme { + val host = androidx.compose.ui.platform.LocalContext.current.findActivity() as androidx.activity.ComponentActivity + if (open.value) InputDisplayContent(host, display, { open.value = false }) { InputSettingsPage({}) } + } } + compose.runOnIdle { + assertFalse(open.value) + assertTrue(ShadowDialog.getShownDialogs().none { it.isShowing }) + } + } + @Test @Config(sdk = [34]) fun mainEditorOpenedFromSecondarySettingsUsesAnActivityWindow() { val displayId = ShadowDisplayManager.addDisplay("w640dp-h480dp", ReflectionHelpers.getStaticField(Display::class.java, "TYPE_EXTERNAL")) val display = context.getSystemService(DisplayManager::class.java).getDisplay(displayId) diff --git a/docs/development/unified-input-validation.md b/docs/development/unified-input-validation.md index 33a52649d0..60b4d81702 100644 --- a/docs/development/unified-input-validation.md +++ b/docs/development/unified-input-validation.md @@ -46,8 +46,36 @@ The follow-up router-ownership fix passed **47 tests** in `InputSourceOwnershipT `InputSurfaceSourceTest`, and `InputRouterTest`, including two new regressions. An obsolete activity (or one without a router) cannot detach the replacement activity's Deck routes; the current owner still releases its held keys on cleanup. -This follow-up changes teardown only and was not reinstalled or retested on Thor, -which was no longer available over ADB after the screenshot pass. +GitHub's complete Build APK workflow passed for `7b7722bd2`. + +### Review follow-up + +- Upgrade binding IDs are deterministic across unsuccessful reads. Editor lookup + from an earlier read remains valid when legacy screen-key import fails. +- An edit of malformed supported-version data commits both the restored library + and a recovery copy of the original text. Reads alone preserve the original; + newer unsupported versions remain protected against overwrite. Settings show + that recovery data was retained. +- Focus/capture loss releases hardware, Android keyboard and PC-keyboard owners + without releasing another source's hold. Secondary settings handle an invalid + presentation display at initial show and resume. +- Physical-button capture waits for release before confirmation/navigation. + Back and B remain assignable; another Back/B press cancels, A confirms, and + Retry starts a new capture. The existing dialog-window key hook is reused. +- Steam Controller BLE teardown synchronously closes its routed source and + gates state/feature publication. Queued callbacks and starts cannot reactivate + it after stop returns; disconnect work remains on the existing BLE thread. + +The input/UI/global-reset run passed **959 tests in 127 suites**. After the +additional BLE finding, **5 BLE/routing tests passed**, including two regressions +for queued callbacks, synchronous release, source detachment and shared holds. +The final APK passed packaging, runtime/native dependency and signature checks: +`a5ec9120be120b829748f8489782a0c7158360d7f8deb61777fe75d601708d20`. +It was installed over Input Test; saved profile preferences remained byte-for-byte +identical and the existing environment was retained. +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. ## Input settings polish, 2026-11-06