feat: sync controller button swaps with virtual controls for 1.0.1

This commit is contained in:
2026-10-29 11:50:56 +08:00
parent fefca3ca68
commit 318331a21e
16 changed files with 254 additions and 26 deletions
@@ -154,6 +154,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
private val profileResolver = ControllerProfileResolver()
private lateinit var profileStore: ControllerProfileStore
private val controllerProfiles = mutableMapOf<Int, ControllerProfile>()
private val readyControllerProfileIds = mutableSetOf<Int>()
private var appSettingsLoaded = false
private var virtualButtonSwapsOverride: Pair<Boolean, Boolean>? = null
private val controllerIdentities = mutableMapOf<Int, ControllerIdentity>()
private val controllerProfileRevisions = mutableMapOf<Int, Int>()
private var selectedControllerId: Int? = null
@@ -1213,7 +1216,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
}
})
settingsPanel.addView(Button(this).apply {
text = "手动设置手柄按键、摇杆与功能键"
text = "交换 X/Y、A/B 按键与手动映射"
setOnClickListener {
showControllerSettings(returnToPause = false, returnToSettings = true)
}
@@ -1313,7 +1316,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
val loaded = appSettingsStore.load()
val loadedCores = runCatching { corePreferencesStore.load() }
runOnUiThread {
appSettings = loaded
// A controller profile can finish loading before the application settings.
appSettings = virtualButtonSwapsOverride?.let { (swapAB, swapXY) ->
loaded.copy(virtualSwapAB = swapAB, virtualSwapXY = swapXY)
} ?: loaded
appSettingsLoaded = true
if (appSettings != loaded) persistAppSettings()
loadedCores.onSuccess {
corePreferences = it
corePreferencesReady = true
@@ -1330,6 +1338,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
private fun applyAppSettings() {
muted = appSettings.muted
if (::virtualGamepad.isInitialized) {
virtualGamepad.configureButtonSwaps(appSettings.virtualSwapAB, appSettings.virtualSwapXY)
virtualGamepad.configureDpad(
mode = appSettings.directionMode,
scale = appSettings.virtualDpadSize.scale,
@@ -1352,6 +1361,21 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
}
}
private fun syncVirtualButtonSwaps() {
val deviceId = selectedControllerId ?: return
// Do not overwrite saved screen controls with a temporary default during reconnect.
if (deviceId !in readyControllerProfileIds) return
val profile = controllerProfiles[deviceId] ?: return
virtualButtonSwapsOverride = profile.swapAB to profile.swapXY
val updated = appSettings.copy(virtualSwapAB = profile.swapAB, virtualSwapXY = profile.swapXY)
val changed = updated != appSettings
appSettings = updated
if (::virtualGamepad.isInitialized) {
virtualGamepad.configureButtonSwaps(profile.swapAB, profile.swapXY)
}
if (changed && appSettingsLoaded) persistAppSettings()
}
private fun persistAppSettings() {
val snapshot = appSettings
controllerScope.launch { appSettingsStore.save(snapshot) }
@@ -1527,6 +1551,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
setOnClickListener {
val index = controllers.indexOfFirst { it.deviceId == selectedControllerId }
selectedControllerId = controllers[(index + 1).mod(controllers.size)].deviceId
syncVirtualButtonSwaps()
draftProfile = selectedControllerId?.let(controllerProfiles::get)
pendingBindingAction = null
manualMappingIndex = null
@@ -1565,8 +1590,23 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
})
})
}
controllerSettingsPanel.addView(section("交换 X/Y、A/B 按键"))
controllerSettingsPanel.addView(body(
"默认顺序:A → NES A,B → NES B,X → A 连发,Y → B 连发。\n" +
"两组可独立交换;已有自定义映射时,交换对应的普通或连发动作绑定。点击保存后,当前手柄和屏幕按键同步交换;屏幕按键的文字与触控位置一起调整。",
))
controllerSettingsPanel.addView(Button(this).apply {
text = if (profile.swapAB) "A/B 交换:开" else "A/B 交换:关"
text = if (profile.swapXY) "交换 X/Y 按键:开" else "交换 X/Y 按键:关"
isEnabled = pendingBindingAction == null && manualMappingIndex == null
setOnClickListener {
draftProfile = profile.toggleXY()
controllerSettingsMessage = "已交换 A/B 连发按键(默认 X/Y);保存后生效。"
renderControllerSettings()
}
})
controllerSettingsPanel.addView(Button(this).apply {
text = if (profile.swapAB) "交换 A/B 按键:开" else "交换 A/B 按键:关"
isEnabled = pendingBindingAction == null && manualMappingIndex == null
setOnClickListener {
draftProfile = profile.toggleAB()
controllerSettingsMessage = "已交换 NES A/B;保存后生效。"
@@ -1810,9 +1850,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
private fun saveControllerProfile() {
val deviceId = selectedControllerId ?: return
val profile = draftProfile?.copy(origin = ProfileOrigin.CUSTOM) ?: return
val previousProfile = controllerProfiles[deviceId]
controllerProfileRevisions[deviceId] = (controllerProfileRevisions[deviceId] ?: 0) + 1
controllerProfiles[deviceId] = profile
val revision = (controllerProfileRevisions[deviceId] ?: 0) + 1
controllerProfileRevisions[deviceId] = revision
pendingBindingAction = null
manualMappingIndex = null
bindingCaptureWaitForNeutral = false
@@ -1820,15 +1859,25 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
controllerScope.launch {
val result = runCatching { profileStore.save(profile) }
runOnUiThread {
if (controllerProfileRevisions[deviceId] != revision ||
controllerIdentities[deviceId]?.fingerprint() != profile.fingerprint
) return@runOnUiThread
if (result.isSuccess) {
inputRouter.clearDevice(deviceId).let(::applyRoutedInput)
axisHysteresis.clearDevice(deviceId)
controllerProfiles[deviceId] = profile
readyControllerProfileIds += deviceId
if (selectedControllerId == deviceId) {
syncVirtualButtonSwaps()
if (draftProfile?.copy(origin = ProfileOrigin.CUSTOM) == profile) draftProfile = profile
}
}
if (selectedControllerId != deviceId) return@runOnUiThread
controllerSettingsMessage = if (result.isSuccess) {
"设置已保存;重连和重启后按设备特征恢复。"
"设置已保存,屏幕按键已同步;重连和重启后恢复。"
} else {
if (previousProfile == null) controllerProfiles.remove(deviceId)
else controllerProfiles[deviceId] = previousProfile
"保存失败:${result.exceptionOrNull()?.message ?: "未知错误"};修改仍保留在页面,可重试保存。"
}
draftProfile = profile
renderControllerSettings()
}
}
@@ -1838,9 +1887,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
val deviceId = selectedControllerId ?: return
val identity = controllerIdentities[deviceId] ?: return
val defaultProfile = profileResolver.resolve(identity)
controllerProfileRevisions[deviceId] = (controllerProfileRevisions[deviceId] ?: 0) + 1
controllerProfiles[deviceId] = defaultProfile
draftProfile = defaultProfile
val revision = (controllerProfileRevisions[deviceId] ?: 0) + 1
controllerProfileRevisions[deviceId] = revision
pendingBindingAction = null
manualMappingIndex = null
bindingCaptureWaitForNeutral = false
@@ -1848,9 +1896,22 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
controllerScope.launch {
val result = runCatching { profileStore.reset(identity) }
runOnUiThread {
if (controllerProfileRevisions[deviceId] != revision ||
controllerIdentities[deviceId]?.fingerprint() != identity.fingerprint()
) return@runOnUiThread
if (result.isSuccess) {
inputRouter.clearDevice(deviceId).let(::applyRoutedInput)
axisHysteresis.clearDevice(deviceId)
controllerProfiles[deviceId] = defaultProfile
readyControllerProfileIds += deviceId
if (selectedControllerId == deviceId) {
syncVirtualButtonSwaps()
draftProfile = defaultProfile
}
}
if (selectedControllerId != deviceId) return@runOnUiThread
controllerSettingsMessage = if (result.isSuccess) {
"已恢复安全的通用默认配置。"
"已恢复通用默认配置,屏幕按键也已恢复。"
} else {
"恢复默认失败:${result.exceptionOrNull()?.message ?: "未知错误"}"
}
@@ -1862,12 +1923,14 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
private fun syncControllerProfiles() {
val connected = controllers.mapTo(mutableSetOf()) { it.deviceId }
controllerProfiles.keys.retainAll(connected)
readyControllerProfileIds.retainAll(connected)
controllerIdentities.keys.retainAll(connected)
controllerProfileRevisions.keys.retainAll(connected)
controllers.forEach { controller ->
val identity = controller.toIdentity()
if (controllerIdentities[controller.deviceId]?.fingerprint() == identity.fingerprint()) return@forEach
controllerIdentities[controller.deviceId] = identity
readyControllerProfileIds.remove(controller.deviceId)
controllerProfiles[controller.deviceId] = profileResolver.resolve(identity)
val revision = (controllerProfileRevisions[controller.deviceId] ?: 0) + 1
controllerProfileRevisions[controller.deviceId] = revision
@@ -1881,7 +1944,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
val cleared = inputRouter.clearDevice(controller.deviceId)
axisHysteresis.clearDevice(controller.deviceId)
controllerProfiles[controller.deviceId] = restored
readyControllerProfileIds += controller.deviceId
applyRoutedInput(cleared)
if (selectedControllerId == controller.deviceId) syncVirtualButtonSwaps()
if (selectedControllerId == controller.deviceId && draftProfile == null) {
renderControllerSettings()
}
@@ -1894,6 +1959,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
draftProfile = null
pendingBindingAction = null
}
syncVirtualButtonSwaps()
renderControllerSettings()
}
@@ -32,6 +32,8 @@ internal fun computeVirtualGamepadGeometry(
dpadScale: Float = 1f,
dpadHorizontalOffset: Float = 0f,
dpadVerticalOffset: Float = 0f,
swapAB: Boolean = false,
swapXY: Boolean = false,
): VirtualGamepadGeometry {
val w = width.coerceAtLeast(1f)
val h = height.coerceAtLeast(1f)
@@ -96,5 +98,13 @@ internal fun computeVirtualGamepadGeometry(
),
pause = VirtualControl(w - rightInset - sideWidth * 0.72f - horizontalShift + shift, h * 0.13f, utilityRadius),
reset = VirtualControl(baseResetX + shift, h * 0.13f, utilityRadius),
)
).let { geometry ->
// Drawing, pressed feedback and touch hit testing all use these same controls.
geometry.copy(
faceA = if (swapAB) geometry.faceB else geometry.faceA,
faceB = if (swapAB) geometry.faceA else geometry.faceB,
faceX = if (swapXY) geometry.faceY else geometry.faceX,
faceY = if (swapXY) geometry.faceX else geometry.faceY,
)
}
}
@@ -47,6 +47,8 @@ class VirtualGamepadView(
private var safeLeft = 0f
private var safeRight = 0f
private var screenShift = 0f
private var swapAB = false
private var swapXY = false
private var directionMode = DirectionMode.EIGHT_WAY
private var dpadScale = 1.18f
private var dpadHorizontalOffset = 0f
@@ -88,6 +90,15 @@ class VirtualGamepadView(
invalidate()
}
internal fun configureButtonSwaps(swapAB: Boolean, swapXY: Boolean) {
if (this.swapAB == swapAB && this.swapXY == swapXY) return
// Release touches against the old layout before changing their targets.
clearInputs()
this.swapAB = swapAB
this.swapXY = swapXY
invalidate()
}
internal fun configureDpad(
mode: DirectionMode,
scale: Float,
@@ -285,6 +296,8 @@ class VirtualGamepadView(
dpadScale = dpadScale,
dpadHorizontalOffset = dpadHorizontalOffset,
dpadVerticalOffset = dpadVerticalOffset,
swapAB = swapAB,
swapXY = swapXY,
)
private companion object {
@@ -52,6 +52,7 @@ data class ControllerProfile(
val pressThreshold: Float = 0.55f,
val releaseThreshold: Float = 0.35f,
val swapAB: Boolean = false,
val swapXY: Boolean = false,
) {
init {
require(pressThreshold in 0.2f..0.95f)
@@ -78,6 +79,16 @@ data class ControllerProfile(
},
)
fun toggleXY(): ControllerProfile {
val x = bindings[GameAction.TURBO_A].orEmpty()
val y = bindings[GameAction.TURBO_B].orEmpty()
return copy(
origin = ProfileOrigin.CUSTOM,
bindings = bindings + mapOf(GameAction.TURBO_A to y, GameAction.TURBO_B to x),
swapXY = !swapXY,
)
}
fun toggleAB(): ControllerProfile {
val a = bindings[GameAction.NES_A].orEmpty()
val b = bindings[GameAction.NES_B].orEmpty()
@@ -13,6 +13,7 @@ object ControllerProfileJson {
.put("pressThreshold", profile.pressThreshold.toDouble())
.put("releaseThreshold", profile.releaseThreshold.toDouble())
.put("swapAB", profile.swapAB)
.put("swapXY", profile.swapXY)
.put(
"bindings",
JSONObject().apply {
@@ -50,6 +51,7 @@ object ControllerProfileJson {
pressThreshold = root.getDouble("pressThreshold").toFloat(),
releaseThreshold = root.getDouble("releaseThreshold").toFloat(),
swapAB = root.getBoolean("swapAB"),
swapXY = root.optBoolean("swapXY", false),
)
}
}
@@ -38,6 +38,8 @@ data class AppSettings(
val virtualDpadSize: VirtualDpadSize = VirtualDpadSize.LARGE,
val virtualDpadHorizontalOffset: Float = 0f,
val virtualDpadVerticalOffset: Float = 0f,
val virtualSwapAB: Boolean = false,
val virtualSwapXY: Boolean = false,
val guideCompleted: Boolean = false,
)
@@ -63,6 +65,8 @@ class AppSettingsStore(private val context: Context) {
virtualDpadSize = VirtualDpadSize.fromStored(values[VIRTUAL_DPAD_SIZE] ?: VirtualDpadSize.LARGE.ordinal),
virtualDpadHorizontalOffset = (values[VIRTUAL_DPAD_HORIZONTAL_OFFSET] ?: 0f).coerceIn(-1f, 1f),
virtualDpadVerticalOffset = (values[VIRTUAL_DPAD_VERTICAL_OFFSET] ?: 0f).coerceIn(-1f, 1f),
virtualSwapAB = values[VIRTUAL_SWAP_AB] ?: false,
virtualSwapXY = values[VIRTUAL_SWAP_XY] ?: false,
guideCompleted = values[GUIDE_COMPLETED] ?: false,
)
}
@@ -80,6 +84,8 @@ class AppSettingsStore(private val context: Context) {
values[VIRTUAL_DPAD_SIZE] = settings.virtualDpadSize.ordinal
values[VIRTUAL_DPAD_HORIZONTAL_OFFSET] = settings.virtualDpadHorizontalOffset.coerceIn(-1f, 1f)
values[VIRTUAL_DPAD_VERTICAL_OFFSET] = settings.virtualDpadVerticalOffset.coerceIn(-1f, 1f)
values[VIRTUAL_SWAP_AB] = settings.virtualSwapAB
values[VIRTUAL_SWAP_XY] = settings.virtualSwapXY
values[GUIDE_COMPLETED] = settings.guideCompleted
}
}
@@ -97,6 +103,8 @@ class AppSettingsStore(private val context: Context) {
private val VIRTUAL_DPAD_SIZE = intPreferencesKey("virtual_dpad_size")
private val VIRTUAL_DPAD_HORIZONTAL_OFFSET = floatPreferencesKey("virtual_dpad_horizontal_offset")
private val VIRTUAL_DPAD_VERTICAL_OFFSET = floatPreferencesKey("virtual_dpad_vertical_offset")
private val VIRTUAL_SWAP_AB = booleanPreferencesKey("virtual_swap_ab")
private val VIRTUAL_SWAP_XY = booleanPreferencesKey("virtual_swap_xy")
private val GUIDE_COMPLETED = booleanPreferencesKey("guide_completed")
}
}
@@ -7,7 +7,7 @@ class BuildIdentityTest {
@Test
fun debugBuildUsesTheDocumentedIdentity() {
assertEquals("org.neslite.app.debug", BuildConfig.APPLICATION_ID)
assertEquals("1.0.0-debug", BuildConfig.VERSION_NAME)
assertEquals(1000000, BuildConfig.VERSION_CODE)
assertEquals("1.0.1-debug", BuildConfig.VERSION_NAME)
assertEquals(1000001, BuildConfig.VERSION_CODE)
}
}
@@ -218,6 +218,47 @@ class VirtualGamepadLayoutTest {
assertTrue(flipped.faceB.x + flipped.faceB.radius < 2760f)
}
@Test
fun allSwapCombinationsMoveOnlyTheirMatchingLabeledTouchControls() {
val original = computeVirtualGamepadGeometry(2760f, 1256f, 126f)
for (swapAB in listOf(false, true)) {
for (swapXY in listOf(false, true)) {
val swapped = computeVirtualGamepadGeometry(
2760f, 1256f, 126f, swapAB = swapAB, swapXY = swapXY,
)
assertEquals(if (swapAB) original.faceB else original.faceA, swapped.faceA)
assertEquals(if (swapAB) original.faceA else original.faceB, swapped.faceB)
assertEquals(if (swapXY) original.faceY else original.faceX, swapped.faceX)
assertEquals(if (swapXY) original.faceX else original.faceY, swapped.faceY)
// Every other control and the game viewport remain unchanged.
assertEquals(original, swapped.copy(
faceA = original.faceA, faceB = original.faceB,
faceX = original.faceX, faceY = original.faceY,
))
}
}
}
@Test
fun swappedControlsKeepTheirPositionsAcrossDifferentInsetsAndDpadSettings() {
for (inset in listOf(0f, 48f, 172f, 288f)) {
val original = computeVirtualGamepadGeometry(
2760f, 1256f, 126f, safeLeft = inset, screenShift = 47f,
dpadScale = 1.35f, dpadHorizontalOffset = -1f, dpadVerticalOffset = 1f,
)
val swapped = computeVirtualGamepadGeometry(
2760f, 1256f, 126f, safeLeft = inset, screenShift = 47f,
dpadScale = 1.35f, dpadHorizontalOffset = -1f, dpadVerticalOffset = 1f,
swapAB = true, swapXY = true,
)
assertEquals(original.faceB, swapped.faceA)
assertEquals(original.faceA, swapped.faceB)
assertEquals(original.faceY, swapped.faceX)
assertEquals(original.faceX, swapped.faceY)
assertEquals(original.horizontalShift, swapped.horizontalShift)
}
}
private fun distance(first: VirtualControl, second: VirtualControl): Float =
hypot(first.x - second.x, first.y - second.y)
}
@@ -55,6 +55,54 @@ class ControllerProfileTest {
assertFalse(JSONObject(ControllerProfileJson.encode(swapped)).has("deviceId"))
}
@Test
fun xySwapOnlyExchangesTurboActionsAndIsReversible() {
val original = ControllerProfileResolver().resolve(identity)
val swapped = original.toggleXY()
assertTrue(swapped.swapXY)
assertFalse(swapped.swapAB)
assertEquals(ProfileOrigin.CUSTOM, swapped.origin)
assertEquals(setOf(GameAction.TURBO_B), swapped.actionsFor(InputBinding(BindingKind.KEY, 99)))
assertEquals(setOf(GameAction.TURBO_A), swapped.actionsFor(InputBinding(BindingKind.KEY, 100)))
GameAction.entries.filter { it != GameAction.TURBO_A && it != GameAction.TURBO_B }.forEach {
assertEquals(original.bindings[it], swapped.bindings[it])
}
assertEquals(original.bindings, swapped.toggleXY().bindings)
assertFalse(swapped.toggleXY().swapXY)
}
@Test
fun bothSwapsAreIndependentAndPersistTogether() {
val original = ControllerProfileResolver().resolve(identity)
val swapped = original.toggleAB().toggleXY()
assertEquals(swapped, original.toggleXY().toggleAB())
assertEquals(setOf(GameAction.NES_B), swapped.actionsFor(InputBinding(BindingKind.KEY, 96)))
assertEquals(setOf(GameAction.NES_A), swapped.actionsFor(InputBinding(BindingKind.KEY, 97)))
assertEquals(swapped, ControllerProfileJson.decode(ControllerProfileJson.encode(swapped)))
val xyOnly = swapped.toggleAB()
assertFalse(xyOnly.swapAB)
assertTrue(xyOnly.swapXY)
assertEquals(original.bindings, xyOnly.toggleXY().bindings)
}
@Test
fun legacyProfileWithoutXyFlagKeepsSavedBindings() {
val original = ControllerProfileResolver().resolve(identity).toggleAB()
val legacy = JSONObject(ControllerProfileJson.encode(original)).apply { remove("swapXY") }
assertEquals(original, ControllerProfileJson.decode(legacy.toString()))
}
@Test
fun xySwapPreservesCustomAndEmptyBindings() {
val original = ControllerProfileResolver().resolve(identity)
.replaceBinding(GameAction.TURBO_A, InputBinding(BindingKind.KEY, 188))
.clearBinding(GameAction.TURBO_B)
val swapped = original.toggleXY()
assertTrue(swapped.bindings.getValue(GameAction.TURBO_A).isEmpty())
assertEquals(setOf(GameAction.TURBO_B), swapped.actionsFor(InputBinding(BindingKind.KEY, 188)))
assertEquals(original, swapped.toggleXY())
}
@Test
fun manualMappingCanReplaceAndClearEachAction() {
val original = ControllerProfileResolver().resolve(identity)
@@ -20,6 +20,8 @@ class AppSettingsTest {
assertEquals(VirtualDpadSize.LARGE, settings.virtualDpadSize)
assertEquals(0f, settings.virtualDpadHorizontalOffset)
assertEquals(0f, settings.virtualDpadVerticalOffset)
assertFalse(settings.virtualSwapAB)
assertFalse(settings.virtualSwapXY)
assertFalse(settings.guideCompleted)
}