Files
nfsmw-online/app/src/main/java/com/ea/ironmonkey/MogaController.kt
T

118 lines
3.4 KiB
Kotlin

package com.ea.ironmonkey
import android.content.Context
import android.hardware.input.InputManager
import android.util.Log
import android.view.InputDevice
import androidx.activity.ComponentActivity
import com.bda.controller.ControllerListener
import com.bda.controller.KeyEvent
import com.bda.controller.MotionEvent
import com.bda.controller.StateEvent
object MogaController : ControllerListener {
external fun nativeOnKeyEvent(keyEvent: KeyEvent?)
external fun nativeOnMotionEvent(motionEvent: MotionEvent?)
external fun nativeOnStateEvent(stateEvent: StateEvent?)
override fun onKeyEvent(keyEvent: KeyEvent?) {
nativeOnKeyEvent(keyEvent)
}
override fun onMotionEvent(motionEvent: MotionEvent?) {
nativeOnMotionEvent(motionEvent)
}
override fun onStateEvent(stateEvent: StateEvent?) {
nativeOnStateEvent(stateEvent)
}
fun doForAllControllers(
action: (Int) -> Unit
){
val deviceIds = InputDevice.getDeviceIds()
deviceIds.forEach {
if(deviceIsController(it)) action(it)
}
}
infix fun Int.isFlag(flag: Int) = this and flag == flag
fun deviceIsController(deviceId: Int): Boolean {
val inputDevice = InputDevice.getDevice(deviceId) ?: return false
if(inputDevice.id == -1) return false
return (inputDevice.sources isFlag InputDevice.SOURCE_GAMEPAD) &&
(inputDevice.sources isFlag InputDevice.SOURCE_JOYSTICK)
}
fun registerControllerHandlers(
context: Context,
onInputDeviceAdded: (Int) -> Unit,
onInputDeviceRemoved: (Int) -> Unit,
onInputDeviceChanged: (Int) -> Unit = {},
){
val inputManager = context.getSystemService(ComponentActivity.INPUT_SERVICE) as InputManager
inputManager.registerInputDeviceListener(object : InputManager.InputDeviceListener {
var lastControllerId: Int = 0;
override fun onInputDeviceAdded(deviceId: Int) {
if(deviceIsController(deviceId)) {
lastControllerId = deviceId
onInputDeviceAdded(deviceId)
}
}
override fun onInputDeviceRemoved(deviceId: Int) {
if(deviceIsController(deviceId) || lastControllerId == deviceId) onInputDeviceRemoved(deviceId)
}
override fun onInputDeviceChanged(deviceId: Int) {
if(deviceIsController(deviceId)) onInputDeviceChanged(deviceId)
}
}, null)
}
fun createDisconnectEvent(deviceId: Int) = StateEvent(
System.currentTimeMillis(),
deviceId,
StateEvent.STATE_UNKNOWN,
StateEvent.ACTION_DISCONNECTED
)
fun createConnectEvent(deviceId: Int) = StateEvent(
System.currentTimeMillis(),
deviceId,
StateEvent.STATE_CONNECTION,
StateEvent.ACTION_CONNECTED
)
fun androidKeyEventToBda(keyEvent: android.view.KeyEvent) = KeyEvent(
keyEvent.eventTime,
keyEvent.deviceId,
keyEvent.keyCode,
keyEvent.action
)
fun androidMotionEventToBda(motionEvent: android.view.MotionEvent) = MotionEvent(
motionEvent.eventTime,
motionEvent.deviceId,
motionEvent.x,
motionEvent.y,
motionEvent.rawX,
motionEvent.rawY,
motionEvent.xPrecision,
motionEvent.yPrecision
)
}