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.
This commit is contained in:
Delete228 committed 2026-11-06 19:53:40 +03:00
1 parent 7b7722bd25
commit 915f373d82
16 files changed
+414 -49

No files matched your search

@@ -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) {
@@ -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 }
@@ -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<Int, UUID>()
@@ -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)
@@ -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<PhysicalInputKey?>(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)) }
})
}
@@ -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() }
@@ -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)) {
@@ -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) {