feat: add guided manual controller mapping

This commit is contained in:
2026-09-12 22:20:54 +08:00
parent 20fa1855ca
commit 10bc3bde1b
14 changed files with 254 additions and 43 deletions
+211 -25
View File
@@ -150,6 +150,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
private var selectedControllerId: Int? = null
private var draftProfile: ControllerProfile? = null
private var pendingBindingAction: GameAction? = null
private var manualMappingIndex: Int? = null
private var bindingCaptureWaitForNeutral = false
private var controllerSettingsMessage = "选择动作后按一个手柄键或推动一个轴。"
private var settingsReturnToPause = false
private var controllerReturnToSettings = false
@@ -557,6 +559,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
repeatCount = event.repeatCount,
)
if (pendingBindingAction != null && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
bindingCaptureWaitForNeutral = false
captureBinding(InputBinding(BindingKind.KEY, event.keyCode))
renderInputState()
return true
@@ -607,11 +610,24 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
)
}
if (pendingBindingAction != null) {
if (bindingCaptureWaitForNeutral) {
val released = ranges.all { range ->
kotlin.math.abs(event.getAxisValue(range.axis)) <= profile.releaseThreshold
}
if (released) {
bindingCaptureWaitForNeutral = false
controllerSettingsMessage = manualMappingPrompt()
renderControllerSettings()
}
renderInputState()
return true
}
ranges
.map { range -> range to event.getAxisValue(range.axis) }
.filter { (_, value) -> kotlin.math.abs(value) >= profile.pressThreshold }
.maxByOrNull { (_, value) -> kotlin.math.abs(value) }
?.let { (range, value) ->
bindingCaptureWaitForNeutral = true
captureBinding(
InputBinding(
if (value < 0f) BindingKind.AXIS_NEGATIVE else BindingKind.AXIS_POSITIVE,
@@ -1052,7 +1068,7 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
}
})
settingsPanel.addView(Button(this).apply {
text = "手柄映射、A/B 交换与死区"
text = "手动设置手柄按键、摇杆与功能键"
setOnClickListener {
showControllerSettings(returnToPause = false, returnToSettings = true)
}
@@ -1210,7 +1226,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
currentOverlayPage == OverlayPage.DIAGNOSTICS
draftProfile = selectedControllerId?.let(controllerProfiles::get)
pendingBindingAction = null
controllerSettingsMessage = "选择动作后按一个手柄键或推动一个轴。"
manualMappingIndex = null
bindingCaptureWaitForNeutral = false
controllerSettingsMessage = "可逐项设置全部按键,也可以点击任意动作单独修改。"
showOverlayPage(OverlayPage.CONTROLLER_SETTINGS, "手柄按键设置")
renderControllerSettings()
}
@@ -1219,6 +1237,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
val returnToSettings = showPreviousMenu && controllerReturnToSettings && ::settingsPanel.isInitialized
val settingsShouldReturnToPause = settingsReturnToPause
pendingBindingAction = null
manualMappingIndex = null
bindingCaptureWaitForNeutral = false
draftProfile = null
clearControllerState()
if (returnToSettings) showSettingsPage()
@@ -1248,6 +1268,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
controllerSettingsPanel.addView(
body("${controller.name}\n档案:${profile.origin} · ${profile.fingerprint.take(12)};不使用临时 deviceId 持久化"),
)
controllerSettingsPanel.addView(
body("设置方法:点击一个动作,然后按下希望使用的手柄按键,或将摇杆/方向轴推到对应方向。修改完成后点击保存。"),
)
if (controllers.size > 1) {
controllerSettingsPanel.addView(Button(this).apply {
text = "切换到下一个手柄"
@@ -1256,11 +1279,42 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
selectedControllerId = controllers[(index + 1).mod(controllers.size)].deviceId
draftProfile = selectedControllerId?.let(controllerProfiles::get)
pendingBindingAction = null
manualMappingIndex = null
bindingCaptureWaitForNeutral = false
renderControllerSettings()
}
})
}
controllerSettingsPanel.addView(body(controllerSettingsMessage))
val hasUnsavedChanges = profile != controllerProfiles[deviceId]
controllerSettingsPanel.addView(
body(
controllerSettingsMessage +
if (hasUnsavedChanges) "\n● 有尚未保存的修改" else "\n当前设置已保存",
).apply {
setTextColor(Color.WHITE)
setPadding(dp(14), dp(10), dp(14), dp(10))
background = roundedBackground(Color.rgb(72, 55, 126), dp(10).toFloat())
},
)
controllerSettingsPanel.addView(Button(this).apply {
text = manualMappingIndex?.let { "逐项设置中:${it + 1}/${MANUAL_MAPPING_ACTIONS.size}" }
?: "开始逐项手动设置全部按键"
isEnabled = manualMappingIndex == null
setOnClickListener { startManualMapping() }
})
if (manualMappingIndex != null) {
controllerSettingsPanel.addView(LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
addView(Button(context).apply {
text = "跳过此项"
setOnClickListener { advanceManualMapping(skipped = true) }
})
addView(Button(context).apply {
text = "停止逐项设置"
setOnClickListener { stopManualMapping() }
})
})
}
controllerSettingsPanel.addView(Button(this).apply {
text = if (profile.swapAB) "A/B 交换:开" else "A/B 交换:关"
setOnClickListener {
@@ -1291,27 +1345,23 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
renderControllerSettings()
})
})
GameAction.entries.forEach { action ->
val description = profile.bindings[action].orEmpty().joinToString { binding ->
binding.displayName(KeyEvent::keyCodeToString) { axis ->
MotionEvent.axisToString(axis) ?: "AXIS_$axis"
}
}.ifEmpty { "未绑定" }
addMappingGroup("方向", listOf(GameAction.UP, GameAction.DOWN, GameAction.LEFT, GameAction.RIGHT), profile)
addMappingGroup(
"游戏按键",
listOf(GameAction.NES_A, GameAction.NES_B, GameAction.TURBO_A, GameAction.TURBO_B),
profile,
)
addMappingGroup(
"功能按键",
listOf(GameAction.START, GameAction.SELECT, GameAction.PAUSE_MENU, GameAction.FAST_FORWARD),
profile,
)
if (pendingBindingAction != null && manualMappingIndex == null) {
controllerSettingsPanel.addView(Button(this).apply {
text = "${action.label}:$description"
setOnClickListener {
clearControllerState()
pendingBindingAction = action
controllerSettingsMessage = "正在捕获“${action.label}”;按键、推动轴,或点击取消。"
renderControllerSettings()
}
})
}
if (pendingBindingAction != null) {
controllerSettingsPanel.addView(Button(this).apply {
text = "取消捕获"
text = "取消本次按键设置"
setOnClickListener {
pendingBindingAction = null
bindingCaptureWaitForNeutral = false
controllerSettingsMessage = "已取消捕获,当前映射未改变。"
clearControllerState()
renderControllerSettings()
@@ -1333,7 +1383,113 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
setOnClickListener { resetControllerProfile() }
})
})
focusFirstButton(controllerSettingsPanel)
if (pendingBindingAction == null) {
focusFirstButton(controllerSettingsPanel)
} else {
contentScroll.post { contentScroll.scrollTo(0, 0) }
}
}
private fun addMappingGroup(title: String, actions: List<GameAction>, profile: ControllerProfile) {
controllerSettingsPanel.addView(section(title))
actions.forEach { action ->
val currentBindings = profile.bindings[action].orEmpty()
val description = currentBindings.joinToString { binding ->
binding.displayName(KeyEvent::keyCodeToString) { axis ->
MotionEvent.axisToString(axis) ?: "AXIS_$axis"
}
}.ifEmpty { "未绑定" }
controllerSettingsPanel.addView(LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
addView(
Button(context).apply {
text = if (pendingBindingAction == action) {
"${action.label}\n等待手柄输入…"
} else {
"${action.label}\n当前:$description\n点击修改"
}
setOnClickListener { beginSingleBinding(action) }
},
LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f),
)
addView(Button(context).apply {
text = "清除"
isEnabled = currentBindings.isNotEmpty()
setOnClickListener { clearActionBinding(action) }
})
})
}
}
private fun beginSingleBinding(action: GameAction) {
clearControllerState()
manualMappingIndex = null
bindingCaptureWaitForNeutral = false
pendingBindingAction = action
controllerSettingsMessage = "正在设置“${action.label}”:请按一个手柄键,或推动一个摇杆/方向轴。"
renderControllerSettings()
}
private fun clearActionBinding(action: GameAction) {
val profile = draftProfile ?: return
clearControllerState()
manualMappingIndex = null
pendingBindingAction = null
bindingCaptureWaitForNeutral = false
draftProfile = profile.clearBinding(action)
controllerSettingsMessage = "已清除“${action.label}”的映射;点击保存后生效。"
renderControllerSettings()
}
private fun startManualMapping() {
clearControllerState()
manualMappingIndex = 0
bindingCaptureWaitForNeutral = false
pendingBindingAction = MANUAL_MAPPING_ACTIONS.first()
controllerSettingsMessage = manualMappingPrompt()
renderControllerSettings()
}
private fun advanceManualMapping(skipped: Boolean = false) {
val current = manualMappingIndex ?: return
val completedAction = MANUAL_MAPPING_ACTIONS[current]
val next = current + 1
bindingCaptureWaitForNeutral = !skipped && bindingCaptureWaitForNeutral
if (next >= MANUAL_MAPPING_ACTIONS.size) {
manualMappingIndex = null
pendingBindingAction = null
bindingCaptureWaitForNeutral = false
controllerSettingsMessage = "逐项手动设置已完成;请检查映射并点击保存。"
} else {
manualMappingIndex = next
pendingBindingAction = MANUAL_MAPPING_ACTIONS[next]
controllerSettingsMessage = (if (skipped) "已跳过“${completedAction.label}”。\n" else "") +
manualMappingPrompt()
}
clearControllerState()
renderControllerSettings()
}
private fun stopManualMapping() {
val changed = draftProfile != selectedControllerId?.let(controllerProfiles::get)
manualMappingIndex = null
pendingBindingAction = null
bindingCaptureWaitForNeutral = false
clearControllerState()
controllerSettingsMessage = if (changed) {
"已停止逐项设置;已完成的修改仍可保存。"
} else {
"已停止逐项设置,当前映射未改变。"
}
renderControllerSettings()
}
private fun manualMappingPrompt(): String {
val index = manualMappingIndex ?: return "选择动作后按一个手柄键或推动一个轴。"
val action = MANUAL_MAPPING_ACTIONS[index]
val neutralHint = if (bindingCaptureWaitForNeutral) "请先松开摇杆/方向轴,再设置下一项。\n" else ""
return neutralHint +
"第 ${index + 1}/${MANUAL_MAPPING_ACTIONS.size} 项:正在设置“${action.label}”。请按对应手柄键或推动对应轴。"
}
private fun focusFirstButton(container: ViewGroup) {
@@ -1369,7 +1525,12 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
.setMessage("该输入已用于 ${conflicts.joinToString { it.label }}。是否移除旧绑定并改为 ${action.label}?")
.setPositiveButton("替换") { _, _ -> finishBinding(profile, action, binding, replace = true) }
.setNegativeButton("取消") { _, _ ->
controllerSettingsMessage = "冲突未替换,映射保持不变。"
pendingBindingAction = action.takeIf { manualMappingIndex != null }
controllerSettingsMessage = if (manualMappingIndex != null) {
"冲突未替换。请换一个输入,或跳过当前项目。\n${manualMappingPrompt()}"
} else {
"冲突未替换,映射保持不变。"
}
clearControllerState()
renderControllerSettings()
}
@@ -1387,7 +1548,11 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
) {
val withoutConflict = if (replace) profile.removeBinding(binding, action) else profile
draftProfile = withoutConflict.replaceBinding(action, binding)
controllerSettingsMessage = "已捕获 ${action.label};点击保存后生效。"
if (manualMappingIndex != null) {
advanceManualMapping()
return
}
controllerSettingsMessage = "已设置 ${action.label};点击保存后生效。"
clearControllerState()
renderControllerSettings()
}
@@ -1395,9 +1560,12 @@ 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
pendingBindingAction = null
manualMappingIndex = null
bindingCaptureWaitForNeutral = false
clearControllerState()
controllerScope.launch {
val result = runCatching { profileStore.save(profile) }
@@ -1406,7 +1574,9 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
controllerSettingsMessage = if (result.isSuccess) {
"设置已保存;重连和重启后按设备特征恢复。"
} else {
"保存失败:${result.exceptionOrNull()?.message ?: "未知错误"}"
if (previousProfile == null) controllerProfiles.remove(deviceId)
else controllerProfiles[deviceId] = previousProfile
"保存失败:${result.exceptionOrNull()?.message ?: "未知错误"};修改仍保留在页面,可重试保存。"
}
draftProfile = profile
renderControllerSettings()
@@ -1422,6 +1592,8 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
controllerProfiles[deviceId] = defaultProfile
draftProfile = defaultProfile
pendingBindingAction = null
manualMappingIndex = null
bindingCaptureWaitForNeutral = false
clearControllerState()
controllerScope.launch {
val result = runCatching { profileStore.reset(identity) }
@@ -2306,6 +2478,20 @@ class MainActivity : ComponentActivity(), InputManager.InputDeviceListener {
}
companion object {
private val MANUAL_MAPPING_ACTIONS = listOf(
GameAction.UP,
GameAction.DOWN,
GameAction.LEFT,
GameAction.RIGHT,
GameAction.NES_A,
GameAction.NES_B,
GameAction.TURBO_A,
GameAction.TURBO_B,
GameAction.START,
GameAction.SELECT,
GameAction.PAUSE_MENU,
GameAction.FAST_FORWARD,
)
private const val EVENT_LINES = 30
private const val STATE_SESSION_ID = "active_session_id"
private const val STATE_GAME_HASH = "active_game_hash"
@@ -67,6 +67,11 @@ data class ControllerProfile(
bindings = bindings + (action to setOf(binding)),
)
fun clearBinding(action: GameAction): ControllerProfile = copy(
origin = ProfileOrigin.CUSTOM,
bindings = bindings + (action to emptySet()),
)
fun removeBinding(binding: InputBinding, except: GameAction): ControllerProfile = copy(
bindings = bindings.mapValues { (action, values) ->
if (action == except) values else values - binding
@@ -7,7 +7,7 @@ class BuildIdentityTest {
@Test
fun debugBuildUsesTheDocumentedIdentity() {
assertEquals("org.neslite.app.debug", BuildConfig.APPLICATION_ID)
assertEquals("0.9.6-debug", BuildConfig.VERSION_NAME)
assertEquals(9006, BuildConfig.VERSION_CODE)
assertEquals("0.9.7-debug", BuildConfig.VERSION_NAME)
assertEquals(9007, BuildConfig.VERSION_CODE)
}
}
@@ -54,4 +54,15 @@ class ControllerProfileTest {
assertEquals(swapped, decoded)
assertFalse(JSONObject(ControllerProfileJson.encode(swapped)).has("deviceId"))
}
@Test
fun manualMappingCanReplaceAndClearEachAction() {
val original = ControllerProfileResolver().resolve(identity)
val custom = InputBinding(BindingKind.KEY, 188)
val replaced = original.replaceBinding(GameAction.NES_A, custom)
assertEquals(setOf(custom), replaced.bindings[GameAction.NES_A])
assertEquals(ProfileOrigin.CUSTOM, replaced.origin)
assertTrue(replaced.clearBinding(GameAction.NES_A).bindings[GameAction.NES_A].orEmpty().isEmpty())
}
}