mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 14:26:00 +00:00
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:
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) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="input_library_recovered">Unreadable input settings were preserved in a recovery copy. You can continue editing the restored profiles.</string>
|
||||
<string name="input_builtin_layout_hint">This built-in layout keeps its existing controls. Create a custom layout to add, move or resize elements.</string>
|
||||
<string name="input_properties">Properties</string>
|
||||
<string name="input_click_properties">Click properties</string>
|
||||
|
||||
@@ -41,6 +41,8 @@
|
||||
<string name="input_custom_controls">Custom controls</string>
|
||||
<string name="input_extra_keys">Device-specific buttons</string>
|
||||
<string name="input_capture">Assign a physical button</string>
|
||||
<string name="input_capture_confirm">Release the button, then choose Edit, Retry, or Cancel. B or Back cancels after release.</string>
|
||||
<string name="input_capture_retry">Retry</string>
|
||||
<string name="input_capture_hint">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.</string>
|
||||
<string name="input_remove_binding">Remove assignment</string>
|
||||
<string name="input_latency">Input diagnostics</string>
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,16 @@ class SessionInputPointerTest {
|
||||
assertTrue(CompositorShadow.events.isEmpty())
|
||||
}
|
||||
|
||||
@Test fun focusCleanupReleasesHardwareAndKeyboardKeysWithoutReleasingAnotherOwner() {
|
||||
val held = ReflectionHelpers.getField<HeldInput>(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<Unit>(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)
|
||||
|
||||
@@ -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<Pair<Int, Boolean>>()
|
||||
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<Any?>(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<Unit>(controller, "release")
|
||||
ReflectionHelpers.setField(controller, "featureRead", 7L)
|
||||
ReflectionHelpers.callInstanceMethod<Unit>(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<Boolean>(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<Unit>(controller, "onState",
|
||||
ReflectionHelpers.ClassParameter.from(ByteArray::class.java, bytes))
|
||||
|
||||
@Implements(FakeInputWriter::class)
|
||||
class Writer {
|
||||
companion object {
|
||||
val reports = ArrayList<ByteArray>()
|
||||
val connections = ArrayList<Boolean>()
|
||||
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++ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -288,6 +288,22 @@ class InputSettingsTest {
|
||||
} finally { ShadowDisplayManager.removeDisplay(displayId) }
|
||||
}
|
||||
|
||||
@Test @Config(sdk = [34]) fun unavailableDisplayDismissesSettingsWithoutCrashing() {
|
||||
val displayId = ShadowDisplayManager.addDisplay("w640dp-h480dp", ReflectionHelpers.getStaticField<Int>(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<Int>(Display::class.java, "TYPE_EXTERNAL"))
|
||||
val display = context.getSystemService(DisplayManager::class.java).getDisplay(displayId)
|
||||
|
||||
Reference in new issue
Block a user