diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index a187dc15b0..5f010b48d3 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -195,7 +195,6 @@
-
-
SessionPrefs.setOscMode(this, o); oscMode = o },
- onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() },
- onOpacity = { o -> ControllerPrefs.setOpacity(this, o); refreshController() },
- onSize = { v -> ControllerPrefs.setSize(this, v); refreshController() },
- onStickClick = { on -> ControllerPrefs.setStickClick(this, on); refreshController() },
- onAdaptiveSticks = { on -> ControllerPrefs.setAdaptiveSticks(this, on); refreshController() },
- onRumble = { on -> ControllerPrefs.setRumble(this, on); refreshController() },
- onDeadZone = { v -> ControllerPrefs.setDeadZone(this, v); refreshController() },
- onSteamButton = { on -> ControllerPrefs.setSteamButton(this, on); refreshController() },
- onQamButton = { on -> ControllerPrefs.setQamButton(this, on); refreshController() },
- onKeyboardButton = { on -> ControllerPrefs.setKeyboardButton(this, on); refreshController() },
- onSelectSteam = { on -> ControllerPrefs.setSelectSteam(this, on); refreshController() },
- onJoyConVr = { on -> ControllerPrefs.setJoyConVr(this, on); refreshController() },
- onEditLayout = { startActivity(Intent(this, ControllerEditorActivity::class.java)) },
- onResetLayout = { ControllerPrefs.resetAllLayouts(this); refreshController() },
onMapping = { showPerformance = false; showComponents = false; showMapping = true },
- onResetAll = { ControllerPrefs.resetAll(this); refreshController() },
),
),
page = page,
@@ -2136,13 +2118,7 @@ class FrontEndActivity : ComponentActivity() {
@Composable
private fun MappingHost() {
- val settings = controllerSettings ?: return
- ControllerMappingPage(
- mapping = settings.mapping,
- onPick = { id, target -> ControllerPrefs.setTarget(this, id, target); refreshController() },
- onReset = { ControllerPrefs.resetMapping(this); refreshController() },
- onBack = { showMapping = false },
- )
+ com.droiddeck.launcher.ui.InputSettingsPage(onBack = { showMapping = false })
}
private fun openComponents(focusContent: Boolean = true, tab: String? = null, gameKey: String? = null) {
@@ -2438,6 +2414,7 @@ class FrontEndActivity : ComponentActivity() {
SessionPrefs.setUnfoldedControlsWithController(this, on); unfoldedControlsWithController = on
},
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
+ onInputSettings = { showPerformance = false; showComponents = false; showMapping = true },
onBackHold = { on -> SessionPrefs.setBackHold(this, on); backHold = on },
onBackActionsInverted = { inverted ->
SessionPrefs.setBackActionsInverted(this, inverted)
diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
index 99fe2528ff..7df65cd605 100644
--- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
+++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt
@@ -76,12 +76,22 @@ import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.SessionClipboard
import com.droiddeck.launcher.input.OnScreenControls
+import com.droiddeck.launcher.input.InputRouter
+import com.droiddeck.launcher.input.InputOutput
+import com.droiddeck.launcher.input.InputCommand
+import com.droiddeck.launcher.input.InputProfiles
+import com.droiddeck.launcher.input.InputProfile
+import com.droiddeck.launcher.input.InputAction
+import com.droiddeck.launcher.input.InputRole
+import com.droiddeck.launcher.input.InputControl
+import com.droiddeck.launcher.input.InputMotion
+import com.droiddeck.launcher.input.HeldInput
+import com.droiddeck.launcher.input.DeckControls
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PhysicalShortcuts
import com.droiddeck.launcher.input.PhysicalShortcutRouter
import com.droiddeck.launcher.input.PadMouse
import com.droiddeck.launcher.input.PadState
-import com.droiddeck.launcher.input.ScreenKeys
import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold
import com.droiddeck.launcher.input.GestureTouchStreamGate
@@ -162,11 +172,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, alignment)
}
- private var unfoldedPanel: com.droiddeck.launcher.ui.DeckControlsPanel? = null
+ private var unfoldedPanel: com.droiddeck.launcher.ui.InputSurfaceView? = null
private lateinit var sessionRoot: FrameLayout
+ private var inputRouter: InputRouter? = null
+ private var physicalInputBindings: com.droiddeck.launcher.input.PhysicalInputBindings? = null
+ private var inputSettingsOpen by mutableStateOf(false)
+ @Volatile private var inputUsesLocalActions = false
+ private var inputUsesPointer = false
+ private var inputProfile = InputProfile.defaults(InputProfile.GAME)
+ private val inputMotion = InputMotion { inputRouter }
+ private val heldKeys = HeldInput { code, down -> WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) }
+ private val heldButtons = HeldInput(::sendSceneButton)
+ private val inputOutput = object : InputOutput {
+ override fun key(code: Int, down: Boolean) { heldKeys.set(4, code, down) }
+ override fun button(code: Int, down: Boolean) { heldButtons.set(4, code, down) }
+ override fun pointer(dx: Float, dy: Float) {
+ if (Looper.myLooper() == Looper.getMainLooper()) moveInputPointer(dx, dy)
+ else uiHandler.post {
+ if (resumed && !SessionState.suspended && !pipUi && !drawerOpen && !inputSettingsOpen)
+ moveInputPointer(dx, dy)
+ }
+ }
+ override fun scroll(steps: Int) { sendSceneWheel(steps) }
+ override fun scrollHorizontal(steps: Int) { sendSceneWheel(steps, horizontal = true) }
+ override fun requestMotion() { inputMotion.request() }
+ override fun command(command: InputCommand) {
+ uiHandler.post {
+ if (!resumed || isDestroyed || pipUi || SessionState.suspended) return@post
+ when (command) {
+ InputCommand.MENU -> { releasePads(); drawerOpen = true }
+ InputCommand.KEYBOARD -> if (secondScreenPresentation?.showKeyboard() != true) togglePcKeyboard()
+ InputCommand.STEAM -> tapSteamButton()
+ InputCommand.QUICK_ACCESS -> tapQam()
+ }
+ }
+ }
+ }
private val guestKeysDown = mutableSetOf()
private val guestButtonsDown = mutableMapOf()
- private val trackpadButtonsDown = mutableSetOf()
private lateinit var surfaceView: SurfaceView
private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState
@@ -177,7 +220,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null
private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null
private var padMotion: com.droiddeck.launcher.input.PadMotion? = null
- private var resumed = false
+ private var resumed by mutableStateOf(false)
private val deckPadListener: () -> Unit = { uiHandler.post { updatePadMotion(); openDeckRing("deck pad changed"); applyUnfoldedControls() } }
private fun openDeckRing(why: String) {
@@ -196,6 +239,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private var steamController: SteamControllerBle? = null
private var onScreenControls: OnScreenControls? = null
+ private var bottomInputControls: OnScreenControls? = null
+ private var primaryInputLayout: com.droiddeck.launcher.input.SavedInputLayout? = null
+ private var secondaryInputLayout by mutableStateOf(null)
private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null
private var steamTouchAvailable by mutableStateOf(false)
private val steamTouchRetry = Runnable { updateOnScreenControls() }
@@ -230,19 +276,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var directHoldBehavior by mutableStateOf(com.droiddeck.launcher.input.TouchGestureConfig.MOUSE_BEHAVIOR_CLICK)
private var relativeMouseMode by mutableIntStateOf(0)
@Volatile private var appliedRelativeMouseMode: Int? = null
- private var screenKeyPickerOpen by mutableStateOf(false)
- private var screenKeyBind: List? = null
- private var screenKeyDir: Int? = null
- private var screenKeyTextFocus = false
- private val appTextFocus get() = screenKeyTextFocus || wowChat.request != null
+ private val appTextFocus get() = wowChat.request != null
private val wowChat by lazy { com.droiddeck.launcher.ui.WowChat(this, ::sendWowChat, ::cancelWowChat, ::readGameField) }
private var wowChatBottom: SecondScreenPresentation? = null
private var wowChatOnTop by mutableStateOf(false)
- private var screenKeyEdit by mutableStateOf(null)
- private var screenLayoutsOpen by mutableStateOf(false)
- private var screenKeysShown by mutableStateOf(true)
- private var screenLayoutNames by mutableStateOf(listOf())
- private var screenKeys: ScreenKeys? = null
private var recognizedGesture by mutableStateOf(null)
private var gesturePointerX = 0f
private var gesturePointerY = 0f
@@ -339,7 +376,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
holds = { backHold },
)
private val mouseBackInput = com.droiddeck.launcher.input.MouseBackInput(
- sendRight = { down -> sendSceneButton(PointerGestures.BTN_RIGHT, down) },
+ sendRight = { down -> heldButtons.set(32, PointerGestures.BTN_RIGHT, down) },
mouseAttached = ::mouseAttached,
)
private var drawerDirectionKey = KeyEvent.KEYCODE_UNKNOWN
@@ -598,6 +635,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
backQamInput.onDeviceRemoved(deviceId)
mouseBackInput.onDeviceRemoved(deviceId)
joyConVr?.refresh()
+ physicalInputBindings?.disconnected(deviceId)
padBridge?.onDeviceRemoved(deviceId)
if (::padMouse.isInitialized) padMouse.reset()
refreshControls()
@@ -692,9 +730,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val bridge = PadBridge(File(LinuxRuntime.sessionRoot(this), "dev/input"))
bridge.setStickDeadZone(ControllerPrefs.deadZone(this))
- bridge.setSelectSteam(ControllerPrefs.read(this).selectSteam)
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
padBridge = bridge
+ inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it) }
+ refreshInputProfile()
bridge.setOnChordInput(backQamInput::onChordInput)
SessionState.padBridge = bridge
if (Build.VERSION.SDK_INT >= 31) {
@@ -708,20 +747,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
joyConVr = vr
}
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
- steamController = SteamControllerBle(this).also { it.start() }
+ steamController = SteamControllerBle(this, inputRouter).also { it.start() }
padMotion = com.droiddeck.launcher.input.PadMotion(this) {
@Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
}
SessionState.deckPadListener = deckPadListener
openDeckRing("activity created")
- bridge.setOnPlayerInput {
- lastPadInputMs = android.os.SystemClock.uptimeMillis()
- uiHandler.removeCallbacks(cursorHide)
- mouseOwnsCursor = false
- cursorVisible = false
- }
- onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { controls ->
+ bridge.setOnPlayerInput(::onPadInput)
+ onScreenControls = OnScreenControls(this, bridge).also { controls ->
+ controls.updateLayout(primaryInputLayout)
controls.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
event.offsetLocation(controls.left - surfaceView.left.toFloat(), controls.top - surfaceView.top.toFloat())
@@ -729,20 +764,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
root.addView(controls)
}
- screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this)
- screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys ->
- keys.onTouchMiss = miss@{ event ->
- if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
- event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat())
- onTouchEvent(event)
- }
- keys.onAdd = { screenKeyPickerOpen = true }
- keys.onSelect = { codes -> screenKeyEdit = screenKeys?.stateOf(codes) }
- keys.onEditingChanged = { touchEditorChanged(); if (!it) screenKeyEdit = null }
- keys.steamStyle = { steamTouchControls?.style }
- keys.visibility = if (screenKeysShown) View.VISIBLE else View.GONE
- root.addView(keys)
- }
keyboard = KeyboardHost(this).also { host ->
host.onImeChanged = { updateDesktopKeyboardButton() }
root.addView(host)
@@ -882,6 +903,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (pipUi) return
when {
::loading.isInitialized && loading.ended -> finish()
+ inputSettingsOpen -> inputSettingsOpen = false
drawerOpen -> drawerOpen = false
achievementsOpen -> closeAchievements()
pcKeyboardOpen -> pcKeyboardOpen = false
@@ -906,7 +928,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
androidx.compose.runtime.DisposableEffect(Unit) {
onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) }
}
- androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi, bottomOutputActive) { updatePointerCapture() }
+ androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, inputSettingsOpen, pipUi, bottomOutputActive) { updatePointerCapture() }
androidx.compose.runtime.LaunchedEffect(bottomOutputActive) { hud.setHidden(pipUi || bottomOutputActive) }
androidx.compose.runtime.LaunchedEffect(pipUi) {
hud.setHidden(pipUi || bottomOutputActive)
@@ -1011,15 +1033,28 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
}
}
- LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
- if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
+ LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
+ updateOnScreenControls()
+ padBridge?.setInputEnabled(resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
+ if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || appTextFocus || SessionState.suspended) {
backQamInput.cancel()
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this@SessionActivity)
cancelTouchGestures()
- screenKeys?.stopEditing()
}
}
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
+ if (inputSettingsOpen) com.droiddeck.launcher.ui.InputSettingsDialog(
+ onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() },
+ onChanged = {
+ controllerSettings = ControllerPrefs.read(this@SessionActivity)
+ oscMode = SessionPrefs.oscMode(this@SessionActivity)
+ padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity))
+ joyConVr?.refresh()
+ onScreenControls?.reload()
+ refreshInputProfile()
+ refreshControls()
+ },
+ )
LaunchedEffect(Unit) {
val root = LinuxRuntime.rootDir(this@SessionActivity)
while (true) {
@@ -1052,84 +1087,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onDismiss = { gestureSettingsOpen = false },
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
)
- if (screenKeyPickerOpen) {
- val dir = screenKeyDir
- com.droiddeck.launcher.ui.ScreenKeyPicker(
- initial = if (dir != null) {
- listOfNotNull((screenKeyEdit?.codes?.getOrNull(dir) ?: 0).takeIf { it != 0 })
- } else {
- screenKeyBind ?: emptyList()
- },
- onDismiss = { screenKeyPickerOpen = false; screenKeyBind = null; screenKeyDir = null },
- onAdd = { codes ->
- val bind = screenKeyBind
- if (dir != null && bind != null) {
- screenKeys?.setDirection(bind, dir, codes.lastOrNull() ?: 0)?.let { screenKeyEdit = it }
- } else if (bind != null) {
- screenKeys?.setCodes(bind, codes)?.let { screenKeyEdit = it }
- } else {
- screenKeys?.add(codes)
- screenKeyEdit = screenKeys?.stateOf(codes)
- }
- screenKeyPickerOpen = false
- screenKeyBind = null
- screenKeyDir = null
- },
- )
- }
- screenKeyEdit?.let { key ->
- com.droiddeck.launcher.ui.ScreenKeyEditor(
- codes = key.codes, keyY = key.y,
- size = key.size, opacity = key.opacity, shape = key.shape, toggle = key.toggle,
- labels = key.labels,
- text = key.text, hasImage = key.image.isNotEmpty(),
- onResize = { screenKeys?.resize(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
- onOpacity = { screenKeys?.setOpacity(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
- onShape = { screenKeys?.setShape(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
- onToggle = { on -> screenKeys?.setToggle(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) },
- onLabels = { on -> screenKeys?.setLabels(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) },
- onDirection = { index -> screenKeyBind = key.codes; screenKeyDir = index; screenKeyPickerOpen = true },
- onText = { screenKeys?.setText(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
- onImage = { screenKeys?.setImage(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
- onClearImage = { screenKeys?.setImage(key.codes, ""); screenKeyEdit = screenKeys?.stateOf(key.codes) },
- onBind = { screenKeyBind = key.codes; screenKeyDir = null; screenKeyPickerOpen = true },
- onTextFocus = { screenKeyTextFocus = true; keyboard?.hide() },
- onTextBlur = { screenKeyTextFocus = false },
- onRemove = { screenKeys?.remove(key.codes); screenKeyEdit = null },
- onDismiss = { screenKeyEdit = null; screenKeyTextFocus = false; screenKeys?.deselect() },
- )
- }
- if (screenLayoutsOpen) com.droiddeck.launcher.ui.ScreenLayoutPanel(
- layouts = screenLayoutNames,
- onSave = { name ->
- screenKeys?.let { keys ->
- com.droiddeck.launcher.input.ControllerPrefs.saveScreenLayout(this@SessionActivity, name, keys.export())
- }
- screenLayoutNames = layoutNames()
- },
- onLoad = { name ->
- com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this@SessionActivity)[name]?.let { screenKeys?.load(it) }
- screenLayoutsOpen = false
- },
- onDelete = { name ->
- com.droiddeck.launcher.input.ControllerPrefs.deleteScreenLayout(this@SessionActivity, name)
- screenLayoutNames = layoutNames()
- },
- onImport = { text ->
- val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels
- val keys = com.droiddeck.launcher.input.importScreenLayout(text, width, resources.displayMetrics.density)
- if (keys != null) {
- screenKeys?.load(com.droiddeck.launcher.input.ControllerPrefs.encodeScreenKeys(keys))
- screenLayoutsOpen = false
- }
- },
- exportText = {
- val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels
- val keys = com.droiddeck.launcher.input.ControllerPrefs.decodeScreenKeys(screenKeys?.export().orEmpty())
- com.droiddeck.launcher.input.exportScreenLayout(keys, width, resources.displayMetrics.density)
- },
- onDismiss = { screenLayoutsOpen = false },
- )
androidx.compose.runtime.LaunchedEffect(drawerOpen) {
if (drawerOpen) {
syncLossless()
@@ -1170,7 +1127,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (pcKeyboardOpen || drawerOpen || achievementsOpen) padMouse.reset()
}
if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard(
- sendKey = { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) },
+ sendKey = { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down, 32) },
onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() },
onClose = { pcKeyboardOpen = false },
)
@@ -1228,6 +1185,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionDrawer(drawerOpen || (docked && drawerPinned), drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, docked = docked,
backRequest = drawerBackRequests, onLayerChange = { drawerLayerOpen = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM,
+ desktop = SessionState.mode == SessionService.MODE_DESKTOP,
systemPowerVr = com.droiddeck.launcher.gpu.SystemVulkanDriver.usesDefault(
SessionPrefs.linuxDriver(this@SessionActivity)),
direct = noSteamSession(),
@@ -1329,9 +1287,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onWowChat = wowChat::choose,
controller = controllerSettings,
onRumble = { on -> updateControllerPrefs { ControllerPrefs.setRumble(this@SessionActivity, on) } },
- onSteamButton = { on -> updateControllerPrefs { ControllerPrefs.setSteamButton(this@SessionActivity, on) } },
- onQamButton = { on -> updateControllerPrefs { ControllerPrefs.setQamButton(this@SessionActivity, on) } },
- onKeyboardButton = { on -> updateControllerPrefs { ControllerPrefs.setKeyboardButton(this@SessionActivity, on) } },
onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null,
onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null,
onAchievements = achievementsInFront?.let { { drawerOpen = false; achievementsOpen = true } },
@@ -1399,6 +1354,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionService.suspendPolicyChanged(this@SessionActivity)
},
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
+ onInputSettings = { releasePads(); drawerOpen = false; inputSettingsOpen = true },
+ onInputSelection = { releasePads(); refreshInputProfile() },
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
touchActive = drawerTouchMode(),
directHoldBehavior = directHoldBehavior,
@@ -1414,19 +1371,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
relativeMouseMode = mode
setRelativeMouse(mode)
},
- onScreenKeys = { if (screenKeysShown) { drawerOpen = false; screenKeys?.startEditing() } },
- screenKeysShown = screenKeysShown,
- onScreenKeysShown = { shown ->
- screenKeysShown = shown
- com.droiddeck.launcher.input.ControllerPrefs.setScreenKeysShown(this@SessionActivity, shown)
- screenKeys?.stopEditing()
- screenKeys?.visibility = if (shown) View.VISIBLE else View.GONE
- },
- onScreenLayouts = {
- drawerOpen = false
- screenLayoutNames = layoutNames()
- screenLayoutsOpen = true
- },
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = { mode ->
if (docked) drawerOpen = false
@@ -1475,7 +1419,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
},
onClose = { drawerOpen = false },
- onDismissScreen = if (docked) ({ selectSecondScreenMode(SecondScreenMode.NONE) }) else null,
components = drawerComponents,
onComponentsRefresh = {
refreshDrawerComponents()
@@ -1519,10 +1462,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun sendSteamGuide() {
drawerOpen = false
- padBridge?.applyTouch { state -> state.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
- uiHandler.postDelayed({
- padBridge?.applyTouch { state -> state.press(com.droiddeck.launcher.input.PadState.GUIDE, false) }
- }, 90)
+ padBridge?.triggerSteamMenu()
}
@androidx.compose.runtime.Composable
@@ -1564,12 +1504,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun switchVrSticks() {
- val chord = { down: Boolean -> padBridge?.applyTouch { state ->
- state.press(com.droiddeck.launcher.input.PadState.L3, down)
- state.press(com.droiddeck.launcher.input.PadState.R3, down)
- } }
- chord(true)
- uiHandler.postDelayed({ chord(false) }, 120)
+ padBridge?.triggerVrStickSwitch()
}
private fun triggerSteamQam() {
@@ -1602,6 +1537,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
drawerOpen = false
keyboard?.hide()
onScreenControls?.releaseAll()
+ bottomInputControls?.releaseAll()
pcKeyboardOpen = !pcKeyboardOpen
}
@@ -1986,7 +1922,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (CompositorHost.isStarted) {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
listOf(PointerGestures.BTN_LEFT, PointerGestures.BTN_RIGHT, PointerGestures.BTN_MIDDLE).forEach {
- WaylandCompositor.nativeSendSceneInput(3, it, 0)
+ heldButtons.set(1, it, false)
}
}
if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false
@@ -2532,6 +2468,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun releasePads() {
+ inputMotion.stop()
+ physicalInputBindings?.release()
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
backQamInput.cancel()
padBridge?.releaseAll()
@@ -2657,7 +2595,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.mode == SessionService.MODE_STEAM && SessionState.running &&
SessionState.firstFrameSeen && !SessionState.suspended && !ended &&
!pipUi && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
- !gestureSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus()
+ !gestureSettingsOpen && !inputSettingsOpen && !appTextFocus && window.decorView.hasWindowFocus()
if (steamVolume) {
val audio = getSystemService(android.media.AudioManager::class.java)
if (com.droiddeck.launcher.input.SteamVolumeKeys.dispatch(event, !audio.isVolumeFixed) { direction ->
@@ -2667,14 +2605,40 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchKeyEvent(event)
}
}
+ if (appTextFocus) return super.dispatchKeyEvent(event)
+ if (!pipUi) {
+ if (physicalInputBindings?.onKey(event, resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
+ !inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true
+ if (physicalShortcuts.onKey(
+ event,
+ enabled = resumed && SessionState.running && !SessionState.suspended &&
+ !(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
+ !(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
+ (event.deviceId to event.keyCode) !in resumeKeysDown &&
+ !(::loading.isInitialized && (loading.visible || loading.ended)) &&
+ !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen,
+ steam = SessionState.mode == SessionService.MODE_STEAM,
+ ) { action ->
+ pendingBackAction?.let(uiHandler::removeCallbacks)
+ pendingBackAction = null
+ drawerControllerActive = true
+ Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}")
+ when (action) {
+ PhysicalShortcuts.Action.STEAM -> sendSteamGuide()
+ PhysicalShortcuts.Action.QAM -> triggerSteamQam()
+ PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen
+ }
+ }) return true
+ }
if (event.keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
Log.i(TAG, String.format(java.util.Locale.ROOT, "back key device=%d (%s) source=0x%x flags=0x%x",
event.deviceId, event.device?.name, event.source, event.flags))
}
- val mouseToGuest = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen &&
+ val mouseToGuest = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen &&
!SessionState.suspended && !(::loading.isInitialized && (loading.visible || loading.ended))
if (mouseBackInput.onKeyEvent(event, mouseToGuest)) return true
val backToQam = !pipUi && !appTextFocus && !drawerOpen && !pcKeyboardOpen && !achievementsOpen &&
+ !inputSettingsOpen && !gestureSettingsOpen &&
SessionState.mode == SessionService.MODE_STEAM && SessionState.running && SessionState.firstFrameSeen &&
!SessionState.suspended && padBridge?.canHoldQam() == true
if (backQamInput.onKeyEvent(event, backToQam)) {
@@ -2683,30 +2647,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true
}
if (pipUi) return true
- if (appTextFocus) return super.dispatchKeyEvent(event)
- if (physicalShortcuts.onKey(
- event,
- enabled = SessionState.running && !SessionState.suspended &&
- !(drawerOpen && event.keyCode == KeyEvent.KEYCODE_BUTTON_A) &&
- !(drawerOpen && PhysicalShortcuts.isDrawerNavigationKey(event)) &&
- (event.deviceId to event.keyCode) !in resumeKeysDown &&
- !(::loading.isInitialized && (loading.visible || loading.ended)) &&
- !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen,
- steam = SessionState.mode == SessionService.MODE_STEAM,
- ) { action ->
- pendingBackAction?.let(uiHandler::removeCallbacks)
- pendingBackAction = null
- drawerControllerActive = true
- Log.i(TAG, "physical shortcut ${action.name} device=${event.deviceId} key=${event.keyCode} scan=${event.scanCode}")
- when (action) {
- PhysicalShortcuts.Action.STEAM -> sendSteamGuide()
- PhysicalShortcuts.Action.QAM -> triggerSteamQam()
- PhysicalShortcuts.Action.DROIDDECK -> drawerOpen = !drawerOpen
- }
- }) return true
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad)
val fromController = PadBridge.isControllerKeyEvent(event)
+ if (fromController && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
+ padBridge?.setInputEnabled(false)
+ padBridge?.onKeyEvent(event)
+ }
if (fromController && event.action == KeyEvent.ACTION_DOWN) {
if (drawerOpen && !drawerControllerActive) focusDrawer()
drawerControllerActive = true
@@ -2772,7 +2719,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return true
}
- if ((pcKeyboardOpen || achievementsOpen) && fromController) return super.dispatchKeyEvent(event)
+ if ((pcKeyboardOpen || achievementsOpen || inputSettingsOpen) && fromController) return super.dispatchKeyEvent(event)
if (!fromController && event.keyCode != KeyEvent.KEYCODE_BACK && sendToTopDesktop(event)) return true
if (joyConVr?.onKeyEvent(event) == true) return true
if (fromController && event.keyCode != KeyEvent.KEYCODE_BACK && padMouseMode() && padMouse.onKey(event)) return true
@@ -2782,7 +2729,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (CompositorHost.isStarted && keyboardKey && !fromController) {
val down = event.action == KeyEvent.ACTION_DOWN
if (down && event.repeatCount > 0) return true
- if (com.droiddeck.launcher.input.GuestKeys.send(event, ::sendGuestKey)) return true
+ val owner = if (event.deviceId <= 0) 16 else 8
+ if (com.droiddeck.launcher.input.GuestKeys.send(event) { code, pressed -> sendGuestKey(code, pressed, owner) }) return true
}
return super.dispatchKeyEvent(event)
}
@@ -2808,6 +2756,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
if (pipUi) return true
notePress(event)
+ if (PadBridge.isControllerMotionEvent(event) && (drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || gestureSettingsOpen || SessionState.suspended)) {
+ padBridge?.setInputEnabled(false)
+ padBridge?.onMotionEvent(event)
+ }
if (drawerOpen && PadBridge.isControllerMotionEvent(event)) {
if (!drawerControllerActive) focusDrawer()
drawerControllerActive = true
@@ -2819,7 +2771,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true
}
if (drawerDirectionKey != KeyEvent.KEYCODE_UNKNOWN) releaseDrawerDirection()
- if ((pcKeyboardOpen || achievementsOpen) && PadBridge.isControllerMotionEvent(event)) return super.dispatchGenericMotionEvent(event)
+ if ((pcKeyboardOpen || achievementsOpen || inputSettingsOpen) && PadBridge.isControllerMotionEvent(event)) return super.dispatchGenericMotionEvent(event)
if (joyConVr?.onMotionEvent(event) == true) return true
if (PadBridge.isControllerMotionEvent(event) && padMouseMode() && padMouse.onMotion(event)) return true
if (padBridge?.onMotionEvent(event) == true) return true
@@ -2849,7 +2801,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return onScreenControls?.let { takes(it, it::takesTouchAt) } == true ||
steamTouchControls?.let { takes(it, it::takesTouchAt) } == true ||
- screenKeys?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true
}
@@ -2977,8 +2928,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (secondScreenMode == SecondScreenMode.NONE) closeSecondScreen(reset = false) else updateKeyboardRoute()
}
- private fun layoutNames(): List =
- com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this).keys.sorted()
private val relativeMouseRequests = java.util.concurrent.Executors.newSingleThreadExecutor { runnable ->
Thread(runnable, "relative-mouse").apply { isDaemon = true }
@@ -3048,7 +2997,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} else moveTo(gesturePointerX + dx, gesturePointerY + dy)
}
override fun button(code: Int, down: Boolean) {
- sendSceneButton(code, down)
+ heldButtons.set(16, code, down)
}
override fun prepareRelativePan() {
if (pointerLocked) return
@@ -3057,7 +3006,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun key(code: Int, down: Boolean) {
if (down) gestureKeysDown.add(code) else gestureKeysDown.remove(code)
- if (code !in guestKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
+ heldKeys.set(2, code, down)
}
override fun wheel(steps: Int) { sendSceneWheel(steps) }
override fun showKeyboard() { uiHandler.post { touchscreenGestures.cancel(); togglePcKeyboard() } }
@@ -3074,7 +3023,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {
if (!pointerLocked) movePointer(x, y)
- sendSceneButton(button, pressed)
+ heldButtons.set(1, button, pressed)
}
override fun onWheel(steps: Int) { sendSceneWheel(steps) }
override fun onScroll(dx: Float, dy: Float) = fingerScroll(dx, dy)
@@ -3084,9 +3033,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return true
}
override fun onZoom(steps: Int) {
- WaylandCompositor.nativeSendKey(KEY_LEFTCTRL, 1)
+ heldKeys.set(128, KEY_LEFTCTRL, true)
sendSceneWheel(steps)
- WaylandCompositor.nativeSendKey(KEY_LEFTCTRL, 0)
+ heldKeys.set(128, KEY_LEFTCTRL, false)
}
override fun onLongPress() {
@Suppress("DEPRECATION")
@@ -3103,7 +3052,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cursorVisible = false
}
override fun onButton(button: Int, pressed: Boolean) {
- WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
+ heldButtons.set(1, button, pressed)
}
override fun onScroll(dx: Float, dy: Float) {
val rect = pointerSurfaceRect() ?: return
@@ -3143,6 +3092,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun padMouseMode(): Boolean {
val now = android.os.SystemClock.uptimeMillis()
+ if (inputUsesLocalActions) {
+ if (padMouseOn) padMouse.reset()
+ padMouseOn = false
+ return false
+ }
if (now - padMouseCheckedAt < PAD_MOUSE_CHECK_MS) return padMouseOn
padMouseCheckedAt = now
val on = !pointerLocked && EpicClient.launcherFocused(this) && !EpicClient.playing(this)
@@ -3198,6 +3152,30 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
showCursor(cx, cy, fromMouse)
}
+ private fun moveInputPointer(dx: Float, dy: Float) {
+ if (pointerLocked) {
+ sendSceneDelta(dx, dy)
+ cursorVisible = false
+ return
+ }
+ val rect = drawnRect() ?: return
+ val position = cursorPos
+ val x = if (position.x >= 0f) position.x.coerceIn(rect.left, rect.right) else rect.centerX()
+ val y = if (position.y >= 0f) position.y.coerceIn(rect.top, rect.bottom) else rect.centerY()
+ val out = SessionState.outputSize
+ movePointer(x + dx * rect.width() / out.first, y + dy * rect.height() / out.second)
+ // Make frame-callback updates visible to drawing before this frame's traversal.
+ androidx.compose.runtime.snapshots.Snapshot.sendApplyNotifications()
+ }
+
+ private fun onPadInput() {
+ if (inputUsesPointer && !pointerLocked) return
+ lastPadInputMs = android.os.SystemClock.uptimeMillis()
+ uiHandler.removeCallbacks(cursorHide)
+ mouseOwnsCursor = false
+ cursorVisible = false
+ }
+
private fun moveCapturedMouse(dx: Float, dy: Float) {
val rect = drawnRect() ?: return
val scale = sceneScale(rect)
@@ -3217,8 +3195,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cursorResyncIdle = 0
if (fromMouse || !touchDrivesPointer()) uiHandler.postDelayed(cursorResync, 60)
if (clientHidesCursor) { cursorVisible = false; return }
- if (!fromMouse && directTouchCursorHidden()) { cursorVisible = false; return }
- if (android.os.SystemClock.uptimeMillis() - lastPadInputMs < CURSOR_PAD_HOLD_MS) return
+ if (!inputUsesPointer && !fromMouse && directTouchCursorHidden()) { cursorVisible = false; return }
+ if (!inputUsesPointer && android.os.SystemClock.uptimeMillis() - lastPadInputMs < CURSOR_PAD_HOLD_MS) return
cursorVisible = true
uiHandler.removeCallbacks(cursorHide)
if (!fromMouse && SessionState.mode == SessionService.MODE_STEAM && SessionState.steamUi != "desktop") uiHandler.postDelayed(cursorHide, 2500)
@@ -3335,8 +3313,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
showSecondScreen(mode)
}
- private fun showSecondScreen(mode: SecondScreenMode) {
+ private fun showSecondScreen(requested: SecondScreenMode) {
if (pipUi || !started) return
+ val mode = if (requested == SecondScreenMode.DECK_CONTROLS || requested == SecondScreenMode.KEYBOARD_TRACKPAD) {
+ val remembered = SessionPrefs.secondScreenPanel(this)
+ if (remembered == requested.id) {
+ val desktop = SessionState.mode == SessionService.MODE_DESKTOP
+ val key = if (desktop) InputProfile.DESKTOP else InputProfile.GAME
+ val preset = if (requested == SecondScreenMode.DECK_CONTROLS) com.droiddeck.launcher.input.InputStockLayouts.DECK else com.droiddeck.launcher.input.InputStockLayouts.TRACKPAD
+ runCatching {
+ com.droiddeck.launcher.input.InputLibraries.update(this) { library ->
+ val selection = library.selections[key]
+ if (selection?.profileSelected == true || selection?.parts?.containsKey(InputRole.SECONDARY) == true) library
+ else library.selectPart(desktop, InputRole.SECONDARY, preset)
+ }
+ }.onSuccess {
+ refreshInputProfile()
+ SessionPrefs.setSecondScreenPanel(this, SecondScreenMode.CUSTOM_CONTROLS.id)
+ }.onFailure {
+ Log.w(TAG, "could not migrate the saved second-screen selection", it)
+ }
+ }
+ SecondScreenMode.CUSTOM_CONTROLS
+ } else requested
val target = displayManager.getDisplay(selectedSecondScreenDisplay)
if (target == null || !target.isValid || (target.flags and Display.FLAG_PRESENTATION) == 0) {
closeSecondScreen(reset = false)
@@ -3370,9 +3369,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun secondScreenPresentation(target: Display) = SecondScreenPresentation(
this, target,
- sendPointer = ::moveSecondScreenPointer,
- sendButton = ::sendTrackpadButton,
- sendWheel = { steps -> WaylandCompositor.nativeSendSceneInput(4, steps, 0) },
onSteamMenu = ::tapSteamButton,
onQam = ::tapQam,
onClose = ::closeBottomPanel,
@@ -3486,12 +3482,39 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun tapSteamButton() {
- if (SessionState.mode == SessionService.MODE_STEAM) {
- padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
- Handler(Looper.getMainLooper()).postDelayed({
- padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, false) }
- }, 90)
- }
+ if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerSteamMenu()
+ }
+
+ fun inputEditorDisplay(role: InputRole): Display? {
+ val main = window.decorView.display
+ if (role == InputRole.PRIMARY) return bottomGame?.display ?: main
+ if (bottomGame != null) return main
+ return displayManager.getDisplay(selectedSecondScreenDisplay)
+ ?: secondScreenDisplays.firstOrNull()?.let { displayManager.getDisplay(it.id) }
+ }
+
+ private fun refreshInputProfile() {
+ val library = com.droiddeck.launcher.input.InputLibraries.read(this)
+ val desktop = loadingMode() == SessionService.MODE_DESKTOP
+ inputProfile = library.compileActive(desktop)
+ primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
+ secondaryInputLayout = library.activeLayout(desktop, InputRole.SECONDARY)
+ inputUsesLocalActions = InputControl.padControls.any { inputProfile.action(InputRole.PHYSICAL, it) !is InputAction.Native }
+ inputUsesPointer = inputProfile.bindings.values.any { bindings ->
+ bindings.values.any { it is InputAction.Pointer || it is InputAction.MouseButton || it is InputAction.Scroll }
+ } || inputProfile.elements.values.any { bindings ->
+ bindings.values.any { it is InputAction.Pointer || it is InputAction.MouseButton || it is InputAction.Scroll }
+ } || inputProfile.clicks.values.any { bindings -> bindings.values.any { it is InputAction.MouseButton } }
+ || inputProfile.keys.any { it.action is InputAction.MouseButton }
+ physicalInputBindings?.configure(inputProfile.keys)
+ padBridge?.setInputProfile(inputProfile)
+ DeckControls.refresh()
+ onScreenControls?.updateLayout(primaryInputLayout)
+ bottomInputControls?.updateLayout(primaryInputLayout)
+ unfoldedPanel?.updateCustomLayout(primaryInputLayout?.elements.orEmpty())
+ unfoldedPanel?.updateStyle(primaryInputLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
+ updateOnScreenPad()
+ secondScreenPresentation?.refreshControls()
}
private fun tapQam() {
@@ -3513,7 +3536,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun refreshControls() {
applyUnfoldedControls()
updateOnScreenControls()
- screenKeys?.refreshAppearance()
}
private fun controlsBelowWanted(): Boolean {
@@ -3536,19 +3558,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
else "unfolded controls: game full screen")
}
var panel = unfoldedPanel
- if (panel != null && panel.deckControls != SessionState.deckPad) {
- sessionRoot.removeView(panel)
- unfoldedPanel = null
- panel = null
- }
if (!wanted) {
if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() }
return
}
if (panel == null) {
- panel = com.droiddeck.launcher.ui.DeckControlsPanel(this, onClose = { chooseUnfoldedControls(false) },
- onSteamMenu = ::tapSteamButton, onQam = ::tapQam, pad = padBridge,
- portraitDock = !com.droiddeck.launcher.session.SessionDisplay.foldable(this), onMenu = { drawerOpen = true })
+ panel = com.droiddeck.launcher.ui.InputSurfaceView(this, padBridge, primaryInputLayout?.elements.orEmpty(), InputRole.PRIMARY,
+ primaryInputLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1)
unfoldedPanel = panel
updateOnScreenControls()
@@ -3556,17 +3572,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
panel.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
}
- private fun moveSecondScreenPointer(x: Float, y: Float, width: Float, height: Float) {
- if (width <= 0f || height <= 0f) return
- val nx = (x / width).coerceIn(0f, 1f)
- val ny = (y / height).coerceIn(0f, 1f)
- val rect = pointerSurfaceRect() ?: return
- val px = rect.left + nx * rect.width()
- val py = rect.top + ny * rect.height()
- WaylandCompositor.nativeSendPointer(1, InputSpace.x(px, outputView().width), InputSpace.y(py, outputView().height))
- showCursor(px, py)
- }
-
private fun bottomKeyboardPresentation(): SecondScreenPresentation? {
if (!started) return null
if (secondScreenPresentation?.showsKeyboard != true && dockDrawer()) {
@@ -3574,7 +3579,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (drawerOpen || drawerPinned) drawerOpen = false
typingReturnMode = secondScreenMode
selectedSecondScreenDisplay = target.displayId
- selectSecondScreenMode(SecondScreenMode.KEYBOARD_TRACKPAD)
+ selectSecondScreenMode(SecondScreenMode.CUSTOM_CONTROLS)
}
return secondScreenPresentation?.takeIf { it.showsKeyboard && it.display != null }
}
@@ -3645,13 +3650,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun selectGameField(vararg then: Int) {
- val held = KEY_LEFTCTRL in guestKeysDown || KEY_LEFTCTRL in gestureKeysDown
- if (!held) WaylandCompositor.nativeSendKey(KEY_LEFTCTRL, 1)
- for (key in intArrayOf(KEY_A) + then) {
- WaylandCompositor.nativeSendKey(key, 1)
- WaylandCompositor.nativeSendKey(key, 0)
- }
- if (!held) WaylandCompositor.nativeSendKey(KEY_LEFTCTRL, 0)
+ heldKeys.set(256, KEY_LEFTCTRL, true)
+ try {
+ for (key in intArrayOf(KEY_A) + then) {
+ heldKeys.set(256, key, true)
+ heldKeys.set(256, key, false)
+ }
+ } finally { heldKeys.release(256) }
}
private fun readGameField(done: (String?) -> Unit) {
@@ -3672,7 +3677,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.ui.SessionTyping.returnFocus(this, taskId)
val mode = typingReturnMode ?: return
typingReturnMode = null
- uiHandler.post { if (secondScreenMode == SecondScreenMode.KEYBOARD_TRACKPAD) selectSecondScreenMode(mode) }
+ uiHandler.post { if (secondScreenMode == SecondScreenMode.CUSTOM_CONTROLS) selectSecondScreenMode(mode) }
}
private fun updateKeyboardRoute() {
@@ -3756,40 +3761,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun sceneScale(rect: android.graphics.RectF): Float =
SessionState.outputSize.first / rect.width()
- private fun openEvdevMouse() {
+ // Clearing button owners emits releases, so backend transitions share their lock with all mouse writes.
+ private fun openEvdevMouse(): Unit = synchronized(heldButtons) {
if (evdevMouseActive || !evdevMouseOn) return
val writer = mouseWriter ?: com.droiddeck.launcher.input.FakeInputWriter(
File(LinuxRuntime.sessionRoot(this), "dev/input").absolutePath,
com.droiddeck.launcher.input.FakeInputWriter.MOUSE_SLOT,
).also { mouseWriter = it }
if (!writer.open()) return
+ heldButtons.clear()
evdevMouseActive = true
lastMouseX = Float.NaN
lastMouseY = Float.NaN
Log.i(TAG, "raw mouse channel active (pointer locked)")
}
- private fun closeEvdevMouse() {
+ private fun closeEvdevMouse(): Unit = synchronized(heldButtons) {
if (!evdevMouseActive) return
+ heldButtons.clear()
mouseWriter?.softRelease()
evdevMouseActive = false
Log.i(TAG, "raw mouse channel idle")
}
- private fun releaseEvdevMouse() {
+ private fun releaseEvdevMouse(): Unit = synchronized(heldButtons) {
+ if (evdevMouseActive) heldButtons.clear()
evdevMouseActive = false
mouseWriter?.destroy()
mouseWriter = null
Log.i(TAG, "raw mouse channel removed")
}
- private fun sendSceneDelta(dx: Float, dy: Float) {
+ private fun sendSceneDelta(dx: Float, dy: Float): Unit = synchronized(heldButtons) {
val writer = if (evdevMouseActive) mouseWriter else null
if (writer != null) writer.writeMouseDelta(dx, dy)
else WaylandCompositor.sendPointerDelta(dx, dy)
}
- private fun sendSceneButton(code: Int, down: Boolean) {
+ private fun sendSceneButton(code: Int, down: Boolean): Unit = synchronized(heldButtons) {
val raw = if (down) evdevMouseActive.also { guestButtonsDown[code] = it }
else guestButtonsDown.remove(code) ?: evdevMouseActive
val writer = if (raw) mouseWriter else null
@@ -3797,14 +3806,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
else WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0)
}
- private fun sendTrackpadButton(button: Int, pressed: Boolean) {
- if (pressed) trackpadButtonsDown.add(button) else trackpadButtonsDown.remove(button)
- WaylandCompositor.nativeSendSceneInput(3, button, if (pressed) 1 else 0)
- }
-
- private fun sendSceneWheel(steps: Int) {
+ private fun sendSceneWheel(steps: Int, horizontal: Boolean = false): Unit = synchronized(heldButtons) {
val writer = if (evdevMouseActive) mouseWriter else null
- if (writer != null) writer.writeMouseWheel(-steps, 0, 120)
+ if (writer != null) writer.writeMouseWheel(if (horizontal) 0 else -steps, if (horizontal) steps else 0, 120)
+ else if (horizontal) WaylandCompositor.nativeSendSceneInput(11, 0, steps * 120)
else WaylandCompositor.nativeSendSceneInput(4, steps, 0)
}
@@ -3866,7 +3871,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) dismissTouch = false
return true
}
- val uiBlocking = drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended
+ val uiBlocking = drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || inputSettingsOpen || pipUi || SessionState.suspended
if (event.actionMasked == MotionEvent.ACTION_DOWN && !uiBlocking && routedTouchMode != SessionPrefs.TOUCH_GESTURES) {
scrollTouchGesture = scrollTouchMode()
scrollRestX = 0f
@@ -3981,7 +3986,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!pointerLocked) showCursor(event.x.coerceIn(rect.left, rect.right), event.y.coerceIn(rect.top, rect.bottom))
if (WaylandCompositor.nativeFocusTakesTouch()) {
listOf(PointerGestures.BTN_LEFT, PointerGestures.BTN_RIGHT, PointerGestures.BTN_MIDDLE).forEach {
- WaylandCompositor.nativeSendSceneInput(3, it, 0)
+ heldButtons.set(1, it, false)
}
}
}
@@ -3995,7 +4000,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y, fromMouse = true)
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE -> {
if (evdevMouseActive) sendMouseDelta(event.x, event.y) else movePointer(event.x, event.y, fromMouse = true)
- guestMouseButton(event.actionButton)?.let { sendSceneButton(it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
+ guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
}
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
@@ -4031,7 +4036,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun updatePointerCapture() {
if (!::surfaceView.isInitialized) return
val view = window.decorView
- val want = (pointerLocked || relativeMouseAttached()) && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !pipUi && !bottomOutputActive && !touchEditorOpen && mouseAttached()
+ val want = (pointerLocked || relativeMouseAttached()) && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !bottomOutputActive && !touchEditorOpen && mouseAttached()
releaseDesktopMouseGrab()
if (want == view.hasPointerCapture()) return
if (want) view.requestPointerCapture() else view.releasePointerCapture()
@@ -4084,13 +4089,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var platformPointerShown: Boolean? = null
private fun touchEditorChanged() {
- touchEditorOpen = screenKeys?.isEditing == true || steamTouchControls?.isEditing == true
+ touchEditorOpen = steamTouchControls?.isEditing == true
updatePointerCapture()
applyPlatformPointer(appUiOwnsPointer())
}
private fun appUiOwnsPointer(): Boolean =
- drawerOpen || pcKeyboardOpen || achievementsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
+ drawerOpen || pcKeyboardOpen || achievementsOpen || inputSettingsOpen || pipUi || glassesOutputActive || bottomOutputActive || touchEditorOpen || wowChatOnTop
private fun applyPlatformPointer(shown: Boolean) {
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
@@ -4120,7 +4125,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
MotionEvent.ACTION_BUTTON_PRESS, MotionEvent.ACTION_BUTTON_RELEASE ->
- guestMouseButton(event.actionButton)?.let { sendSceneButton(it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
+ guestMouseButton(event.actionButton)?.let { heldButtons.set(8, it, event.actionMasked == MotionEvent.ACTION_BUTTON_PRESS) }
MotionEvent.ACTION_SCROLL -> {
val v = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
if (v != 0f) sendSceneWheel(-Math.round(v))
@@ -4164,7 +4169,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
device.plugged = false
uiHandler.postDelayed({ updateOnScreenControls() }, 700)
}
- view.onStyle = { screenKeys?.refreshAppearance() }
view.onTouchMiss = miss@{ event ->
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.ON_SCREEN_CONTROLS, event)) return@miss
event.offsetLocation(view.left - surfaceView.left.toFloat(), view.top - surfaceView.top.toFloat())
@@ -4188,19 +4192,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun updateOnScreenPad() {
+ fun hideBottomControls() { bottomInputControls?.takeIf { it.visibility == View.VISIBLE }?.let { it.releaseAll(); it.visibility = View.GONE } }
val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc")
.takeIf { it.isFile }
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this)
val controls = onScreenControls ?: return
- if (pipUi || unfoldedPanel != null || pcKeyboardOpen ||
+ if (pipUi || unfoldedPanel != null || pcKeyboardOpen || inputSettingsOpen ||
(SessionState.mode == SessionService.MODE_STEAM && !SessionPrefs.builtinPad(this))) {
onScreenButtonsVisible = false
+ hideBottomControls()
controls.releaseAll()
controls.visibility = View.GONE
steamTouchControls?.let { it.cancelEditing(); it.releaseAll(); it.visibility = View.GONE }
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
- screenKeys?.followSteam = false
applyTouchRouting()
return
}
@@ -4229,7 +4234,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onScreenButtonsVisible = show
val drawn = show && !keyboardCoversPad()
if (steam != null) {
- screenKeys?.followSteam = drawn
+ hideBottomControls()
if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE }
if (!drawn) { steam.cancelEditing(); steam.releaseAll() }
steam.visibility = if (drawn) View.VISIBLE else View.GONE
@@ -4238,7 +4243,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden")
return
}
- screenKeys?.followSteam = false
+ val bottomRoot = bottomGame?.surfaceView?.parent as? android.view.ViewGroup
+ if (drawn && bottomRoot != null) {
+ controls.releaseAll(); controls.visibility = View.GONE
+ var bottom = bottomInputControls
+ if (bottom?.parent !== bottomRoot) {
+ (bottom?.parent as? android.view.ViewGroup)?.removeView(bottom)
+ bottom = OnScreenControls(bottomRoot.context, padBridge).also { view ->
+ view.onTouchMiss = { event -> onBottomGameTouch(event) }
+ bottomRoot.addView(view, android.view.ViewGroup.LayoutParams(-1, -1))
+ }
+ bottomInputControls = bottom
+ }
+ bottom.updateLayout(primaryInputLayout)
+ bottom.setButtonsOnly(buttonsOnly)
+ bottom.visibility = View.VISIBLE
+ return
+ }
+ hideBottomControls()
if (drawn == (controls.visibility == View.VISIBLE)) return
if (!drawn) controls.releaseAll()
controls.visibility = if (drawn) View.VISIBLE else View.GONE
@@ -4307,17 +4329,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard
private fun releaseHeldGuestInput() {
- guestButtonsDown.keys.toList().forEach { sendSceneButton(it, false) }
- trackpadButtonsDown.toList().forEach { WaylandCompositor.nativeSendSceneInput(3, it, 0) }
- trackpadButtonsDown.clear()
+ mouseBackInput.cancel()
+ heldButtons.release(1 or 2 or 8 or 16)
guestKeysDown.toList().forEach { sendGuestKey(it, false) }
+ heldKeys.release(8 or 16 or 32)
}
- private fun sendGuestKey(key: Int, down: Boolean) {
+ private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) {
if (down && pipUi) return
val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key
- if (down) guestKeysDown.add(code) else guestKeysDown.remove(code)
- if (down || code !in gestureKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0)
+ if (owner == 1) { if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) }
+ heldKeys.set(owner, code, down)
}
private fun capturePausedFrame(manual: Boolean = false) {
@@ -4393,13 +4415,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
pendingBackAction = null
releaseDrawerDirection()
onScreenControls?.releaseAll()
- screenKeys?.releaseAll()
+ bottomInputControls?.releaseAll()
releasePads()
touchpad.cancel()
scrollTouch.cancel()
directTouchHold.cancel()
twoFingerGestures.cancel()
- releaseHeldGuestInput()
+ guestKeysDown.toList().forEach { sendGuestKey(it, false) }
+ heldKeys.clear()
+ heldButtons.clear()
keyboard?.hide()
sessionClipboard.stop()
padMotion?.stop()
@@ -4410,7 +4434,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (CompositorHost.isStarted) {
WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
listOf(PointerGestures.BTN_LEFT, PointerGestures.BTN_RIGHT, PointerGestures.BTN_MIDDLE).forEach {
- WaylandCompositor.nativeSendSceneInput(3, it, 0)
+ heldButtons.set(1, it, false)
}
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, ALIGN_CENTER)
}
@@ -4516,7 +4540,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onResume() {
super.onResume()
com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event ->
- com.droiddeck.launcher.input.GuestKeys.send(event, ::sendGuestKey)
+ com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) }
}
if (refreshActivityDisplayId() && started) {
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
@@ -4544,7 +4568,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this,
enabled = {
resumed && window.decorView.hasWindowFocus() && !ended && !drawerOpen && !pcKeyboardOpen &&
- !achievementsOpen && !gestureSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended &&
+ !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && SessionState.running && !SessionState.suspended &&
SessionState.mode == SessionService.MODE_STEAM && padBridge != null
},
setPressed = { padBridge?.setHomeGuidePressed(it) },
@@ -4555,6 +4579,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
updatePadMotion()
ControllerPrefs.prefs(this).registerOnSharedPreferenceChangeListener(shortcutPrefListener)
readPrefs()
+ refreshInputProfile()
refreshControls()
if (::pip.isInitialized) pip.resumed()
if (CompositorHost.isStarted) applyFrameGen()
@@ -4569,6 +4594,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
backQamInput.cancel()
mouseBackInput.cancel()
capturePausedFrame()
+ padBridge?.setInputEnabled(false)
sessionClipboard.stop()
if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel()
if (::touchpad.isInitialized) touchpad.cancel()
@@ -4577,12 +4603,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
uiHandler.removeCallbacks(clearRecognizedGesture)
uiHandler.removeCallbacks(cursorResync)
gestureSettingsOpen = false
+ inputSettingsOpen = false
+ releasePads()
+ heldKeys.clear()
+ heldButtons.clear()
drawerOpen = false
pcKeyboardOpen = false
achievementsOpen = false
(getSystemService(INPUT_SERVICE) as? InputManager)?.unregisterInputDeviceListener(deviceListener)
releaseDrawerDirection()
onScreenControls?.releaseAll()
+ bottomInputControls?.releaseAll()
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (::padMouse.isInitialized) padMouse.reset()
resumed = false
@@ -4806,6 +4837,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (holder !== outputHolder()) return
glassesOutputActive = glassesScreen?.holder === holder
bottomOutputActive = bottomGame?.holder === holder
+ updateOnScreenPad()
updatePointerCapture()
if (bottomOutputActive) bottomRecoveries = 0
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(glassesOutputActive || bottomOutputActive)
@@ -4910,6 +4942,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (bottomGame !== screen) return
bottomGame = null
bottomOutputActive = false
+ updateOnScreenPad()
surfaceW = 0
surfaceH = 0
CompositorHost.detach(screen.holder.surface)
@@ -4941,9 +4974,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
title, openMenu, openMenu, if (steam) ({ tapSteamButton() }) else null, if (steam) ({ tapQam() }) else null,
extras + com.droiddeck.launcher.ui.BarExtra(getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, onClick = swapBack),
)
- val keyboardExtra = com.droiddeck.launcher.ui.BarExtra(getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) {
- keyboard?.toggle()
- }
+ val profileLayout = secondaryInputLayout
androidx.compose.foundation.layout.Box(
Modifier.fillMaxSize().background(androidx.compose.ui.graphics.Color.Black)
.pointerInput(Unit) { awaitPointerEventScope { while (true) awaitPointerEvent() } },
@@ -4957,36 +4988,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
},
modifier = Modifier.fillMaxSize(),
)
- secondScreenMode == SecondScreenMode.DECK_CONTROLS && SessionState.deckPad ->
- androidx.compose.ui.viewinterop.AndroidView(
- factory = { context ->
- com.droiddeck.launcher.ui.DeckControlsPanel(context, onClose = openMenu, onSteamMenu = ::tapSteamButton,
- onQam = ::tapQam, pad = padBridge, onMenu = openMenu, onSwap = swapBack)
- },
- modifier = Modifier.fillMaxSize(),
- )
- secondScreenMode == SecondScreenMode.KEYBOARD_TRACKPAD -> androidx.compose.foundation.layout.Column(Modifier.fillMaxSize()) {
- com.droiddeck.launcher.ui.BottomScreenBar(bar(getString(SecondScreenMode.KEYBOARD_TRACKPAD.label), listOf(keyboardExtra)))
- androidx.compose.ui.viewinterop.AndroidView(
- factory = { context ->
- com.droiddeck.launcher.ui.SessionTrackpadView(context, ::moveSecondScreenPointer,
- ::sendTrackpadButton,
- { steps -> WaylandCompositor.nativeSendSceneInput(4, steps, 0) })
- },
- modifier = Modifier.fillMaxWidth().weight(1f),
- )
+ secondScreenMode == SecondScreenMode.CUSTOM_CONTROLS -> {
+ androidx.compose.runtime.key(profileLayout) {
+ androidx.compose.ui.viewinterop.AndroidView(
+ factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(),
+ surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) },
+ modifier = Modifier.fillMaxSize(),
+ )
+ }
}
- secondScreenMode == SecondScreenMode.TERMINAL -> androidx.compose.foundation.layout.Column(Modifier.fillMaxSize()) {
- var terminal by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(null) }
- com.droiddeck.launcher.ui.BottomScreenBar(bar(getString(SecondScreenMode.TERMINAL.label), listOf(
- com.droiddeck.launcher.ui.BarExtra(getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard) { terminal?.showKeyboard() },
- )))
- androidx.compose.ui.viewinterop.AndroidView(
- factory = { context -> com.droiddeck.launcher.ui.SessionTerminalPanel(context).also { terminal = it } },
- modifier = Modifier.fillMaxWidth().weight(1f),
- )
- }
- pages.isEmpty() -> com.droiddeck.launcher.ui.BottomScreenBar(bar(null))
+
else -> BottomDashboard(
pages, com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
@@ -5199,6 +5210,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
closeSecondScreen(reset = false)
glassesScope.cancel()
glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } }
+ bottomInputControls?.let { (it.parent as? android.view.ViewGroup)?.removeView(it) }
+ bottomInputControls = null
bottomGame?.let { screen -> bottomGame = null; runCatching { screen.dismiss() } }
headTracker?.stop()
if (::hud.isInitialized) hud.stop()
@@ -5207,7 +5220,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
joyConVr = null
handCamera?.stop()
handCamera = null
+ inputMotion.stop()
+ padBridge?.setInputEnabled(false)
+ physicalInputBindings?.close()
padBridge?.stop()
+ DeckControls.clearRouter(inputRouter)
+ inputRouter = null
+ heldKeys.clear()
+ heldButtons.clear()
steamController?.stop()
if (SessionState.padBridge === padBridge) SessionState.padBridge = null
padMotion?.stop()
diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerEditorActivity.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerEditorActivity.kt
deleted file mode 100644
index cb544d5a4d..0000000000
--- a/app/src/main/java/com/droiddeck/launcher/input/ControllerEditorActivity.kt
+++ /dev/null
@@ -1,136 +0,0 @@
-package com.droiddeck.launcher.input
-
-import com.droiddeck.launcher.ui.focusGlide
-import android.os.Build
-import android.os.Bundle
-import android.view.Gravity
-import android.view.View
-import android.view.WindowManager
-import android.widget.FrameLayout
-import androidx.activity.ComponentActivity
-import androidx.compose.foundation.background
-import androidx.compose.foundation.clickable
-import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.selection.toggleable
-import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.material3.MaterialTheme
-import androidx.compose.material3.Text
-import androidx.compose.ui.Alignment
-import androidx.compose.runtime.Composable
-import androidx.compose.runtime.getValue
-import androidx.compose.runtime.mutableStateOf
-import androidx.compose.runtime.remember
-import androidx.compose.runtime.setValue
-import androidx.compose.ui.Modifier
-import androidx.compose.ui.draw.clip
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.semantics.Role
-import androidx.compose.ui.text.font.FontWeight
-import androidx.compose.ui.platform.ComposeView
-import androidx.compose.ui.unit.dp
-import androidx.compose.ui.unit.sp
-import androidx.compose.ui.res.stringResource
-import com.droiddeck.launcher.R
-import com.droiddeck.launcher.ui.DroidDeckTheme
-import com.droiddeck.launcher.ui.onSignal
-import com.droiddeck.launcher.ui.LocalPalette
-
-class ControllerEditorActivity : ComponentActivity() {
- override fun attachBaseContext(newBase: android.content.Context) {
- super.attachBaseContext(newBase)
- com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
- }
-
- private lateinit var controls: OnScreenControls
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
- immersive()
- val root = FrameLayout(this)
- root.setBackgroundColor(0xFF0B0F14.toInt())
- controls = OnScreenControls(this, null, editing = true)
- root.addView(controls, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT))
- val bar = ComposeView(this).apply {
- setContent {
- DroidDeckTheme {
- var snap by remember { mutableStateOf(ControllerPrefs.read(context).snap) }
- Column(
- horizontalAlignment = Alignment.CenterHorizontally,
- verticalArrangement = Arrangement.spacedBy(5.dp),
- modifier = Modifier
- .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), RoundedCornerShape(20.dp))
- .padding(start = 5.dp, end = 5.dp, top = 8.dp, bottom = 5.dp),
- ) {
- Text(stringResource(R.string.ctrl_editor_drag), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
- Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
- EditorButton(stringResource(R.string.ctrl_editor_snap), false, selected = snap) {
- snap = !snap
- ControllerPrefs.setSnap(context, snap)
- controls.setSnap(snap)
- }
- EditorButton(stringResource(R.string.ctrl_reset), false) { controls.resetLayout() }
- EditorButton(stringResource(R.string.common_cancel), false) { finish() }
- EditorButton(stringResource(R.string.ctrl_editor_save), true) {
- controls.saveLayout()
- finish()
- }
- }
- }
- }
- }
- }
- root.addView(bar, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER))
- setContentView(root)
- }
-
- @Composable
- private fun EditorButton(label: String, primary: Boolean, selected: Boolean? = null, onClick: () -> Unit) {
- val pal = LocalPalette.current
- Text(
- label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
- color = when {
- primary -> pal.onSignal
- selected == true -> pal.signal
- else -> MaterialTheme.colorScheme.onBackground
- },
- modifier = Modifier.clip(RoundedCornerShape(50))
- .background(
- when {
- primary -> pal.signal
- selected == true -> pal.signal.copy(alpha = 0.18f)
- else -> Color.White.copy(alpha = 0.06f)
- },
- )
- .focusGlide(RoundedCornerShape(50))
- .then(
- if (selected == null) Modifier.clickable(onClick = onClick)
- else Modifier.toggleable(value = selected, role = Role.Switch, onValueChange = { onClick() }),
- )
- .padding(horizontal = 12.dp, vertical = 6.dp),
- )
- }
-
- override fun onWindowFocusChanged(hasFocus: Boolean) {
- super.onWindowFocusChanged(hasFocus)
- if (hasFocus) immersive()
- }
-
- private fun immersive() {
- @Suppress("DEPRECATION")
- window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
- or View.SYSTEM_UI_FLAG_FULLSCREEN
- or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
- or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
- or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
- or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
- if (Build.VERSION.SDK_INT >= 28) {
- window.attributes = window.attributes.apply {
- layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
- }
- }
- }
-}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt
index bb1705ba68..1edc2395ce 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/ControllerPrefs.kt
@@ -169,56 +169,6 @@ object ControllerPrefs {
prefs(context).edit().remove("layout.${width}x$height").apply()
}
- fun screenKeysShown(context: Context): Boolean = prefs(context).getBoolean("screenKeysShown", true)
-
- fun setScreenKeysShown(context: Context, shown: Boolean) {
- prefs(context).edit().putBoolean("screenKeysShown", shown).apply()
- }
-
- fun screenKeys(context: Context): List = decodeScreenKeys(prefs(context).getString("screenKeys", null).orEmpty())
-
- fun setScreenKeys(context: Context, keys: List) {
- prefs(context).edit().putString("screenKeys", encodeScreenKeys(keys)).apply()
- }
-
- fun encodeScreenKeys(keys: List): String = keys.joinToString(";") {
- "${it.codes.joinToString("+")}:${it.x},${it.y},${it.size}:${escape(it.glyph)}:${escape(it.text)}:${escape(it.image)}:${it.opacity}:${it.shape}:${if (it.toggle) 1 else 0}:${if (it.labels) 1 else 0}"
- }
-
- fun decodeScreenKeys(raw: String): List = raw.split(';').mapNotNull { entry ->
- val parts = entry.split(':')
- if (parts.size < 2) return@mapNotNull null
- val keys = parts[0].split('+').mapNotNull { it.toIntOrNull() }.takeIf { it.isNotEmpty() } ?: return@mapNotNull null
- val nums = parts[1].split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 3 } ?: return@mapNotNull null
- ScreenKey(
- keys, nums[0], nums[1], nums[2].toInt(),
- parts.getOrNull(2)?.let(::unescape).orEmpty(),
- parts.getOrNull(3)?.let(::unescape).orEmpty(),
- parts.getOrNull(4)?.let(::unescape).orEmpty(),
- parts.getOrNull(5)?.toFloatOrNull()?.coerceIn(0.2f, 1f) ?: 1f,
- parts.getOrNull(6)?.toIntOrNull()?.coerceIn(SCREEN_KEY_PILL, SCREEN_KEY_STICK) ?: SCREEN_KEY_PILL,
- parts.getOrNull(7) == "1",
- parts.getOrNull(8) != "0",
- )
- }
-
- fun screenLayouts(context: Context): Map =
- prefs(context).all.mapNotNull { (key, value) ->
- if (!key.startsWith("screenLayout.") || value !is String) null else key.removePrefix("screenLayout.") to value
- }.toMap()
-
- fun saveScreenLayout(context: Context, name: String, raw: String) {
- prefs(context).edit().putString("screenLayout.$name", raw).apply()
- }
-
- fun deleteScreenLayout(context: Context, name: String) {
- prefs(context).edit().remove("screenLayout.$name").apply()
- }
-
- private fun escape(value: String) = value.replace("%", "%25").replace(";", "%3B").replace(":", "%3A").replace(",", "%2C")
-
- private fun unescape(value: String) = value.replace("%2C", ",").replace("%3A", ":").replace("%3B", ";").replace("%25", "%")
-
fun resetAll(context: Context) {
prefs(context).edit().clear().putBoolean("rumble", true).apply()
}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/DeckControls.kt b/app/src/main/java/com/droiddeck/launcher/input/DeckControls.kt
index a8c499793b..41b7240362 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/DeckControls.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/DeckControls.kt
@@ -5,53 +5,165 @@ object DeckControls {
const val R4 = 2
const val L5 = 4
const val R5 = 8
- private const val LEFT_TOUCH = 16
- private const val RIGHT_TOUCH = 32
- private const val LEFT_CLICK = 64
- private const val RIGHT_CLICK = 128
-
- private const val SLOT = 0
-
- private var controls = 0
+ private val controls = arrayOf(InputControl.L4, InputControl.R4, InputControl.L5, InputControl.R5,
+ InputControl.LEFT_PAD, InputControl.RIGHT_PAD, InputControl.LEFT_CLICK, InputControl.RIGHT_CLICK)
+ private val sources = ArrayList()
+ private val physical = Source(InputRole.PHYSICAL)
+ private var router: InputRouter? = null
private val pads = ShortArray(4)
private val pressure = ShortArray(2)
+ private val touchOwners = arrayOfNulls(2)
@Synchronized
- fun setGrip(bit: Int, down: Boolean) {
- set(bit, down)
+ fun setRouter(next: InputRouter?) {
+ if (router === next) return
+ for (source in sources) source.closeRoutes()
+ router = next
+ for (source in sources) source.configure()
publish()
}
@Synchronized
- fun setPad(right: Boolean, touching: Boolean, x: Float = 0f, y: Float = 0f) {
- val at = if (right) 2 else 0
- set(if (right) RIGHT_TOUCH else LEFT_TOUCH, touching)
- pads[at] = if (touching) axis(x) else 0
- pads[at + 1] = if (touching) axis(y) else 0
- publish()
+ fun clearRouter(owner: InputRouter?) {
+ if (owner != null && router === owner) setRouter(null)
}
@Synchronized
- fun setClick(right: Boolean, down: Boolean) {
- set(if (right) RIGHT_CLICK else LEFT_CLICK, down)
- pressure[if (right) 1 else 0] = if (down) Short.MAX_VALUE else 0
- publish()
- }
+ @JvmOverloads
+ fun source(role: InputRole, routed: Boolean = false) = Source(role, routed)
+
+ @Synchronized
+ fun setGrip(bit: Int, down: Boolean) = physical.setGrip(bit, down)
+
+ @Synchronized
+ fun setPad(right: Boolean, touching: Boolean, x: Float = 0f, y: Float = 0f) = physical.setPad(right, touching, x, y)
+
+ @Synchronized
+ fun setClick(right: Boolean, down: Boolean) = physical.setClick(right, down)
@Synchronized
fun releaseAll() {
- if (controls == 0 && pads.all { it.toInt() == 0 } && pressure.all { it.toInt() == 0 }) return
- controls = 0
- pads.fill(0)
- pressure.fill(0)
+ for (source in sources) source.clear()
publish()
}
- private fun set(bit: Int, on: Boolean) {
- controls = if (on) controls or bit else controls and bit.inv()
+ @Synchronized
+ fun suspend() {
+ for (source in sources) source.suspend()
+ publish()
}
- private fun axis(value: Float): Short = (value.coerceIn(-1f, 1f) * Short.MAX_VALUE).toInt().toShort()
+ @Synchronized
+ fun refresh() {
+ for (source in sources) source.route()
+ publish()
+ }
- private fun publish() = FakeInputWriter.writeDeckControls(SLOT, controls, pads, pressure)
+ class Source internal constructor(private val role: InputRole, private val routed: Boolean = false) {
+ private val x = FloatArray(8)
+ private val y = FloatArray(8)
+ private val touched = BooleanArray(8)
+ private var routes: Array? = null
+ internal var mask = 0
+ internal val axes = ShortArray(4)
+
+ internal fun configure() {
+ routes = router?.takeUnless { routed }?.let { r -> Array(8) { i ->
+ r.channel(role, controls[i]).also { it.awaitNeutral(x[i], y[i], touched[i]) }
+ } }
+ mask = 0
+ axes.fill(0)
+ }
+
+ private fun attach() {
+ if (this !in sources) { sources.add(this); configure() }
+ }
+
+ fun setGrip(bit: Int, down: Boolean) = synchronized(DeckControls) {
+ val at = when (bit) { L4 -> 0; R4 -> 1; L5 -> 2; R5 -> 3; else -> return@synchronized }
+ update(at, if (down) 1f else 0f)
+ }
+
+ fun setPad(right: Boolean, touching: Boolean, x: Float = 0f, y: Float = 0f) = synchronized(DeckControls) {
+ update(if (right) 5 else 4, if (touching) x else 0f, if (touching) y else 0f, touching)
+ }
+
+ fun setClick(right: Boolean, down: Boolean) = synchronized(DeckControls) {
+ update(if (right) 7 else 6, if (down) 1f else 0f)
+ }
+
+ private fun update(at: Int, value: Float, second: Float = 0f, contact: Boolean = false) {
+ val timing = InputTiming.begin()
+ attach()
+ x[at] = value; y[at] = second; touched[at] = contact
+ route()
+ publish()
+ InputTiming.end(timing)
+ }
+
+ internal fun native(control: InputControl?, value: Float, second: Float, contact: Boolean) = synchronized(DeckControls) {
+ require(routed)
+ attach()
+ x.fill(0f); y.fill(0f); touched.fill(false)
+ val at = controls.indexOf(control)
+ if (at >= 0) { x[at] = value; y[at] = second; touched[at] = contact }
+ route(); publish()
+ }
+
+ internal fun route() {
+ mask = 0
+ axes.fill(0)
+ for (i in controls.indices) {
+ val target = if (routes == null) controls[i] else routes!![i].update(x[i], y[i], touched[i]) ?: continue
+ val at = controls.indexOf(target)
+ if (at < 0) continue
+ if (at == 4 || at == 5) {
+ if (touched[i]) {
+ mask = mask or (1 shl at)
+ axes[(at - 4) * 2] = axis(x[i]); axes[(at - 4) * 2 + 1] = axis(y[i])
+ }
+ } else if (x[i] > 0.5f) mask = mask or (1 shl at)
+ }
+ }
+
+ internal fun clear() {
+ x.fill(0f); y.fill(0f); touched.fill(false); mask = 0; axes.fill(0)
+ routes?.forEach { it.release() }
+ }
+
+ internal fun suspend() {
+ mask = 0; axes.fill(0)
+ routes?.forEach { it.suspend() }
+ }
+
+ fun release() = synchronized(DeckControls) { clear(); publish() }
+
+ internal fun closeRoutes() { routes?.forEach { it.close() }; routes = null }
+
+ fun close() = synchronized(DeckControls) {
+ clear(); closeRoutes(); sources.remove(this); publish()
+ }
+ }
+
+ private fun axis(value: Float) = (value.coerceIn(-1f, 1f) * Short.MAX_VALUE).toInt().toShort()
+
+ private fun publish() {
+ var mask = 0
+ pads.fill(0)
+ for (source in sources) {
+ mask = mask or source.mask
+ }
+ for (side in 0..1) {
+ val contact = 16 shl side
+ val owner = touchOwners[side]?.takeIf { it.mask and contact != 0 }
+ ?: sources.firstOrNull { it.mask and contact != 0 }
+ touchOwners[side] = owner
+ if (owner == null) continue
+ pads[side * 2] = owner.axes[side * 2]
+ pads[side * 2 + 1] = owner.axes[side * 2 + 1]
+ }
+ pressure[0] = if (mask and 64 != 0) Short.MAX_VALUE else 0
+ pressure[1] = if (mask and 128 != 0) Short.MAX_VALUE else 0
+ FakeInputWriter.writeDeckControls(0, mask, pads, pressure)
+ }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GamepadGeometry.kt b/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt
similarity index 99%
rename from app/src/main/java/com/droiddeck/launcher/ui/GamepadGeometry.kt
rename to app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt
index 2b369c20aa..988ab5f764 100644
--- a/app/src/main/java/com/droiddeck/launcher/ui/GamepadGeometry.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/GamepadGeometry.kt
@@ -1,4 +1,4 @@
-package com.droiddeck.launcher.ui
+package com.droiddeck.launcher.input
import kotlin.math.min
diff --git a/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt b/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt
index 4d69f68c5b..9ba24e3381 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt
@@ -3,7 +3,7 @@ package com.droiddeck.launcher.input
import android.view.MotionEvent
internal class GestureTouchStreamGate {
- enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
+ enum class Source { SURFACE, ON_SCREEN_CONTROLS }
private var owner: Source? = null
diff --git a/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt b/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt
new file mode 100644
index 0000000000..1fdb6121fc
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/HeldInput.kt
@@ -0,0 +1,27 @@
+package com.droiddeck.launcher.input
+
+class HeldInput(private val emit: (Int, Boolean) -> Unit) {
+ private val owners = IntArray(768)
+
+ @Synchronized
+ fun set(source: Int, code: Int, down: Boolean) {
+ if (code !in owners.indices) return
+ val before = owners[code]
+ val after = if (down) before or source else before and source.inv()
+ owners[code] = after
+ if ((before == 0) != (after == 0)) emit(code, after != 0)
+ }
+
+ @Synchronized
+ fun release(source: Int) {
+ for (code in owners.indices) if (owners[code] and source != 0) set(source, code, false)
+ }
+
+ @Synchronized
+ fun clear() {
+ for (code in owners.indices) if (owners[code] != 0) {
+ owners[code] = 0
+ emit(code, false)
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScreenKeyIcons.kt b/app/src/main/java/com/droiddeck/launcher/input/InputButtonIcons.kt
similarity index 77%
rename from app/src/main/java/com/droiddeck/launcher/input/ScreenKeyIcons.kt
rename to app/src/main/java/com/droiddeck/launcher/input/InputButtonIcons.kt
index b1ea677b99..8f87c05cbf 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/ScreenKeyIcons.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputButtonIcons.kt
@@ -1,16 +1,49 @@
package com.droiddeck.launcher.input
+import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
+import android.graphics.drawable.Drawable
+import com.droiddeck.launcher.R
-object ScreenKeyIcons {
- fun has(code: Int): Boolean = code in SET
+object InputButtonIcons {
+ // Persisted symbol IDs must not depend on Android resource IDs or overlap Linux key codes.
+ const val MENU = 1001
+ const val KEYBOARD = 1002
+ const val STEAM = 1003
+ const val QUICK_ACCESS = 1004
- private val SET = setOf(28, 14, 15, 57, 42, 54, 29, 97, 125, 103, 108, 105, 106)
+ fun has(code: Int): Boolean = code in codes
- fun draw(canvas: Canvas, code: Int, cx: Float, cy: Float, box: Float, paint: Paint): Boolean {
- if (!has(code)) return false
+ private val keyCodes = listOf(28, 14, 15, 57, 42, 54, 29, 97, 125, 103, 108, 105, 106)
+ val codes = listOf(MENU, KEYBOARD, STEAM, QUICK_ACCESS) + keyCodes
+
+ fun label(context: Context, code: Int): String = when (code) {
+ MENU -> context.getString(R.string.touch_droiddeck_menu)
+ KEYBOARD -> context.getString(R.string.drawer_keyboard)
+ STEAM -> context.getString(R.string.drawer_steam_menu)
+ QUICK_ACCESS -> context.getString(R.string.drawer_open_qam)
+ else -> pcKeyLabel(context, code)
+ }
+
+ fun drawable(context: Context, code: Int): Drawable? = when (code) {
+ MENU -> R.drawable.ic_stat_session
+ KEYBOARD -> R.drawable.ic_bottom_keyboard
+ STEAM -> R.drawable.ic_input_steam
+ QUICK_ACCESS -> R.drawable.ic_input_quick_access
+ else -> null
+ }?.let { context.getDrawable(it)?.mutate() }
+
+ fun draw(canvas: Canvas, code: Int, cx: Float, cy: Float, box: Float, paint: Paint, drawable: Drawable? = null): Boolean {
+ if (drawable != null) {
+ drawable.setTint(paint.color)
+ val half = box / 2f
+ drawable.setBounds((cx - half).toInt(), (cy - half).toInt(), (cx + half).toInt(), (cy + half).toInt())
+ drawable.draw(canvas)
+ return true
+ }
+ if (code !in keyCodes) return false
val h = box / 2f
val stroke = box * 0.085f
val path = Path()
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt
new file mode 100644
index 0000000000..28e36f1806
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt
@@ -0,0 +1,294 @@
+package com.droiddeck.launcher.input
+
+import android.content.Context
+import android.hardware.display.DisplayManager
+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 = 8
+ 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"
+
+ private fun prefs(context: Context) = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
+
+ @Synchronized
+ fun read(context: Context): InputLibrary {
+ val p = prefs(context)
+ val raw = p.getString(KEY, null)
+ val decoded = raw?.let(::decode)
+ if (raw != null && decoded == null) return scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, migrate(context))))
+ var library = decoded ?: scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, migrate(context))))
+ val version = raw?.let { JSONObject(it).getInt("version") } ?: 0
+ if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library)))
+ if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
+ val legacy = LegacyScreenKeyMigration.snapshot(context)
+ if (legacy != null) {
+ val upgraded = runCatching { LegacyScreenKeyMigration.migrate(context, library, legacy) }.getOrElse {
+ android.util.Log.e("InputLibraries", "Could not migrate screen keys; keeping the original settings", it)
+ return library
+ }
+ val encoded = encode(upgraded)
+ require(encoded.length <= 2_000_000)
+ if (!p.edit().putString(KEY, encoded).putString(LegacyScreenKeyMigration.BACKUP, legacy).commit()) return library
+ LegacyScreenKeyMigration.clean(context)
+ return upgraded
+ }
+ }
+ if (raw == null || version < VERSION) write(context, library)
+ if (p.contains(LegacyScreenKeyMigration.BACKUP)) LegacyScreenKeyMigration.clean(context)
+ return library
+ }
+
+ 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 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) {
+ val encoded = encode(library.validate())
+ require(encoded.length <= 2_000_000) { "The input library is too large to save." }
+ prefs(context).edit().putString(KEY, encoded).apply()
+ }
+
+ private fun migrate(context: Context): InputLibrary {
+ val profiles = mutableListOf()
+ val stock = InputStockLayouts.layouts()
+ val layouts = (listOf(SavedInputLayout(OVERLAY, "Built-in gamepad", template = InputLayoutTemplate.OVERLAY)) + stock).toMutableList()
+ val bindings = InputStockLayouts.presets(stock).toMutableList()
+ for (id in listOf(InputProfile.GAME, InputProfile.DESKTOP)) {
+ val old = InputProfiles.readLegacy(context, id)
+ val name = if (id == InputProfile.GAME) "Game" else "Desktop"
+ val legacySurface = InputSurfaceLayout.hasLegacy(context, id) ||
+ old.bindings[InputRole.SECONDARY] != InputProfile.defaults(id).bindings[InputRole.SECONDARY]
+ val layout = if (legacySurface) SavedInputLayout("$id.layout", "$name touch", InputSurfaceLayout.readLegacy(context, id)).also { layouts += it }
+ else stock.first { it.id == if (id == InputProfile.DESKTOP) TRACKPAD else DECK }
+ val parts = InputRole.entries.associateWith { role ->
+ if (role == InputRole.SECONDARY && !legacySurface) {
+ val preset = bindings.first { it.layoutId == layout.id }
+ return@associateWith InputPart(preset.id, layout.id)
+ }
+ val preset = SavedInputBindings("$id.${role.name.lowercase()}", "$name / ${role.name.lowercase()}",
+ role == InputRole.PHYSICAL, if (role == InputRole.SECONDARY) layout.id else null,
+ old.bindings[role].orEmpty(), keys = if (role == InputRole.PHYSICAL) old.keys else emptyList())
+ bindings += preset
+ InputPart(preset.id, when (role) { InputRole.PHYSICAL -> null; InputRole.PRIMARY -> OVERLAY; InputRole.SECONDARY -> layout.id })
+ }
+ profiles += SavedInputProfile(id, name, id, parts)
+ }
+ val selected = prefs(context).getString("selected", InputProfiles.AUTO)
+ ?.takeIf { it == InputProfiles.AUTO || profiles.any { p -> p.id == it } } ?: InputProfiles.AUTO
+ return InputLibrary(profiles, layouts, bindings, selected).validate()
+ }
+
+ @Suppress("DEPRECATION")
+ private fun upgradeOverlay(context: Context, library: InputLibrary): InputLibrary {
+ if (library.layouts.none { it.template == InputLayoutTemplate.OVERLAY }) return library
+ val display = context.getSystemService(DisplayManager::class.java)?.getDisplay(Display.DEFAULT_DISPLAY)
+ val surfaceContext = display?.let(context::createDisplayContext) ?: context
+ val metrics = DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) }
+ val settings = ControllerPrefs.read(context)
+ val elements = LegacyGamepadLayout(surfaceContext, metrics.widthPixels.coerceAtLeast(1), metrics.heightPixels.coerceAtLeast(1)).elements()
+ val style = InputSurfaceStyle(settings.tint, settings.opacity)
+ val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old ->
+ old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style)
+ }
+ var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
+ val migrated = mutableMapOf, String>()
+ for (profile in library.profiles) {
+ val parts = profile.parts.mapValues { (role, part) ->
+ val layout = replacements[part.layout] ?: return@mapValues part
+ val key = part.bindings to layout.id
+ val id = migrated.getOrPut(key) {
+ val old = library.preset(part.bindings)
+ 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))
+ newId
+ }
+ part.copy(bindings = id)
+ }
+ result = result.withProfile(profile.copy(parts = parts))
+ }
+ val oldBindings = migrated.keys.map { it.first }.toSet()
+ result = result.copy(bindings = result.bindings.filter { it.id !in oldBindings || result.usersOfBindings(it.id).isNotEmpty() })
+ // Older editor layouts were resolution-specific. Keep each as a selectable saved layout.
+ for (key in ControllerPrefs.prefs(context).all.keys.filter { it.startsWith("layout.") }.sorted()) {
+ val size = key.removePrefix("layout.").split('x').mapNotNull { it.toIntOrNull() }
+ if (size.size != 2 || size.any { it <= 0 } || result.layouts.size >= 128) continue
+ if (size[0] == metrics.widthPixels && size[1] == metrics.heightPixels) continue
+ val id = "migrated.$key"
+ if (result.layouts.none { it.id == id }) result = result.withLayout(SavedInputLayout(id, "Gamepad ${size[0]} × ${size[1]}",
+ LegacyGamepadLayout(surfaceContext, size[0], size[1]).elements(), style = style))
+ }
+ return result.validate()
+ }
+
+ private fun upgradeStockLayouts(library: InputLibrary): InputLibrary {
+ val stock = InputStockLayouts.layouts()
+ val replacements = library.layouts.filter { it.template == InputLayoutTemplate.DECK || it.template == InputLayoutTemplate.TRACKPAD }
+ .associate { old -> old.id to stock.first { it.id == if (old.template == InputLayoutTemplate.DECK) DECK else TRACKPAD }.copy(id = old.id, name = old.name) }
+ var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
+ val migrated = mutableMapOf, String>()
+ for (profile in library.profiles) {
+ val parts = profile.parts.mapValues { (_, part) ->
+ 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 = 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,
+ elements = InputStockLayouts.actions(stockLayout) + old.elements, clicks = InputStockLayouts.clicks(stockLayout) + old.clicks))
+ id
+ }
+ part.copy(bindings = id)
+ }
+ result = result.withProfile(profile.copy(parts = parts))
+ }
+ val oldBindings = migrated.keys.map { it.first }.toSet()
+ result = result.copy(bindings = result.bindings.filter { it.id !in oldBindings || result.usersOfBindings(it.id).isNotEmpty() })
+ for (layout in stock) if (result.layouts.none { it.id == layout.id }) result = result.withLayout(layout)
+ for (preset in InputStockLayouts.presets(stock)) if (result.bindings.none { it.id == preset.id }) result = result.withPreset(preset)
+ 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 }
+ val screen = when {
+ InputRole.PRIMARY in roles && InputRole.SECONDARY in roles -> InputLayoutScreen.BOTH
+ InputRole.PRIMARY in roles -> InputLayoutScreen.MAIN
+ InputRole.SECONDARY in roles -> InputLayoutScreen.SECONDARY
+ layout.id == OVERLAY || layout.id.startsWith("migrated.layout.") -> InputLayoutScreen.MAIN
+ else -> InputLayoutScreen.SECONDARY
+ }
+ layout.copy(screen = screen)
+ })
+
+ internal fun encode(library: InputLibrary): String {
+ val layouts = JSONArray()
+ for (layout in library.layouts) {
+ val elements = JSONArray()
+ for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
+ .put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
+ .put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
+ .put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel))
+ layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
+ .put("tint", layout.style.tint).put("opacity", layout.style.opacity).put("screen", layout.screen.name))
+ }
+ val bindings = JSONArray()
+ for (b in library.bindings) {
+ val controls = JSONObject(); b.controls.forEach { (c, a) -> controls.put(c.id, InputProfiles.encode(a)) }
+ val elements = JSONObject(); b.elements.forEach { (id, a) -> elements.put(id, InputProfiles.encode(a)) }
+ val clicks = JSONObject(); b.clicks.forEach { (id, a) -> clicks.put(id, InputProfiles.encode(a)) }
+ val keys = JSONArray()
+ b.keys.forEach { binding -> keys.put(JSONObject().put("device", binding.key.device).put("name", binding.key.name)
+ .put("keyCode", binding.key.keyCode).put("scanCode", binding.key.scanCode).put("action", InputProfiles.encode(binding.action))) }
+ bindings.put(JSONObject().put("id", b.id).put("name", b.name).put("physical", b.physical)
+ .put("layout", b.layoutId).put("controls", controls).put("elements", elements).put("keys", keys).put("clicks", clicks))
+ }
+ val profiles = JSONArray()
+ for (p in library.profiles) {
+ val parts = JSONObject()
+ p.parts.forEach { (role, part) -> parts.put(role.name, JSONObject().put("bindings", part.bindings).put("layout", part.layout)) }
+ profiles.put(JSONObject().put("id", p.id).put("name", p.name).put("base", p.base).put("parts", parts))
+ }
+ val selections = JSONObject()
+ for ((mode, selection) in library.selections) {
+ val parts = JSONObject()
+ selection.parts.forEach { (role, id) -> parts.put(role.name, id) }
+ selections.put(mode, JSONObject().put("profile", selection.profile).put("parts", parts).put("profileSelected", selection.profileSelected))
+ }
+ return JSONObject().put("selections", selections).put("version", VERSION).put("selected", library.selected).put("steam", library.steam).put("desktop", library.desktop)
+ .put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).toString()
+ }
+
+ internal fun decode(raw: String): InputLibrary? = runCatching {
+ require(raw.length <= 2_000_000)
+ val doc = JSONObject(raw); require(doc.getInt("version") in 2..VERSION)
+ val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
+ val elements = layout.getJSONArray("elements").objects(64).map { e ->
+ InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
+ e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
+ e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
+ e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
+ e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true))
+ }
+ SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")),
+ InputSurfaceStyle(layout.optInt("tint", ControllerPrefs.STEAM_BLUE), layout.optInt("opacity", 100)),
+ InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)))
+ }
+ val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
+ val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
+ val keys = b.getJSONArray("keys").objects(64).map { k -> PhysicalInputBinding(
+ PhysicalInputKey(k.getString("device"), k.getString("name"), k.getInt("keyCode"), k.getInt("scanCode")),
+ requireNotNull(InputProfiles.decode(k.getJSONObject("action")))) }
+ SavedInputBindings(b.getString("id"), b.getString("name"), b.getBoolean("physical"), b.optionalString("layout"),
+ controls, b.getJSONObject("elements").actions(64), keys, b.optJSONObject("clicks")?.actions(64).orEmpty())
+ }
+ val profiles = doc.getJSONArray("profiles").objects(64).map { p ->
+ val parts = p.getJSONObject("parts")
+ SavedInputProfile(p.getString("id"), p.getString("name"), p.getString("base"), InputRole.entries.associateWith { role ->
+ val part = parts.getJSONObject(role.name); InputPart(part.getString("bindings"), part.optionalString("layout"))
+ })
+ }
+ val selections = doc.optJSONObject("selections")?.let { saved ->
+ require(saved.length() <= 2)
+ saved.keys().asSequence().associateWith { mode ->
+ val value = saved.getJSONObject(mode)
+ val parts = value.getJSONObject("parts")
+ require(parts.length() <= InputRole.entries.size)
+ val profile = value.getString("profile")
+ InputSelection(profile, parts.keys().asSequence().associate { role -> InputRole.valueOf(role) to parts.getString(role) },
+ value.optBoolean("profileSelected", profile != InputProfiles.AUTO || parts.length() == 0))
+ }
+ }.orEmpty()
+ InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections).validate()
+ }.getOrNull()
+
+ private fun JSONArray.objects(limit: Int): List {
+ require(length() <= limit)
+ return (0 until length()).map { getJSONObject(it) }
+ }
+
+ private fun JSONObject.actions(limit: Int): Map {
+ require(length() <= limit)
+ return keys().asSequence().associateWith { requireNotNull(InputProfiles.decode(getJSONObject(it))) }
+ }
+
+ private fun JSONObject.optionalString(key: String): String? = if (isNull(key)) null else getString(key)
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt
new file mode 100644
index 0000000000..217e42216a
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt
@@ -0,0 +1,286 @@
+package com.droiddeck.launcher.input
+
+import java.util.UUID
+
+enum class InputLayoutTemplate { CUSTOM, OVERLAY, DECK, TRACKPAD }
+
+enum class InputLayoutScreen { MAIN, SECONDARY, BOTH;
+ fun supports(role: InputRole) = role != InputRole.PHYSICAL && (this == BOTH ||
+ if (role == InputRole.PRIMARY) this == MAIN else this == SECONDARY)
+}
+
+data class InputSurfaceStyle(val tint: Int = ControllerPrefs.STEAM_BLUE, val opacity: Int = 100)
+
+data class SavedInputLayout(
+ val id: String, val name: String, val elements: List = emptyList(),
+ val template: InputLayoutTemplate = InputLayoutTemplate.CUSTOM,
+ val style: InputSurfaceStyle = InputSurfaceStyle(),
+ val screen: InputLayoutScreen = InputLayoutScreen.BOTH,
+) {
+ val editable get() = template == InputLayoutTemplate.CUSTOM
+ fun supports(role: InputRole) = screen.supports(role) && when (template) {
+ InputLayoutTemplate.OVERLAY -> role == InputRole.PRIMARY
+ InputLayoutTemplate.DECK, InputLayoutTemplate.TRACKPAD -> role == InputRole.SECONDARY
+ InputLayoutTemplate.CUSTOM -> true
+ }
+}
+
+data class SavedInputBindings(
+ val id: String, val name: String, val physical: Boolean,
+ val layoutId: String? = null,
+ val controls: Map = emptyMap(),
+ val elements: Map = emptyMap(),
+ val keys: List = emptyList(),
+ val clicks: Map = emptyMap(),
+) {
+ fun compatible(layout: SavedInputLayout?) = if (physical) layout == null
+ else layout != null && if (layout.editable) layoutId == layout.id else layoutId == null
+
+ fun action(element: InputSurfaceElement) = elements[element.id]
+ ?: if (element.id == "legacy:${element.control.id}") controls[element.control] ?: InputAction.Native()
+ else InputAction.Disabled
+
+ fun clickAction(element: InputSurfaceElement) = clicks[element.id]
+ ?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() }
+}
+
+data class InputSelection(
+ val profile: String = InputProfiles.AUTO, val parts: Map = emptyMap(), val profileSelected: Boolean = false,
+)
+
+data class InputPart(val bindings: String, val layout: String? = null)
+
+data class SavedInputProfile(val id: String, val name: String, val base: String, val parts: Map) {
+ fun binding(role: InputRole) = parts.getValue(role).bindings
+}
+
+data class InputLibrary(
+ val profiles: List, val layouts: List, val bindings: List,
+ val selected: String = InputProfiles.AUTO,
+ val steam: String = InputProfile.GAME, val desktop: String = InputProfile.DESKTOP,
+ val selections: Map = emptyMap(),
+) {
+ fun profile(id: String) = profiles.first { it.id == id }
+ fun preset(id: String) = bindings.first { it.id == id }
+ fun layout(profile: String, role: InputRole) = profiles.firstOrNull { it.id == profile }?.parts?.get(role)?.layout
+ ?.let { id -> layouts.firstOrNull { it.id == id } }
+ private fun mode(isDesktop: Boolean) = if (isDesktop) InputProfile.DESKTOP else InputProfile.GAME
+ fun selection(isDesktop: Boolean) = selections[mode(isDesktop)] ?: InputSelection(selected)
+ fun activeId(isDesktop: Boolean): String {
+ val id = selection(isDesktop).profile
+ return if (id == InputProfiles.AUTO) { if (isDesktop) desktop else steam } else id
+ }
+ fun selectProfile(isDesktop: Boolean, id: String) = copy(selections = selections + (mode(isDesktop) to InputSelection(id, profileSelected = true)))
+ fun selectPart(isDesktop: Boolean, role: InputRole, bindingsId: String): InputLibrary {
+ val previous = selection(isDesktop)
+ return copy(selections = selections + (mode(isDesktop) to previous.copy(parts = previous.parts + (role to bindingsId))))
+ }
+ fun activePart(isDesktop: Boolean, role: InputRole): InputPart {
+ val binding = selection(isDesktop).parts[role]?.let(::preset)
+ return if (binding != null) InputPart(binding.id, binding.layoutId) else profile(activeId(isDesktop)).parts.getValue(role)
+ }
+ fun activeLayout(isDesktop: Boolean, role: InputRole) = activePart(isDesktop, role).layout?.let { id -> layouts.first { it.id == id } }
+ fun compileActive(isDesktop: Boolean): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith { preset(activePart(isDesktop, it).bindings) })
+
+ fun saveSelection(isDesktop: Boolean, name: String, id: String = newInputId()): InputLibrary {
+ val current = profile(activeId(isDesktop))
+ var result = withProfile(SavedInputProfile(id, inputName(name), current.base, InputRole.entries.associateWith { activePart(isDesktop, it) }))
+ for (role in InputRole.entries) result = result.usePart(id, role, id, shared = false)
+ return result.selectProfile(isDesktop, id)
+ }
+
+
+ fun compile(id: String): InputProfile {
+ val profile = profile(id)
+ val parts = InputRole.entries.associateWith { preset(profile.binding(it)) }
+ return compileParts(id, parts)
+ }
+
+ private fun compileParts(id: String, parts: Map): InputProfile {
+ return InputProfile(id, parts.mapValues { it.value.controls }.filterValues { it.isNotEmpty() },
+ parts.getValue(InputRole.PHYSICAL).keys,
+ parts.mapValues { it.value.elements }.filterValues { it.isNotEmpty() },
+ parts.mapValues { it.value.clicks }.filterValues { it.isNotEmpty() })
+ }
+
+ fun usersOfBindings(id: String) = profiles.filter { p -> p.parts.values.any { it.bindings == id } }
+ fun selectedBindings(id: String) = selections.values.any { id in it.parts.values }
+ fun usersOfLayout(id: String) = profiles.filter { p -> p.parts.values.any { it.layout == id } }
+ fun withProfile(value: SavedInputProfile) = copy(profiles = profiles.filterNot { it.id == value.id } + value)
+ fun withPreset(value: SavedInputBindings) = copy(bindings = bindings.filterNot { it.id == value.id } + value)
+ fun withLayout(value: SavedInputLayout) = copy(layouts = layouts.filterNot { it.id == value.id } + value,
+ bindings = bindings.map { preset -> if (preset.layoutId != value.id) preset else preset.copy(
+ elements = preset.elements.filter { (id, action) -> value.elements.any { it.id == id && action.validFor(it) } },
+ clicks = preset.clicks.filter { (id, action) -> value.elements.any { it.id == id && it.hasClick && action.validForClick() } }) })
+
+ fun duplicateProfile(id: String, name: String, newId: String = newInputId(), sharePhysical: Boolean = false): InputLibrary {
+ require(profiles.size < 64)
+ var result = withProfile(profile(id).copy(id = newId, name = inputName(name)))
+ for (role in InputRole.entries) result = result.usePart(newId, role, id, shared = sharePhysical && role == InputRole.PHYSICAL)
+ return result
+ }
+
+ fun usePart(profileId: String, role: InputRole, sourceId: String, shared: Boolean): InputLibrary {
+ val target = profile(profileId)
+ val source = profile(sourceId).parts.getValue(role)
+ if (shared) return withProfile(target.copy(parts = target.parts + (role to source)))
+ val sourceLayout = layout(sourceId, role)
+ val name = (target.name + " / " + role.name.lowercase()).take(80)
+ val copiedLayout = sourceLayout?.takeIf { it.editable }?.copy(id = newInputId(), name = name)
+ val copiedBindings = preset(source.bindings).copy(id = newInputId(), name = name,
+ layoutId = copiedLayout?.id ?: preset(source.bindings).layoutId)
+ return (if (copiedLayout == null) this else withLayout(copiedLayout)).withPreset(copiedBindings)
+ .withProfile(target.copy(parts = target.parts + (role to InputPart(copiedBindings.id, copiedLayout?.id ?: source.layout))))
+ }
+
+ fun useLayout(profileId: String, role: InputRole, layoutId: String, shared: Boolean): InputLibrary {
+ val source = layouts.first { it.id == layoutId }
+ require(source.supports(role))
+ val target = profile(profileId)
+ val layout = if (shared || !source.editable) source else source.copy(id = newInputId(), name = (target.name + " / " + source.name).take(80))
+ val previous = preset(target.binding(role))
+ val actions = if (previous.compatible(source)) previous else bindings.firstOrNull { it.compatible(source) } ?: SavedInputBindings(newInputId(), target.name, false,
+ controls = if (source.editable) emptyMap() else InputProfile.defaults(target.base).bindings[role].orEmpty(),
+ elements = if (source.editable) source.elements.associate { it.id to InputAction.Disabled } else emptyMap())
+ val copied = actions.copy(id = newInputId(), name = (target.name + " / " + role.name.lowercase()).take(80),
+ layoutId = layout.id.takeIf { layout.editable })
+ return withLayout(layout).withPreset(copied)
+ .withProfile(target.copy(parts = target.parts + (role to InputPart(copied.id, layout.id))))
+ }
+
+ fun copyBindings(id: String, name: String, profileId: String? = null, role: InputRole? = null, newId: String = newInputId()): InputLibrary {
+ require(bindings.size < 512)
+ var result = withPreset(preset(id).copy(id = newId, name = inputName(name)))
+ if (profileId != null && role != null) result = result.chooseBindings(profileId, role, newId)
+ return result
+ }
+
+ fun chooseBindings(profileId: String, role: InputRole, id: String): InputLibrary {
+ val profile = profile(profileId)
+ require(preset(id).compatible(layout(profileId, role)))
+ return withProfile(profile.copy(parts = profile.parts + (role to profile.parts.getValue(role).copy(bindings = id))))
+ }
+
+ fun chooseLayout(profileId: String, role: InputRole, id: String): InputLibrary {
+ val layout = layouts.first { it.id == id }
+ require(layout.supports(role))
+ val profile = profile(profileId)
+ val previous = preset(profile.binding(role))
+ val compatible = bindings.firstOrNull { it.id == previous.id && it.compatible(layout) }
+ ?: bindings.firstOrNull { it.compatible(layout) }
+ ?: SavedInputBindings(newInputId(), layout.name, false, if (layout.editable) layout.id else null)
+ return withPreset(compatible).withProfile(profile.copy(parts = profile.parts + (role to InputPart(compatible.id, id))))
+ }
+
+ fun copyLayout(id: String, name: String, newId: String = newInputId()): InputLibrary {
+ val source = layouts.first { it.id == id }
+ require(source.editable)
+ return withLayout(source.copy(id = newId, name = inputName(name)))
+ }
+
+ fun removeProfile(id: String): InputLibrary {
+ require(id != InputProfile.GAME && id != InputProfile.DESKTOP)
+ return copy(profiles = profiles.filterNot { it.id == id }, selected = selected.takeUnless { it == id } ?: InputProfiles.AUTO,
+ steam = steam.takeUnless { it == id } ?: InputProfile.GAME, desktop = desktop.takeUnless { it == id } ?: InputProfile.DESKTOP,
+ selections = selections.mapValues { (_, selection) -> if (selection.profile == id) selection.copy(profile = InputProfiles.AUTO) else selection })
+ }
+
+ fun removeLayout(id: String): InputLibrary {
+ require(usersOfLayout(id).isEmpty() && bindings.none { it.layoutId == id && selectedBindings(it.id) } && layouts.first { it.id == id }.editable)
+ return copy(layouts = layouts.filterNot { it.id == id }, bindings = bindings.filterNot { it.layoutId == id })
+ }
+
+ fun removeBindings(id: String): InputLibrary {
+ require(usersOfBindings(id).isEmpty() && !selectedBindings(id))
+ return copy(bindings = bindings.filterNot { it.id == id })
+ }
+
+ fun resetProfile(id: String): InputLibrary {
+ val p = profile(id)
+ var result = this
+ val defaults = InputProfile.defaults(p.base)
+ val parts = p.parts.mapValues { (role, part) ->
+ val previous = preset(part.bindings)
+ val isPrivate = usersOfBindings(part.bindings).all { it.id == id }
+ val preset = SavedInputBindings(if (isPrivate) previous.id else newInputId(),
+ if (isPrivate) previous.name else (p.name + " / " + role.name.lowercase()).take(80), role == InputRole.PHYSICAL,
+ part.layout?.takeIf { layout(id, role)?.editable == true }, defaults.bindings[role].orEmpty(),
+ elements = (layout(id, role)?.let { InputStockLayouts.actions(it) } ?: emptyMap()) + layout(id, role)?.elements.orEmpty().filter { it.id == "builtin:keyboard" }
+ .associate { it.id to InputAction.Command(InputCommand.KEYBOARD) })
+ result = result.withPreset(preset)
+ part.copy(bindings = preset.id)
+ }
+ return result.withProfile(p.copy(parts = parts))
+ }
+
+ fun validate(): InputLibrary {
+ require(profiles.size in 2..64 && layouts.size in 3..256 && bindings.size in 1..512)
+ fun unique(ids: List) { require(ids.all { it.isNotBlank() && it.length <= 128 } && ids.distinct().size == ids.size) }
+ unique(profiles.map { it.id }); unique(layouts.map { it.id }); unique(bindings.map { it.id })
+ require(profiles.any { it.id == InputProfile.GAME } && profiles.any { it.id == InputProfile.DESKTOP })
+ require(selected == InputProfiles.AUTO || profiles.any { it.id == selected })
+ require(profiles.any { it.id == steam } && profiles.any { it.id == desktop })
+ for (layout in layouts) {
+ require(layout.style.opacity in 1..100)
+ inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id })
+ for (e in layout.elements) {
+ inputName(e.name)
+ require(e.icon == 0 || InputButtonIcons.has(e.icon))
+ require(e.image.isEmpty() || e.image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && e.image != "." && e.image != "..")
+ require(e.opacity.isFinite() && e.opacity in 0.01f..1f)
+ require(!e.toggle || e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER)
+ require(listOf(e.x, e.y, e.width, e.height).all { it.isFinite() })
+ require(e == e.bounded())
+ require(if (e.id.startsWith("legacy:")) e.id == "legacy:${e.control.id}" && e.kind == InputElementKind.from(e.control)
+ else e.control == e.kind.control)
+ }
+ }
+ for (preset in bindings) {
+ inputName(preset.name)
+ require(preset.controls.all { (c, a) -> a.validFor(c) })
+ require(preset.elements.size <= 64 && preset.keys.size <= 64 && preset.clicks.size <= 64)
+ require(preset.keys.map { Triple(it.key.device, it.key.keyCode, it.key.scanCode) }.distinct().size == preset.keys.size)
+ require(preset.physical || preset.keys.isEmpty())
+ val layout = preset.layoutId?.let { id -> layouts.first { it.id == id } }
+ require(!preset.physical || layout == null && preset.elements.isEmpty() && preset.clicks.isEmpty())
+ require(preset.elements.all { (id, action) -> layout?.elements?.firstOrNull { it.id == id }?.let { action.validFor(it) } == true })
+ require(preset.clicks.all { (id, action) -> layout?.elements?.any { it.id == id && it.hasClick } == true && action.validForClick() })
+ require(preset.keys.all { it.key.device.isNotBlank() && it.key.keyCode >= 0 && it.key.scanCode >= 0 &&
+ it.action.validFor(InputControl.A) && (it.action !is InputAction.Native || it.action.target == null) })
+ }
+ require(selections.keys.all { it == InputProfile.GAME || it == InputProfile.DESKTOP })
+ for (selection in selections.values) {
+ require(selection.profile == InputProfiles.AUTO || profiles.any { it.id == selection.profile })
+ for ((role, id) in selection.parts) {
+ val binding = preset(id)
+ require(binding.physical == (role == InputRole.PHYSICAL))
+ val layout = binding.layoutId?.let { lid -> layouts.first { it.id == lid } }
+ require(binding.compatible(layout) && (layout == null || layout.supports(role)))
+ }
+ }
+ for (p in profiles) {
+ inputName(p.name); require(p.base == InputProfile.GAME || p.base == InputProfile.DESKTOP)
+ require(p.parts.keys == InputRole.entries.toSet())
+ for ((role, part) in p.parts) {
+ val layout = part.layout?.let { id -> layouts.first { it.id == id } }
+ require(if (role == InputRole.PHYSICAL) layout == null else layout?.supports(role) == true)
+ require(preset(part.bindings).compatible(layout))
+ }
+ }
+ return this
+ }
+}
+
+internal fun inputName(value: String): String = value.trim().also { require(it.isNotEmpty() && it.length <= 80) }
+fun newInputId(): String = UUID.randomUUID().toString()
+
+internal fun InputAction.validFor(element: InputSurfaceElement): Boolean = when {
+ this !is InputAction.Native -> validFor(element.control)
+ element.id.startsWith("legacy:") -> validFor(element.control)
+ element.kind == InputElementKind.DPAD -> target == null
+ target == null -> false
+ element.kind == InputElementKind.TRACKPAD -> target.isTrackpad
+ element.kind == InputElementKind.STICK -> target == InputControl.LS || target == InputControl.RS
+ element.kind == InputElementKind.TRIGGER -> target == InputControl.LT || target == InputControl.RT
+ else -> target.dimensions == 1 && target != InputControl.LT && target != InputControl.RT
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputMotion.kt b/app/src/main/java/com/droiddeck/launcher/input/InputMotion.kt
new file mode 100644
index 0000000000..9d24ca8d54
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputMotion.kt
@@ -0,0 +1,35 @@
+package com.droiddeck.launcher.input
+
+import android.os.Handler
+import android.os.Looper
+import android.view.Choreographer
+
+class InputMotion(private val router: () -> InputRouter?) : Choreographer.FrameCallback {
+ private val handler = Handler(Looper.getMainLooper())
+ private var scheduled = false
+ private var lastFrame = 0L
+ private val start = Runnable {
+ if (!scheduled) {
+ scheduled = true
+ lastFrame = System.nanoTime()
+ Choreographer.getInstance().postFrameCallback(this)
+ }
+ }
+
+ fun request() {
+ if (Looper.myLooper() == Looper.getMainLooper()) start.run() else handler.post(start)
+ }
+
+ override fun doFrame(frameTimeNanos: Long) {
+ val dt = (frameTimeNanos - lastFrame).coerceAtLeast(0) / 1_000_000_000f
+ lastFrame = frameTimeNanos
+ if (router()?.tick(dt) == true) Choreographer.getInstance().postFrameCallback(this)
+ else scheduled = false
+ }
+
+ fun stop() {
+ handler.removeCallbacks(start)
+ Choreographer.getInstance().removeFrameCallback(this)
+ scheduled = false
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt b/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt
new file mode 100644
index 0000000000..2375cf34e8
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt
@@ -0,0 +1,107 @@
+package com.droiddeck.launcher.input
+
+enum class InputRole { PHYSICAL, PRIMARY, SECONDARY }
+
+enum class InputControl(val id: String, val label: String, val dimensions: Int = 1) {
+ A("a", "A"), B("b", "B"), X("x", "X"), Y("y", "Y"),
+ LB("lb", "L1"), RB("rb", "R1"), SELECT("select", "View / Select"), START("start", "Menu / Start"),
+ L3("l3", "L3"), R3("r3", "R3"), GUIDE("guide", "Steam / Guide"), QAM("qam", "Quick access"),
+ UP("up", "D-pad up"), RIGHT("right", "D-pad right"), DOWN("down", "D-pad down"), LEFT("left", "D-pad left"),
+ LT("lt", "L2"), RT("rt", "R2"), LS("ls", "Left stick", 2), RS("rs", "Right stick", 2),
+ L4("l4", "L4"), R4("r4", "R4"), L5("l5", "L5"), R5("r5", "R5"),
+ LEFT_PAD("left-pad", "Left trackpad", 2), RIGHT_PAD("right-pad", "Right trackpad", 2),
+ LEFT_CLICK("left-click", "Left trackpad click"), RIGHT_CLICK("right-click", "Right trackpad click");
+
+ val isPad: Boolean get() = ordinal <= RS.ordinal
+ val isTrackpad: Boolean get() = this == LEFT_PAD || this == RIGHT_PAD
+
+ companion object {
+ val padControls = entries.filter { it.isPad }.toTypedArray()
+ fun fromId(id: String) = entries.firstOrNull { it.id == id }
+ }
+}
+
+enum class InputCommand { MENU, KEYBOARD, STEAM, QUICK_ACCESS }
+
+sealed interface InputAction {
+ data class Native(val target: InputControl? = null) : InputAction
+ data object Disabled : InputAction
+ data class Keys(val codes: List) : InputAction
+ data class MouseButton(val code: Int) : InputAction
+ data class Command(val command: InputCommand) : InputAction
+ data class Directions(val up: Int, val right: Int, val down: Int, val left: Int, val diagonals: List? = null) : InputAction
+ data class Pointer(val speed: Float = 900f) : InputAction
+ data class Scroll(val speed: Float = 10f, val horizontal: Boolean = false) : InputAction
+}
+
+data class InputProfile(
+ val id: String,
+ val bindings: Map> = emptyMap(),
+ val keys: List = emptyList(),
+ val elements: Map> = emptyMap(),
+ val clicks: Map> = emptyMap(),
+) {
+ fun action(role: InputRole, control: InputControl): InputAction =
+ bindings[role]?.get(control) ?: InputAction.Native()
+
+ fun withBinding(role: InputRole, control: InputControl, action: InputAction) =
+ copy(bindings = bindings + (role to (bindings[role].orEmpty() + (control to action))))
+
+ fun elementAction(role: InputRole, id: String, control: InputControl): InputAction =
+ elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else InputAction.Disabled
+
+ fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
+ ?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
+
+ companion object {
+ const val GAME = "game"
+ const val DESKTOP = "desktop"
+
+ fun defaults(id: String): InputProfile {
+ if (id != DESKTOP) return InputProfile(GAME)
+ val desktop = mapOf(
+ InputControl.LS to InputAction.Pointer(), InputControl.RS to InputAction.Scroll(),
+ InputControl.A to InputAction.MouseButton(272), InputControl.B to InputAction.MouseButton(273),
+ InputControl.X to InputAction.Keys(listOf(28)), InputControl.Y to InputAction.Keys(listOf(1)),
+ InputControl.UP to InputAction.Keys(listOf(103)), InputControl.RIGHT to InputAction.Keys(listOf(106)),
+ InputControl.DOWN to InputAction.Keys(listOf(108)), InputControl.LEFT to InputAction.Keys(listOf(105)),
+ InputControl.LT to InputAction.MouseButton(273), InputControl.RT to InputAction.MouseButton(272),
+ InputControl.LB to InputAction.Keys(listOf(29)), InputControl.RB to InputAction.Keys(listOf(56)),
+ InputControl.SELECT to InputAction.Command(InputCommand.KEYBOARD),
+ InputControl.START to InputAction.Command(InputCommand.MENU),
+ InputControl.LEFT_PAD to InputAction.Scroll(), InputControl.RIGHT_PAD to InputAction.Pointer(),
+ InputControl.LEFT_CLICK to InputAction.MouseButton(273), InputControl.RIGHT_CLICK to InputAction.MouseButton(272),
+ )
+ return InputProfile(DESKTOP, InputRole.entries.associateWith { desktop })
+ }
+ }
+}
+
+internal fun defaultElementClick(element: InputSurfaceElement, action: InputAction, legacy: (InputControl) -> InputAction): InputAction {
+ fun click(control: InputControl) = when (control) {
+ InputControl.LS -> InputControl.L3; InputControl.RS -> InputControl.R3
+ InputControl.LEFT_PAD -> InputControl.LEFT_CLICK; InputControl.RIGHT_PAD -> InputControl.RIGHT_CLICK
+ else -> null
+ }
+ if (!element.hasClick) return InputAction.Disabled
+ if (element.id == "legacy:${element.control.id}") {
+ val target = click(element.control) ?: return InputAction.Disabled
+ return legacy(target).let { if (it is InputAction.Native && it.target == null) InputAction.Native(target) else it }
+ }
+ return (action as? InputAction.Native)?.let { click(it.target ?: element.control) }?.let { InputAction.Native(it) } ?: InputAction.Disabled
+}
+
+internal fun InputAction.validForClick(): Boolean = if (this is InputAction.Native)
+ target != null && target.dimensions == 1 && target != InputControl.LT && target != InputControl.RT
+else validFor(InputControl.A)
+
+internal fun InputAction.validFor(control: InputControl): Boolean = when (this) {
+ is InputAction.Native -> target == null || (control.isPad == target.isPad && control.dimensions == target.dimensions &&
+ (!control.isTrackpad && !target.isTrackpad || control.isTrackpad && target.isTrackpad))
+ is InputAction.Keys -> codes.isNotEmpty() && codes.size <= 8 && codes.distinct().size == codes.size && codes.all { it in 1..255 }
+ is InputAction.MouseButton -> code in 272..276
+ is InputAction.Directions -> control.dimensions == 2 && listOf(up, right, down, left).all { it in 0..255 } && (diagonals == null || diagonals.size == 4 && diagonals.all { it in 0..255 })
+ is InputAction.Pointer -> control.dimensions == 2 && speed.isFinite() && speed in 100f..3000f
+ is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f
+ else -> true
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputProfiles.kt b/app/src/main/java/com/droiddeck/launcher/input/InputProfiles.kt
new file mode 100644
index 0000000000..16d41bfd0b
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputProfiles.kt
@@ -0,0 +1,139 @@
+package com.droiddeck.launcher.input
+
+import android.content.Context
+import org.json.JSONArray
+import org.json.JSONObject
+
+object InputProfiles {
+ const val AUTO = "auto"
+ private const val VERSION = 1
+
+ private fun prefs(context: Context) = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
+
+ fun selection(context: Context): String = InputLibraries.read(context).selected
+
+ fun select(context: Context, id: String) {
+ InputLibraries.update(context) { library ->
+ require(id == AUTO || library.profiles.any { it.id == id })
+ library.copy(selected = id, selections = emptyMap())
+ }
+ }
+
+ fun active(context: Context, desktop: Boolean): InputProfile {
+ val library = InputLibraries.read(context)
+ return library.compileActive(desktop)
+ }
+
+ fun read(context: Context, id: String): InputProfile {
+ return InputLibraries.read(context).compile(id)
+ }
+
+ internal fun readLegacy(context: Context, id: String): InputProfile {
+ migrate(context)
+ var result = InputProfile.defaults(id)
+ val stored = prefs(context).getString("profile.$id", null) ?: return result
+ val document = runCatching { JSONObject(stored) }.getOrNull() ?: return result
+ if (document.optInt("version") != VERSION) return result
+ val bindings = document.optJSONArray("bindings") ?: return result
+ for (i in 0 until minOf(bindings.length(), 256)) {
+ val entry = bindings.optJSONObject(i) ?: continue
+ val role = runCatching { InputRole.valueOf(entry.getString("role")) }.getOrNull() ?: continue
+ val control = InputControl.fromId(entry.optString("control")) ?: continue
+ val action = decode(entry.optJSONObject("action") ?: continue) ?: continue
+ if (action.validFor(control)) result = result.withBinding(role, control, action)
+ }
+ val keys = document.optJSONArray("keys")
+ if (keys != null) result = result.copy(keys = (0 until minOf(keys.length(), 64)).mapNotNull { i ->
+ runCatching {
+ val item = keys.getJSONObject(i)
+ val action = decode(item.getJSONObject("action")) ?: return@mapNotNull null
+ if (!action.validFor(InputControl.A) || action is InputAction.Native && action.target != null) return@mapNotNull null
+ val key = PhysicalInputKey(item.getString("device"), item.getString("name"), item.getInt("keyCode"), item.getInt("scanCode"))
+ if (key.device.isBlank() || key.keyCode < 0 || key.scanCode < 0) return@mapNotNull null
+ PhysicalInputBinding(key, action)
+ }.getOrNull()
+ }.distinctBy { Triple(it.key.device, it.key.keyCode, it.key.scanCode) })
+ return result
+ }
+
+ fun save(context: Context, profile: InputProfile) {
+ InputLibraries.update(context) { library ->
+ val definition = library.profile(profile.id)
+ var updated = library
+ for (role in InputRole.entries) {
+ val preset = updated.preset(definition.binding(role))
+ updated = updated.withPreset(preset.copy(controls = profile.bindings[role].orEmpty(),
+ elements = profile.elements[role].orEmpty(), keys = if (role == InputRole.PHYSICAL) profile.keys else emptyList(),
+ clicks = profile.clicks[role].orEmpty()))
+ }
+ updated
+ }
+ }
+
+ private fun saveLegacy(context: Context, profile: InputProfile) {
+ val bindings = JSONArray()
+ for ((role, controls) in profile.bindings) for ((control, action) in controls) {
+ require(action.validFor(control))
+ bindings.put(JSONObject().put("role", role.name).put("control", control.id).put("action", encode(action)))
+ }
+ val keys = JSONArray()
+ for (binding in profile.keys) keys.put(JSONObject().put("device", binding.key.device).put("name", binding.key.name)
+ .put("keyCode", binding.key.keyCode).put("scanCode", binding.key.scanCode).put("action", encode(binding.action)))
+ prefs(context).edit().putString("profile.${profile.id}", JSONObject()
+ .put("version", VERSION).put("id", profile.id).put("bindings", bindings).put("keys", keys).toString()).apply()
+ }
+
+ fun reset(context: Context, id: String) = InputLibraries.update(context) { it.resetProfile(id) }.let { }
+
+ fun resetAll(context: Context) {
+ prefs(context).edit().clear().putBoolean("migrated", true).apply()
+ InputSurfaceLayout.resetAll(context)
+ }
+
+ private fun migrate(context: Context) {
+ val p = prefs(context)
+ if (p.getBoolean("migrated", false)) return
+ var game = InputProfile.defaults(InputProfile.GAME)
+ val old = ControllerPrefs.read(context)
+ for ((id, target) in old.mapping) {
+ val source = InputControl.fromId(id) ?: continue
+ val action = if (target == ControllerPrefs.OFF) InputAction.Disabled
+ else InputAction.Native(InputControl.fromId(target) ?: continue)
+ if (target != id) game = game.withBinding(InputRole.PRIMARY, source, action)
+ }
+ if (old.selectSteam) game = game.withBinding(InputRole.PHYSICAL, InputControl.SELECT, InputAction.Native(InputControl.GUIDE))
+ if (!p.contains("profile.${InputProfile.GAME}")) saveLegacy(context, game)
+ if (old.selectSteam && !p.contains("profile.${InputProfile.DESKTOP}")) {
+ saveLegacy(context, InputProfile.defaults(InputProfile.DESKTOP)
+ .withBinding(InputRole.PHYSICAL, InputControl.SELECT, InputAction.Native(InputControl.GUIDE)))
+ }
+ p.edit().putBoolean("migrated", true).apply()
+ }
+
+ internal fun encode(action: InputAction): JSONObject = JSONObject().apply {
+ when (action) {
+ is InputAction.Native -> { put("type", "native"); action.target?.let { put("target", it.id) } }
+ InputAction.Disabled -> put("type", "disabled")
+ is InputAction.Keys -> { put("type", "keys"); put("codes", JSONArray(action.codes)) }
+ is InputAction.MouseButton -> { put("type", "button"); put("code", action.code) }
+ is InputAction.Command -> { put("type", "command"); put("command", action.command.name) }
+ is InputAction.Directions -> { put("type", "directions"); put("codes", JSONArray(listOf(action.up, action.right, action.down, action.left))); action.diagonals?.let { put("diagonals", JSONArray(it)) } }
+ is InputAction.Pointer -> { put("type", "pointer"); put("speed", action.speed.toDouble()) }
+ is InputAction.Scroll -> { put("type", "scroll"); put("speed", action.speed.toDouble()); put("horizontal", action.horizontal) }
+ }
+ }
+
+ internal fun decode(json: JSONObject): InputAction? = runCatching {
+ when (json.getString("type")) {
+ "native" -> InputAction.Native(if (json.has("target")) InputControl.fromId(json.getString("target")) ?: return null else null)
+ "disabled" -> InputAction.Disabled
+ "keys" -> InputAction.Keys(json.getJSONArray("codes").let { a -> (0 until a.length()).map { a.getInt(it) } })
+ "button" -> InputAction.MouseButton(json.getInt("code"))
+ "command" -> InputAction.Command(InputCommand.valueOf(json.getString("command")))
+ "directions" -> json.getJSONArray("codes").let { InputAction.Directions(it.getInt(0), it.getInt(1), it.getInt(2), it.getInt(3), json.optJSONArray("diagonals")?.let { d -> (0 until d.length()).map { d.getInt(it) } }) }
+ "pointer" -> InputAction.Pointer(json.getDouble("speed").toFloat())
+ "scroll" -> InputAction.Scroll(json.getDouble("speed").toFloat(), json.optBoolean("horizontal", false))
+ else -> null
+ }
+ }.getOrNull()
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputRouter.kt b/app/src/main/java/com/droiddeck/launcher/input/InputRouter.kt
new file mode 100644
index 0000000000..24b45ed1ef
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputRouter.kt
@@ -0,0 +1,360 @@
+package com.droiddeck.launcher.input
+
+import kotlin.math.abs
+
+interface InputOutput {
+ fun key(code: Int, down: Boolean)
+ fun button(code: Int, down: Boolean)
+ fun pointer(dx: Float, dy: Float)
+ fun scroll(steps: Int)
+ fun scrollHorizontal(steps: Int) {}
+ fun command(command: InputCommand)
+ fun requestMotion()
+}
+
+class InputRouter(private val output: InputOutput) {
+ private val keys = IntArray(256)
+ private val buttons = IntArray(5)
+ private val channels = ArrayList()
+ private val pads = ArrayList()
+ private var profile = InputProfile.defaults(InputProfile.GAME)
+ private var moving = false
+ private var wheel = 0f
+ private var horizontalWheel = 0f
+ private var enabled = true
+ private val snapshots = ArrayList<() -> Unit>()
+
+ @Synchronized
+ fun beforeProfileChange(snapshot: () -> Unit) { snapshots.add(snapshot) }
+
+ @Synchronized
+ fun removeSnapshot(snapshot: () -> Unit) { snapshots.remove(snapshot) }
+
+ @Synchronized
+ fun setEnabled(on: Boolean): Boolean {
+ if (enabled == on) return false
+ if (!on) releaseAll()
+ enabled = on
+ for (pad in pads) pad.refreshIdentity()
+ return true
+ }
+
+ @Synchronized
+ fun setProfile(next: InputProfile) {
+ if (profile == next) return
+ for (snapshot in snapshots) snapshot()
+ for (pad in pads) pad.snapshot()
+ profile = next
+ for (channel in channels) channel.configure(channel.actionFrom(next))
+ for (pad in pads) pad.refreshIdentity()
+ wheel = 0f
+ horizontalWheel = 0f
+ moving = false
+ }
+
+ @JvmOverloads
+ @Synchronized
+ fun pad(role: InputRole, retained: PadState? = null): PadSource = PadSource(role, retained).also { pads.add(it) }
+
+ @Synchronized
+ fun channel(role: InputRole, control: InputControl, fixedAction: InputAction? = null, element: InputSurfaceElement? = null, elementClick: Boolean = false): Channel = Channel(role, control, fixedAction, element, elementClick).also {
+ channels.add(it)
+ it.configure(it.actionFrom(profile))
+ }
+
+ @Synchronized
+ fun releaseAll() {
+ for (snapshot in snapshots) snapshot()
+ for (pad in pads) pad.snapshot()
+ for (channel in channels) channel.suspend()
+ for (pad in pads) pad.refreshIdentity()
+ wheel = 0f
+ horizontalWheel = 0f
+ moving = false
+ }
+
+ @Synchronized
+ fun tick(seconds: Float): Boolean {
+ if (!enabled) return false
+ var x = 0f
+ var y = 0f
+ var scroll = 0f
+ var horizontalScroll = 0f
+ for (channel in channels) {
+ if (channel.blocked || channel.control.isTrackpad) continue
+ val cx = if (abs(channel.x) > 0.12f) channel.x else 0f
+ val cy = if (abs(channel.y) > 0.12f) channel.y else 0f
+ when (val action = channel.action) {
+ is InputAction.Pointer -> { x += cx * action.speed; y += cy * action.speed }
+ is InputAction.Scroll -> if (action.horizontal) horizontalScroll += cx * action.speed else scroll += cy * action.speed
+ else -> Unit
+ }
+ }
+ val dt = seconds.coerceIn(0f, 0.05f)
+ if (x != 0f || y != 0f) output.pointer(x * dt, y * dt)
+ wheel += scroll * dt
+ horizontalWheel += horizontalScroll * dt
+ flushWheel()
+ moving = x != 0f || y != 0f || scroll != 0f || horizontalScroll != 0f
+ return moving
+ }
+
+ private fun flushWheel() {
+ val steps = wheel.toInt()
+ if (steps != 0) { wheel -= steps; output.scroll(steps) }
+ val horizontalSteps = horizontalWheel.toInt()
+ if (horizontalSteps != 0) { horizontalWheel -= horizontalSteps; output.scrollHorizontal(horizontalSteps) }
+ }
+
+ private fun key(code: Int, down: Boolean) {
+ val was = keys[code]
+ keys[code] = (was + if (down) 1 else -1).coerceAtLeast(0)
+ if ((was == 0) != (keys[code] == 0)) output.key(code, down)
+ }
+
+ private fun button(code: Int, down: Boolean) {
+ val at = code - 272
+ val was = buttons[at]
+ buttons[at] = (was + if (down) 1 else -1).coerceAtLeast(0)
+ if ((was == 0) != (buttons[at] == 0)) output.button(code, down)
+ }
+
+ inner class Channel internal constructor(val role: InputRole, val control: InputControl, private val fixedAction: InputAction?, private val element: InputSurfaceElement?, private val elementClick: Boolean) {
+ var action: InputAction = InputAction.Native()
+ private set
+ internal var x = 0f
+ internal var y = 0f
+ internal var contact = false
+ internal var blocked = false
+ private var held = false
+ private val directions = BooleanArray(4)
+ private var radialKeys = emptyList()
+
+ internal fun actionFrom(profile: InputProfile) = element?.let { if (elementClick) profile.elementClickAction(role, it) else profile.elementAction(role, it.id, control) }
+ ?: profile.action(role, control)
+
+ internal fun configure(next: InputAction) {
+ suspend()
+ action = (fixedAction ?: next).takeIf { if (elementClick) it.validForClick() else if (element != null) it.validFor(element) else it.validFor(control) }
+ ?: if (element != null) InputAction.Disabled else InputAction.Native()
+ }
+
+ internal fun observe(value: Float, second: Float = 0f, touching: Boolean = false) {
+ x = value; y = second; contact = touching
+ }
+
+ internal fun awaitNeutral(value: Float, second: Float, touching: Boolean) = synchronized(this@InputRouter) {
+ observe(value, second, touching)
+ suspend()
+ }
+
+ internal fun nativeIdentity(): Boolean = enabled && !blocked && (action as? InputAction.Native)?.target == null && action is InputAction.Native
+
+ internal fun suspend() {
+ releaseOutputs()
+ blocked = contact || abs(x) > 0.12f || abs(y) > 0.12f
+ }
+
+ fun release() = synchronized(this@InputRouter) {
+ releaseOutputs()
+ x = 0f; y = 0f; contact = false; blocked = false
+ }
+
+ fun close() = synchronized(this@InputRouter) {
+ release()
+ channels.remove(this)
+ }
+
+ fun acceptsPointerGesture() = synchronized(this@InputRouter) { enabled && !blocked && contact && action is InputAction.Pointer }
+
+ fun pointerDelta(dx: Float, dy: Float) = synchronized(this@InputRouter) {
+ val pointer = action as? InputAction.Pointer
+ if (enabled && !blocked && contact && pointer != null && dx.isFinite() && dy.isFinite()) output.pointer(dx * pointer.speed, dy * pointer.speed)
+ }
+
+ fun wheelSteps(steps: Int) = synchronized(this@InputRouter) {
+ val scroll = action as? InputAction.Scroll
+ if (enabled && !blocked && scroll != null && steps != 0) {
+ if (scroll.horizontal) output.scrollHorizontal(steps) else output.scroll(steps)
+ }
+ }
+
+ fun update(value: Float, second: Float = 0f, touching: Boolean = false): InputControl? = synchronized(this@InputRouter) {
+ val oldX = x
+ val oldY = y
+ val oldContact = contact
+ x = value.coerceIn(-1f, 1f)
+ y = second.coerceIn(-1f, 1f)
+ contact = touching
+ if (!enabled) {
+ blocked = contact || abs(x) > 0.12f || abs(y) > 0.12f
+ return@synchronized null
+ }
+ if (blocked) {
+ if (!contact && abs(x) <= 0.12f && abs(y) <= 0.12f) blocked = false
+ return@synchronized null
+ }
+ when (val a = action) {
+ is InputAction.Native -> return@synchronized a.target ?: control
+ is InputAction.Disabled -> Unit
+ is InputAction.Pointer -> {
+ if (control.isTrackpad) {
+ if (contact && oldContact) output.pointer((x - oldX) * a.speed, -(y - oldY) * a.speed)
+ } else requestMotion()
+ }
+ is InputAction.Scroll -> {
+ if (control.isTrackpad) {
+ if (contact && oldContact) {
+ if (a.horizontal) horizontalWheel -= (x - oldX) * a.speed else wheel += (y - oldY) * a.speed
+ flushWheel()
+ }
+ } else requestMotion()
+ }
+ is InputAction.Directions -> {
+ val vertical = if (control.isTrackpad) -y else y
+ if (a.diagonals == null) {
+ direction(0, -vertical, a.up); direction(1, x, a.right)
+ direction(2, vertical, a.down); direction(3, -x, a.left)
+ } else {
+ val cardinal = listOf(a.up, a.right, a.down, a.left)
+ val sector = ((kotlin.math.round(Math.toDegrees(kotlin.math.atan2(vertical, x).toDouble()) / 45).toInt() + 2) % 8 + 8) % 8
+ val next = if (kotlin.math.hypot(x, vertical) < .24f) emptyList() else if (sector % 2 == 0) listOf(cardinal[sector / 2])
+ else a.diagonals[sector / 2].let { if (it != 0) listOf(it) else listOf(cardinal[sector / 2], cardinal[(sector / 2 + 1) % 4]) }
+ val codes = next.filter { it != 0 }.distinct()
+ radialKeys.filterNot { it in codes }.forEach { key(it, false) }
+ codes.filterNot { it in radialKeys }.forEach { key(it, true) }
+ radialKeys = codes
+ }
+ }
+ else -> {
+ val down = if (control.isTrackpad) contact else maxOf(abs(x), abs(y)) > if (held) 0.35f else 0.55f
+ if (held != down) {
+ held = down
+ when (a) {
+ is InputAction.Keys -> if (down) a.codes.forEach { key(it, true) } else a.codes.asReversed().forEach { key(it, false) }
+ is InputAction.MouseButton -> button(a.code, down)
+ is InputAction.Command -> if (down) output.command(a.command)
+ else -> Unit
+ }
+ }
+ }
+ }
+ null
+ }
+
+ private fun requestMotion() {
+ if (!moving && (abs(x) > 0.12f || abs(y) > 0.12f)) { moving = true; output.requestMotion() }
+ }
+
+ private fun direction(at: Int, value: Float, code: Int) {
+ val down = value > if (directions[at]) 0.35f else 0.55f
+ if (directions[at] != down) { directions[at] = down; if (code != 0) key(code, down) }
+ }
+
+ private fun releaseOutputs() {
+ when (val a = action) {
+ is InputAction.Keys -> if (held) a.codes.asReversed().forEach { key(it, false) }
+ is InputAction.MouseButton -> if (held) button(a.code, false)
+ is InputAction.Directions -> {
+ val codes = intArrayOf(a.up, a.right, a.down, a.left)
+ for (i in directions.indices) if (directions[i] && codes[i] != 0) key(codes[i], false)
+ }
+ else -> Unit
+ }
+ radialKeys.forEach { key(it, false) }; radialKeys = emptyList()
+ held = false
+ directions.fill(false)
+ }
+ }
+
+ inner class PadSource internal constructor(role: InputRole, retained: PadState?) {
+ private val routes = Array(InputControl.padControls.size) { channel(role, InputControl.padControls[it]) }
+ private val result = PadState()
+ private var last: PadState? = null
+ private var identity = true
+ private var nativeCandidate = true
+
+ init {
+ last = retained
+ if (retained != null) for (route in routes) {
+ route.awaitNeutral(retained.value(route.control), retained.secondValue(route.control), false)
+ }
+ refreshIdentity()
+ }
+
+ internal fun refreshIdentity() {
+ nativeCandidate = routes.all { (it.action as? InputAction.Native)?.target == null && it.action is InputAction.Native }
+ identity = enabled && nativeCandidate && routes.none { it.blocked }
+ }
+
+ internal fun snapshot() {
+ val raw = last ?: return
+ for (route in routes) {
+ route.x = raw.value(route.control)
+ route.y = raw.secondValue(route.control)
+ }
+ }
+
+ fun route(raw: PadState): PadState = synchronized(this@InputRouter) {
+ last = raw
+ if (identity) return@synchronized raw
+ result.clear()
+ for (route in routes) {
+ val x = raw.value(route.control)
+ val y = raw.secondValue(route.control)
+ val target = route.update(x, y) ?: continue
+ result.add(target, x, y)
+ }
+ if (nativeCandidate && enabled && routes.none { it.blocked }) identity = true
+ result
+ }
+
+ fun release() = synchronized(this@InputRouter) {
+ for (route in routes) route.release()
+ last = null
+ result.clear()
+ refreshIdentity()
+ }
+
+ fun close() = synchronized(this@InputRouter) {
+ release()
+ for (route in routes) route.close()
+ pads.remove(this)
+ }
+ }
+}
+
+private val padButtons = intArrayOf(PadState.A, PadState.B, PadState.X, PadState.Y, PadState.LB, PadState.RB,
+ PadState.SELECT, PadState.START, PadState.L3, PadState.R3, PadState.GUIDE, PadState.QAM)
+
+internal fun PadState.value(control: InputControl): Float = when (control) {
+ InputControl.UP -> if (up) 1f else 0f
+ InputControl.RIGHT -> if (right) 1f else 0f
+ InputControl.DOWN -> if (down) 1f else 0f
+ InputControl.LEFT -> if (left) 1f else 0f
+ InputControl.LT -> leftTrigger
+ InputControl.RT -> rightTrigger
+ InputControl.LS -> leftX
+ InputControl.RS -> rightX
+ else -> if (control.ordinal < padButtons.size && isDown(padButtons[control.ordinal])) 1f else 0f
+}
+
+internal fun PadState.secondValue(control: InputControl): Float = when (control) {
+ InputControl.LS -> leftY
+ InputControl.RS -> rightY
+ else -> 0f
+}
+
+internal fun PadState.add(control: InputControl, x: Float, y: Float = 0f) {
+ when (control) {
+ InputControl.UP -> up = up || x > 0.5f
+ InputControl.RIGHT -> right = right || x > 0.5f
+ InputControl.DOWN -> down = down || x > 0.5f
+ InputControl.LEFT -> left = left || x > 0.5f
+ InputControl.LT -> leftTrigger = maxOf(leftTrigger, x)
+ InputControl.RT -> rightTrigger = maxOf(rightTrigger, x)
+ InputControl.LS -> if (x * x + y * y > leftX * leftX + leftY * leftY) { leftX = x; leftY = y }
+ InputControl.RS -> if (x * x + y * y > rightX * rightX + rightY * rightY) { rightX = x; rightY = y }
+ else -> if (control.ordinal < padButtons.size && x > 0.5f) press(padButtons[control.ordinal], true)
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputStockLayouts.kt b/app/src/main/java/com/droiddeck/launcher/input/InputStockLayouts.kt
new file mode 100644
index 0000000000..3ca108c533
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputStockLayouts.kt
@@ -0,0 +1,41 @@
+package com.droiddeck.launcher.input
+
+internal object InputStockLayouts {
+ const val DECK = "preset.deck"
+ const val TRACKPAD = "preset.trackpad"
+ private fun commands(indices: List): List {
+ val names = listOf("DroidDeck menu", "Keyboard", "Steam", "Quick access")
+ val icons = listOf(InputButtonIcons.MENU, InputButtonIcons.KEYBOARD, InputButtonIcons.STEAM, InputButtonIcons.QUICK_ACCESS)
+ val step = .98f / indices.size
+ return indices.mapIndexed { position, i ->
+ InputSurfaceElement(InputControl.A, .02f + position * step, .01f, step - .02f, .11f,
+ "command:$i", name = names[i], icon = icons[i])
+ }
+ }
+ private fun commandActions(): Map = listOf(InputCommand.MENU, InputCommand.KEYBOARD, InputCommand.STEAM, InputCommand.QUICK_ACCESS)
+ .mapIndexed { i, command -> "command:$i" to InputAction.Command(command) }.toMap()
+ private fun grips() = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4).mapIndexed { i, c ->
+ InputSurfaceElement(c, .02f + i * .245f, .78f, .225f, .20f)
+ }
+ private fun pads() = listOf(InputSurfaceElement(InputControl.LEFT_PAD, .02f, .14f, .47f, .62f),
+ InputSurfaceElement(InputControl.RIGHT_PAD, .51f, .14f, .47f, .62f))
+ fun layouts() = listOf(
+ SavedInputLayout(InputLibraries.DECK, "Deck grips + trackpads", commands(listOf(2, 3, 0)) + pads() + grips(), screen = InputLayoutScreen.SECONDARY),
+ SavedInputLayout(InputLibraries.TRACKPAD, "Trackpad + keyboard", commands(listOf(0, 1)) +
+ InputSurfaceElement(InputControl.RIGHT_PAD, .02f, .14f, .96f, .84f, mouseGestures = true), screen = InputLayoutScreen.SECONDARY),
+ )
+
+ fun actions(layout: SavedInputLayout): Map = (commandActions() + if (layout.id == InputLibraries.TRACKPAD) mapOf(
+ "legacy:right-pad" to InputAction.Pointer(), "legacy:a" to InputAction.MouseButton(272), "legacy:b" to InputAction.MouseButton(273),
+ ) else emptyMap()).filterKeys { id -> layout.elements.any { it.id == id } }
+
+ fun clicks(layout: SavedInputLayout): Map = if (layout.id == InputLibraries.TRACKPAD)
+ mapOf("legacy:right-pad" to InputAction.MouseButton(272)) else emptyMap()
+
+ fun presets(layouts: List) = layouts.map { layout ->
+ val desktop = layout.id == InputLibraries.TRACKPAD
+ SavedInputBindings(if (desktop) TRACKPAD else DECK, layout.name, false, layout.id,
+ controls = InputProfile.defaults(if (desktop) InputProfile.DESKTOP else InputProfile.GAME).bindings[InputRole.SECONDARY].orEmpty(),
+ elements = actions(layout), clicks = clicks(layout))
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt
new file mode 100644
index 0000000000..b20acf3741
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceLayout.kt
@@ -0,0 +1,95 @@
+package com.droiddeck.launcher.input
+
+import android.content.Context
+import org.json.JSONArray
+import org.json.JSONObject
+
+enum class InputElementKind(val control: InputControl) {
+ BUTTON(InputControl.A), STICK(InputControl.LS), TRACKPAD(InputControl.LEFT_PAD),
+ DPAD(InputControl.LS), TRIGGER(InputControl.LT);
+
+ companion object {
+ fun from(control: InputControl) = when {
+ control.isTrackpad -> TRACKPAD
+ control.dimensions == 2 -> STICK
+ control == InputControl.LT || control == InputControl.RT -> TRIGGER
+ else -> BUTTON
+ }
+ }
+}
+
+enum class InputButtonShape { ROUNDED, PILL, CIRCLE, RECTANGLE }
+
+data class InputSurfaceElement(
+ val control: InputControl, val x: Float, val y: Float, val width: Float, val height: Float,
+ val id: String = "legacy:${control.id}",
+ val kind: InputElementKind = InputElementKind.from(control),
+ val name: String = control.label,
+ val floating: Boolean = true,
+ val hideWhenIdle: Boolean = false,
+ val mouseGestures: Boolean = false,
+ val toggle: Boolean = false,
+ val icon: Int = 0,
+ val image: String = "",
+ val opacity: Float = 1f,
+ val buttonShape: InputButtonShape = InputButtonShape.ROUNDED,
+ val showLabel: Boolean = true,
+) {
+ val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
+
+ fun bounded() = copy(x = x.coerceIn(0f, 0.97f), y = y.coerceIn(0f, 0.97f),
+ width = width.coerceIn(0.03f, 1f - x.coerceIn(0f, 0.97f)), height = height.coerceIn(0.03f, 1f - y.coerceIn(0f, 0.97f)))
+}
+
+object InputSurfaceLayout {
+ private fun prefs(context: Context) = context.getSharedPreferences("input-surfaces", Context.MODE_PRIVATE)
+
+ fun resetAll(context: Context) { prefs(context).edit().clear().apply() }
+
+ fun defaults() = listOf(
+ InputSurfaceElement(InputControl.LEFT_PAD, 0.02f, 0.02f, 0.46f, 0.65f),
+ InputSurfaceElement(InputControl.RIGHT_PAD, 0.52f, 0.02f, 0.46f, 0.65f),
+ InputSurfaceElement(InputControl.A, 0.02f, 0.72f, 0.20f, 0.25f),
+ InputSurfaceElement(InputControl.B, 0.26f, 0.72f, 0.20f, 0.25f),
+ InputSurfaceElement(InputControl.SELECT, 0.52f, 0.72f, 0.20f, 0.25f),
+ InputSurfaceElement(InputControl.START, 0.76f, 0.72f, 0.22f, 0.25f),
+ )
+
+ fun read(context: Context, profile: String, role: InputRole = InputRole.SECONDARY): List =
+ InputLibraries.read(context).layout(profile, role)?.elements.orEmpty()
+
+ internal fun hasLegacy(context: Context, profile: String) = prefs(context).contains(profile)
+
+ internal fun readLegacy(context: Context, profile: String): List {
+ val text = prefs(context).getString(profile, null) ?: return defaults()
+ return runCatching {
+ val doc = JSONObject(text)
+ require(doc.getInt("version") == 1)
+ val elements = doc.getJSONArray("elements")
+ (0 until minOf(elements.length(), 28)).mapNotNull { i ->
+ val item = elements.optJSONObject(i) ?: return@mapNotNull null
+ val control = InputControl.fromId(item.optString("control")) ?: return@mapNotNull null
+ val values = listOf("x", "y", "w", "h").map { item.optDouble(it, Double.NaN).toFloat() }
+ if (values.any { !it.isFinite() }) return@mapNotNull null
+ InputSurfaceElement(control, values[0], values[1], values[2], values[3]).bounded()
+ }.distinctBy { it.control }
+ }.getOrElse { defaults() }
+ }
+
+ fun save(context: Context, profile: String, layout: List) {
+ InputLibraries.update(context) { library ->
+ val saved = library.layout(profile, InputRole.SECONDARY) ?: return@update library
+ library.withLayout(saved.copy(elements = layout.map { it.bounded() }))
+ }
+ }
+
+ internal fun saveLegacy(context: Context, profile: String, layout: List) {
+ val array = JSONArray()
+ for (element in layout.distinctBy { it.control }.take(28)) {
+ val e = element.bounded()
+ array.put(JSONObject().put("control", e.control.id).put("x", e.x.toDouble()).put("y", e.y.toDouble())
+ .put("w", e.width.toDouble()).put("h", e.height.toDouble()))
+ }
+ prefs(context).edit().putString(profile, JSONObject().put("version", 1).put("elements", array).toString()).apply()
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSnap.kt b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSnap.kt
new file mode 100644
index 0000000000..011a478888
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSnap.kt
@@ -0,0 +1,24 @@
+package com.droiddeck.launcher.input
+
+import kotlin.math.abs
+
+internal data class SurfaceSnapResult(val element: InputSurfaceElement, val x: Float? = null, val y: Float? = null)
+
+internal fun snapSurfaceElement(element: InputSurfaceElement, others: List, thresholdX: Float, thresholdY: Float,
+ corner: Int = 0): SurfaceSnapResult {
+ fun axis(start: Float, size: Float, targets: List, threshold: Float, low: Boolean, high: Boolean): Triple {
+ val anchors = when { low -> listOf(0f); high -> listOf(size); else -> listOf(0f, size / 2f, size) }
+ val candidate = anchors.flatMap { anchor -> targets.map { target -> Triple(target - start - anchor, target, anchor) } }
+ .filter { abs(it.first) <= threshold }.minByOrNull { abs(it.first) } ?: return Triple(start, size, null)
+ val offset = candidate.first
+ val nextStart = if (high) start else start + offset
+ val nextSize = when { low -> size - offset; high -> size + offset; else -> size }
+ if (nextStart < 0f || nextSize < .03f || nextStart + nextSize > 1.00001f) return Triple(start, size, null)
+ return Triple(nextStart.coerceAtLeast(0f), nextSize, candidate.second)
+ }
+ val xTargets = listOf(0f, .5f, 1f) + others.flatMap { listOf(it.x, it.x + it.width / 2f, it.x + it.width) }
+ val yTargets = listOf(0f, .5f, 1f) + others.flatMap { listOf(it.y, it.y + it.height / 2f, it.y + it.height) }
+ val x = axis(element.x, element.width, xTargets, thresholdX, corner and 1 != 0, corner and 2 != 0)
+ val y = axis(element.y, element.height, yTargets, thresholdY, corner and 4 != 0, corner and 8 != 0)
+ return SurfaceSnapResult(element.copy(x = x.first, y = y.first, width = x.second, height = y.second).bounded(), x.third, y.third)
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSource.kt b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSource.kt
new file mode 100644
index 0000000000..80c869a641
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputSurfaceSource.kt
@@ -0,0 +1,117 @@
+package com.droiddeck.launcher.input
+
+class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole, val element: InputSurfaceElement) {
+ private val router = pad.inputRouter
+ private val route = router?.channel(role, element.control, element = element)
+ private val deck = DeckControls.source(role, routed = true)
+ private val clickDeck = DeckControls.source(role, routed = true)
+ private val clickOwner = Any()
+ private val clickRoute = if (element.hasClick) router?.channel(role, InputControl.A, element = element, elementClick = true) else null
+ private val gestureWheel = if (element.mouseGestures) router?.channel(role, InputControl.RIGHT_PAD, fixedAction = InputAction.Scroll()) else null
+ private val gestureRight = if (element.mouseGestures) router?.channel(role, InputControl.A, fixedAction = InputAction.MouseButton(273)) else null
+ private val gestureMiddle = if (element.mouseGestures) router?.channel(role, InputControl.A, fixedAction = InputAction.MouseButton(274)) else null
+ val mouseGestures get() = element.mouseGestures && route?.action is InputAction.Pointer
+
+ fun gestureContact(touching: Boolean) { if (!closed) route?.update(0f, 0f, touching) }
+ fun pointerDelta(dx: Float, dy: Float) {
+ if (closed) return
+ val timing = InputTiming.begin()
+ route?.pointerDelta(dx, dy)
+ InputTiming.end(timing)
+ }
+ fun gestureWheel(steps: Int) { if (!closed && route?.acceptsPointerGesture() == true) gestureWheel?.wheelSteps(steps) }
+ fun gestureButton(code: Int, down: Boolean) {
+ if (closed || down && route?.acceptsPointerGesture() != true) return
+ when (code) {
+ 272 -> click(down)
+ 273 -> gestureRight?.update(if (down) 1f else 0f)
+ 274 -> gestureMiddle?.update(if (down) 1f else 0f)
+ }
+ }
+
+ private var nativePad = false
+ private var nativeDeck = false
+ private var clickPad = false
+ private var clickDeckActive = false
+ private var closed = false
+ private var fingerDown = false
+ private var latchBlocked = false
+ var latched = false
+ private set
+ var onStateChanged: () -> Unit = {}
+ private fun resetLatch() { latched = false; latchBlocked = fingerDown; onStateChanged() }
+ private val snapshot: () -> Unit = { releaseNative(); resetLatch(); if (element.toggle) route?.release() }
+
+ init { router?.beforeProfileChange(snapshot) }
+
+ fun update(value: Float, y: Float = 0f, touching: Boolean = false) {
+ if (closed) return
+ val timing = InputTiming.begin()
+ val x = if (element.toggle && route?.action !is InputAction.Command && route?.action !is InputAction.Disabled) {
+ val down = value > .5f
+ if (!down) latchBlocked = false
+ if (down && !fingerDown && !latchBlocked) latched = !latched
+ fingerDown = down
+ if (latched) 1f else 0f
+ } else value
+ val target = if (router == null) element.control else route?.update(x, y, touching)
+ val toPad = target?.isPad == true
+ val toDeck = target != null && !target.isPad
+ if (toPad || nativePad) writePad(this, target) { state ->
+ state.clear()
+ if (toPad) {
+ if (element.kind == InputElementKind.DPAD) {
+ state.up = y < -.5f; state.down = y > .5f; state.left = x < -.5f; state.right = x > .5f
+ } else state.add(target, x, y)
+ }
+ }
+ if (toDeck || nativeDeck) deck.native(if (toDeck) target else null, x, y, touching)
+ nativePad = toPad; nativeDeck = toDeck
+ if (element.toggle) onStateChanged()
+ InputTiming.end(timing)
+ }
+
+ fun click(down: Boolean) {
+ if (closed) return
+ val timing = InputTiming.begin()
+ val target = if (router == null) when (element.control) { InputControl.LS -> InputControl.L3; InputControl.RS -> InputControl.R3; else -> null } else clickRoute?.update(if (down) 1f else 0f)
+ val toPad = target?.isPad == true
+ val toDeck = target != null && !target.isPad
+ if (toPad || clickPad) writePad(clickOwner, target) { state ->
+ state.clear()
+ if (toPad && down) state.add(target, 1f)
+ }
+ if (toDeck || clickDeckActive) clickDeck.native(if (toDeck) target else null, if (down) 1f else 0f, 0f, false)
+ clickPad = toPad; clickDeckActive = toDeck
+ InputTiming.end(timing)
+ }
+
+ private fun writePad(owner: Any, target: InputControl?, mutation: (PadState) -> Unit) {
+ if (router != null) pad.applyRoutedTouch(owner, role, mutation)
+ else pad.applyTouch(owner, role, when (target) { InputControl.LS -> PadBridge.LEFT_STICK; InputControl.RS -> PadBridge.RIGHT_STICK; else -> 0 }, mutation)
+ }
+
+ private fun releaseNative() {
+ if (nativePad) pad.releaseTouch(this)
+ if (nativeDeck) deck.release()
+ if (clickPad) pad.releaseTouch(clickOwner)
+ if (clickDeckActive) clickDeck.release()
+ clickPad = false; clickDeckActive = false
+ nativePad = false; nativeDeck = false
+ }
+
+ fun close() {
+ if (closed) return
+ closed = true
+ router?.removeSnapshot(snapshot)
+ releaseNative(); resetLatch()
+ route?.close(); clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close()
+ }
+
+ fun release() {
+ if (closed) return
+ releaseNative(); resetLatch()
+ route?.release(); clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release()
+ }
+
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputTiming.kt b/app/src/main/java/com/droiddeck/launcher/input/InputTiming.kt
new file mode 100644
index 0000000000..0d2589c42f
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/InputTiming.kt
@@ -0,0 +1,33 @@
+package com.droiddeck.launcher.input
+
+import java.util.Locale
+
+object InputTiming {
+ @JvmField @Volatile var enabled = false
+ private val samples = LongArray(4096)
+ private var count = 0L
+ private var next = 0
+
+ @JvmStatic fun begin(): Long = if (enabled) System.nanoTime() else 0L
+
+ @JvmStatic fun end(start: Long) {
+ if (start == 0L) return
+ val elapsed = System.nanoTime() - start
+ synchronized(this) {
+ samples[next] = elapsed
+ next = (next + 1) % samples.size
+ count++
+ }
+ }
+
+ @Synchronized fun reset() { count = 0; next = 0; samples.fill(0) }
+
+ @Synchronized fun report(): String {
+ val size = minOf(count, samples.size.toLong()).toInt()
+ if (size == 0) return "No input samples"
+ val values = samples.copyOf(size).sortedArray()
+ fun percentile(p: Double) = values[((size - 1) * p).toInt()] / 1000.0
+ return String.format(Locale.ROOT, "Dispatch to publication (µs): p50 %.1f, p95 %.1f, p99 %.1f; %d samples, last %d retained",
+ percentile(.5), percentile(.95), percentile(.99), count, size)
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt
new file mode 100644
index 0000000000..4525fa9d9c
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt
@@ -0,0 +1,207 @@
+package com.droiddeck.launcher.input
+
+import android.content.Context
+import android.graphics.Rect
+import kotlin.math.*
+
+internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int) {
+ private val resources get() = context.resources
+ private val settings = ControllerPrefs.read(context)
+ private val safe = Rect()
+ private var fit = 1f
+ private class Control(val id: String, val group: String, val stick: Int, val radiusDp: Float, val offsetXDp: Float, val offsetYDp: Float) {
+ var radius = 0f
+ var cx = 0f
+ var cy = 0f
+ val halfW get() = if (id in shoulderIds) radius * SHOULDER_WIDTH else radius
+ val halfH get() = if (id in shoulderIds) radius * SHOULDER_HEIGHT else radius
+ }
+ private val controls = listOf(
+ Control("up", "dpad", -1, 26f, 0f, -52f),
+ Control("right", "dpad", -1, 26f, 52f, 0f),
+ Control("down", "dpad", -1, 26f, 0f, 52f),
+ Control("left", "dpad", -1, 26f, -52f, 0f),
+ Control("ls", "ls", 0, 48f, 0f, 0f),
+ Control("rs", "rs", 1, 48f, 0f, 0f),
+ Control("a", "face", -1, 30f, 0f, 50f),
+ Control("b", "face", -1, 30f, 50f, 0f),
+ Control("x", "face", -1, 30f, -50f, 0f),
+ Control("y", "face", -1, 30f, 0f, -50f),
+ Control("lb", "lb", -1, 24f, 0f, 0f),
+ Control("rb", "rb", -1, 24f, 0f, 0f),
+ Control("lt", "lt", -1, 24f, 0f, 0f),
+ Control("rt", "rt", -1, 24f, 0f, 0f),
+ Control("select", "select", -1, 20f, 0f, 0f),
+ Control("start", "start", -1, 20f, 0f, 0f),
+ Control("guide", "guide", -1, 22f, 0f, 0f),
+ Control("qam", "qam", -1, 22f, 0f, 0f),
+ )
+
+ private val groups = controls.map { it.group }.distinct()
+
+ private fun dp(value: Float) = value * resources.displayMetrics.density
+
+ private fun scaled(value: Float) = dp(value) * settings.size / 100f * fit
+
+ private fun fitScale(): Float {
+ val metrics = resources.displayMetrics
+ val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
+ val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
+ val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
+ return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
+ }
+
+ private fun pxPerMm(dpi: Float): Float {
+ val nominal = resources.displayMetrics.densityDpi.toFloat()
+ return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
+ }
+
+ private fun placeAuto(w: Float, h: Float) {
+ val metrics = resources.displayMetrics
+ val mmX = pxPerMm(metrics.xdpi)
+ val mmY = pxPerMm(metrics.ydpi)
+ val usableW = w - safe.left - safe.right
+ val usableH = h - safe.top - safe.bottom
+ val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
+ val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
+ val gap = dp(12f)
+ val floor = BOTTOM_MARGIN_MM * mmY
+ val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
+ val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
+ put("ls", safe.left + inboard, restY)
+ put("face", w - safe.right - inboard, restY)
+ besideBelow("dpad", "ls", 1f, gap, floor)
+ besideBelow("rs", "face", -1f, gap, floor)
+ val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
+ val shoulderY = if (phone) safe.top + floor + halfH("lb")
+ else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
+ shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
+ shoulders("face", "rb", "rt", -1f, gap, shoulderY)
+ val bottom = h - safe.bottom - floor - extent("guide")
+ val spread = extent("guide") + gap / 2f
+ put("guide", w / 2f - spread, bottom)
+ put("qam", w / 2f + spread, bottom)
+ val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
+ put("select", inner, restY)
+ put("start", w - inner, restY)
+ if (phone) {
+ val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
+ put("select", top, shoulderY)
+ put("start", w - top, shoulderY)
+ }
+ if (crowded("select", gap) || crowded("start", gap)) {
+ above("select", "dpad", gap)
+ val (sx, sy) = centre("select")
+ put("start", w - sx, sy)
+ if (crowded("start", gap)) above("start", "rs", gap)
+ }
+ if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
+ val row = centre("select").second
+ put("guide", w / 2f - spread, row)
+ put("qam", w / 2f + spread, row)
+ if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
+ val top = safe.top + dp(8f) + extent("guide")
+ put("guide", w / 2f - spread, top)
+ put("qam", w / 2f + spread, top)
+ }
+ }
+ }
+
+ private fun drop(group: String, anchor: String, gap: Float): Float =
+ (extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
+
+ private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
+ val (ax, ay) = centre(anchor)
+ val reach = extent(anchor) + extent(group) + gap
+ val floor = height - safe.bottom - margin - extent(group)
+ val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
+ val dx = sqrt(max(0f, reach * reach - dy * dy))
+ put(group, ax + inward * dx, ay + dy)
+ }
+
+ private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
+ val (ax, _) = centre(anchor)
+ val spread = extent(bumper) + gap / 2f
+ put(bumper, ax + inward * spread, y)
+ put(trigger, ax - inward * spread, y)
+ }
+
+ private fun above(group: String, anchor: String, gap: Float) {
+ val (ax, ay) = centre(anchor)
+ put(group, ax, ay - extent(anchor) - gap - extent(group))
+ }
+
+ private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
+ val (x, y) = centre(group)
+ return groups.any { other ->
+ if (other == group || other == except) return@any false
+ val (ox, oy) = centre(other)
+ val dx = x - ox
+ val dy = y - oy
+ sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
+ }
+ }
+
+ private fun members(group: String) = controls.filter { it.group == group }
+
+ private fun centre(group: String): Pair {
+ val first = members(group).first()
+ return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
+ }
+
+ private fun extent(group: String): Float = members(group).maxOf { control ->
+ sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
+ }
+
+ private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
+
+ private fun put(group: String, x: Float, y: Float) {
+ for (control in members(group)) {
+ control.cx = x + scaled(control.offsetXDp)
+ control.cy = y + scaled(control.offsetYDp)
+ }
+ }
+
+ private fun clamp(group: String) {
+ val list = members(group)
+ val margin = dp(4f)
+ val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
+ val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
+ val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
+ val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
+ val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
+ val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
+ if (dx == 0f && dy == 0f) return
+ for (control in list) { control.cx += dx; control.cy += dy }
+ }
+
+
+ fun elements(): List {
+ fit = fitScale()
+ controls.forEach { it.radius = scaled(it.radiusDp) }
+ placeAuto(width.toFloat(), height.toFloat())
+ for ((group, position) in ControllerPrefs.layout(context, width, height)) {
+ if (group in groups && position.first.isFinite() && position.second.isFinite()) put(group, position.first * width, position.second * height)
+ }
+ groups.forEach(::clamp)
+ val result = controls.filter {
+ settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton)
+ }.map { c ->
+ InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
+ 2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks).bounded()
+ }.toMutableList()
+ if (settings.keyboardButton) result += InputSurfaceElement(InputControl.A, .02f, .9f, .12f, .08f,
+ "builtin:keyboard", name = "Keyboard")
+ return result
+ }
+ private companion object {
+ const val MIN_FACE_MM = 9.5f
+ const val FULL_SIZE_HEIGHT_MM = 85f
+ const val BOTTOM_MARGIN_MM = 5f
+ const val DROP_DEGREES = 35.0
+ const val PHONE_MAX_HEIGHT_MM = 90f
+ const val SHOULDER_WIDTH = 1.45f
+ const val SHOULDER_HEIGHT = 0.8f
+ val shoulderIds = setOf("lb", "rb", "lt", "rt")
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/LegacyScreenKeyMigration.kt b/app/src/main/java/com/droiddeck/launcher/input/LegacyScreenKeyMigration.kt
new file mode 100644
index 0000000000..fed7b35fe9
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/LegacyScreenKeyMigration.kt
@@ -0,0 +1,82 @@
+package com.droiddeck.launcher.input
+
+import android.content.Context
+import android.hardware.display.DisplayManager
+import android.util.DisplayMetrics
+import android.view.Display
+import org.json.JSONObject
+
+internal object LegacyScreenKeyMigration {
+ const val BACKUP = "legacy-screen-keys-backup"
+
+ fun snapshot(context: Context): String? {
+ val values = ControllerPrefs.prefs(context).all.filterKeys { it == "screenKeys" || it == "screenKeysShown" || it.startsWith("screenLayout.") }
+ return values.takeIf { it.isNotEmpty() }?.let { JSONObject(it).toString() }
+ }
+
+ fun clean(context: Context) {
+ val prefs = ControllerPrefs.prefs(context)
+ prefs.edit().apply { prefs.all.keys.filter { it == "screenKeys" || it == "screenKeysShown" || it.startsWith("screenLayout.") }.forEach(::remove) }.apply()
+ }
+
+ @Suppress("DEPRECATION")
+ fun migrate(context: Context, library: InputLibrary, raw: String): InputLibrary {
+ val old = JSONObject(raw)
+ val display = context.getSystemService(DisplayManager::class.java)?.getDisplay(Display.DEFAULT_DISPLAY)
+ val metrics = DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) }
+ val settings = ControllerPrefs.read(context)
+ val style = InputSurfaceStyle(settings.tint, settings.opacity)
+ val sets = buildList {
+ old.optString("screenKeys").takeIf { it.isNotBlank() }?.let { add("Screen keys (imported)" to it) }
+ old.keys().asSequence().filter { it.startsWith("screenLayout.") }.sorted().forEach { key ->
+ add((key.removePrefix("screenLayout.").ifBlank { "Screen keys" } + " (imported)").take(80) to old.getString(key))
+ }
+ }
+ var result = library
+ for ((index, set) in sets.withIndex()) {
+ val id = "migrated.screenkeys.$index"
+ if (result.profiles.any { it.id == id }) continue
+ val converted = convert(context, set.second, metrics.widthPixels, metrics.heightPixels, metrics.density)
+ if (converted.isEmpty()) continue
+ val layout = SavedInputLayout("$id.layout", set.first, converted.map { it.first }, style = style, screen = InputLayoutScreen.MAIN)
+ val bindings = SavedInputBindings("$id.bindings", set.first, false, layout.id, elements = converted.associate { it.first.id to it.second })
+ val base = library.profile(library.steam)
+ val profile = SavedInputProfile(id, set.first, base.base, base.parts + (InputRole.PRIMARY to InputPart(bindings.id, layout.id)))
+ result = result.withLayout(layout).withPreset(bindings).withProfile(profile)
+ }
+ return result.validate()
+ }
+
+ internal fun convert(context: Context, raw: String, width: Int, height: Int, density: Float): List> =
+ raw.split(';').filter { it.isNotBlank() }.mapIndexed { index, entry ->
+ val parts = entry.split(':')
+ require(parts.size >= 2) { "Invalid legacy screen key" }
+ val codes = parts[0].split('+').map { it.toInt() }
+ require(codes.all { it in 0..255 })
+ val position = parts[1].split(',').map { it.toFloat() }
+ require(position.size == 3 && position.all { it.isFinite() })
+ fun text(at: Int) = parts.getOrNull(at).orEmpty().replace("%2C", ",").replace("%3A", ":").replace("%3B", ";").replace("%25", "%")
+ val shape = parts.getOrNull(6)?.toIntOrNull() ?: 0
+ val kind = when (shape) { 5 -> InputElementKind.DPAD; 6 -> InputElementKind.STICK; 4 -> InputElementKind.TRIGGER; else -> InputElementKind.BUTTON }
+ val label = text(3).ifEmpty { text(2) }.ifEmpty { codes.filter { it != 0 }.joinToString("+") { pcKeyLabel(context, it) } }.ifBlank { "Button" }.take(80)
+ val image = text(4)
+ val icon = codes.singleOrNull()?.takeIf { InputButtonIcons.has(it) && text(3).isEmpty() && text(2).isEmpty() } ?: 0
+ val heightPx = position[2].coerceIn(24f, 140f) * density
+ val ratio = when { shape == 2 -> 1f; shape == 4 -> 1.7f; shape == 5 || shape == 6 || image.isNotEmpty() || icon != 0 -> 1.15f; else -> (.55f * label.length + 1.05f).coerceIn(1.7f, 4.6f) }
+ val w = (heightPx * ratio / width.coerceAtLeast(1)).coerceIn(.03f, 1f)
+ val h = (heightPx / height.coerceAtLeast(1)).coerceIn(.03f, 1f)
+ val element = InputSurfaceElement(kind.control, (position[0] - w / 2).coerceIn(0f, 1f - w), (position[1] - h / 2).coerceIn(0f, 1f - h), w, h,
+ id = "imported:$index", kind = kind, name = label, floating = false,
+ toggle = parts.getOrNull(7) == "1" && kind != InputElementKind.DPAD && kind != InputElementKind.STICK,
+ icon = icon, image = image, opacity = (parts.getOrNull(5)?.toFloatOrNull() ?: 1f).coerceIn(.2f, 1f),
+ buttonShape = when (shape) { 0 -> InputButtonShape.PILL; 2 -> InputButtonShape.CIRCLE; 3 -> InputButtonShape.RECTANGLE; else -> InputButtonShape.ROUNDED },
+ showLabel = parts.getOrNull(8) != "0").bounded()
+ val action = when (kind) {
+ InputElementKind.DPAD -> InputAction.Directions(codes.getOrElse(0) { 0 }, codes.getOrElse(1) { 0 }, codes.getOrElse(2) { 0 }, codes.getOrElse(3) { 0 })
+ InputElementKind.STICK -> InputAction.Directions(codes.getOrElse(0) { 0 }, codes.getOrElse(2) { 0 }, codes.getOrElse(4) { 0 }, codes.getOrElse(6) { 0 }, listOf(1, 3, 5, 7).map { codes.getOrElse(it) { 0 } })
+ else -> codes.filter { it != 0 }.distinct().let { if (it.isEmpty()) InputAction.Disabled else InputAction.Keys(it) }
+ }
+ require(action.validFor(element))
+ element to action
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt
index dc26a75f55..053bc695ed 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt
@@ -1,833 +1,44 @@
package com.droiddeck.launcher.input
-import android.annotation.SuppressLint
import android.content.Context
-import android.graphics.Canvas
-import android.graphics.Color
-import android.graphics.Paint
-import android.graphics.Path
-import android.graphics.Rect
-import android.graphics.RectF
-import android.os.Build
-import android.view.HapticFeedbackConstants
import android.view.MotionEvent
-import android.view.View
-import android.view.WindowInsets
-import com.droiddeck.launcher.session.SessionPrefs
-import kotlin.math.abs
-import kotlin.math.hypot
-import kotlin.math.max
-import kotlin.math.min
-import kotlin.math.sin
-import kotlin.math.sqrt
+import android.widget.FrameLayout
+import com.droiddeck.launcher.ui.InputSurfaceView
-@SuppressLint("ViewConstructor")
-class OnScreenControls(
- context: Context,
- private val pad: PadBridge?,
- private val editing: Boolean = false,
- private val onKeyboard: (() -> Unit)? = null,
-) : View(context) {
+class OnScreenControls(context: Context, pad: PadBridge?) : FrameLayout(context) {
+ private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY)
+ private var layout: SavedInputLayout? = null
+ var isButtonsOnly = false
+ private set
+ var onTouchMiss: ((MotionEvent) -> Unit)?
+ get() = surface.onTouchMiss
+ set(value) { surface.onTouchMiss = value }
- private class Control(
- val id: String,
- val group: String,
- val stick: Int,
- val radiusDp: Float,
- val offsetXDp: Float,
- val offsetYDp: Float,
- ) {
- var target = id
- var radius = 0f
- var cx = 0f
- var cy = 0f
- var pressedBy = -1
- var kx = 0f
- var ky = 0f
- var ax = 0f
- var ay = 0f
- var dirty = false
- var clicked = false
- var lastUp = 0L
- var downAt = 0L
- var downX = 0f
- var downY = 0f
- var travel = 0f
- val wide = id in shoulderIds
- val halfW get() = if (wide) radius * SHOULDER_WIDTH else radius
- val halfH get() = if (wide) radius * SHOULDER_HEIGHT else radius
+ init { addView(surface, LayoutParams(-1, -1)) }
- fun contains(x: Float, y: Float, r: Float, padding: Float = 0f): Boolean {
- val dx = x - cx
- val dy = y - cy
- if (wide) return abs(dx) <= halfW + r * 0.25f + padding && abs(dy) <= halfH + r * 0.25f + padding
- val hit = r * 1.25f + padding
- return dx * dx + dy * dy <= hit * hit
- }
-
- fun drag(x: Float, y: Float): Boolean {
- travel = max(travel, hypot(x - downX, y - downY))
- var dx = x - ax
- var dy = y - ay
- val d = sqrt(dx * dx + dy * dy)
- val atLimit = d > radius
- if (atLimit) { dx = dx / d * radius; dy = dy / d * radius }
- if (!atLimit && abs(dx - kx) < MIN_STICK_MOVE_PX && abs(dy - ky) < MIN_STICK_MOVE_PX) return false
- kx = dx; ky = dy; dirty = true
- return true
- }
- }
-
- private val stickRedraw = ThrottledRedraw(this, STICK_REDRAW_MS)
- private val tapSlop = android.view.ViewConfiguration.get(context).scaledTouchSlop.toFloat()
-
- private fun stickTap(control: Control, event: MotionEvent): Boolean {
- val i = event.actionIndex
- val travel = max(control.travel, hypot(event.getX(i) - control.downX, event.getY(i) - control.downY))
- return stickTap(control.downAt, event.eventTime, travel, tapSlop, control.clicked,
- event.actionMasked == MotionEvent.ACTION_CANCEL || (event.flags and MotionEvent.FLAG_CANCELED) != 0)
- }
-
- private val controls = listOf(
- Control("up", "dpad", -1, 26f, 0f, -52f),
- Control("right", "dpad", -1, 26f, 52f, 0f),
- Control("down", "dpad", -1, 26f, 0f, 52f),
- Control("left", "dpad", -1, 26f, -52f, 0f),
- Control("ls", "ls", 0, 48f, 0f, 0f),
- Control("rs", "rs", 1, 48f, 0f, 0f),
- Control("a", "face", -1, 30f, 0f, 50f),
- Control("b", "face", -1, 30f, 50f, 0f),
- Control("x", "face", -1, 30f, -50f, 0f),
- Control("y", "face", -1, 30f, 0f, -50f),
- Control("lb", "lb", -1, 24f, 0f, 0f),
- Control("rb", "rb", -1, 24f, 0f, 0f),
- Control("lt", "lt", -1, 24f, 0f, 0f),
- Control("rt", "rt", -1, 24f, 0f, 0f),
- Control("select", "select", -1, 20f, 0f, 0f),
- Control("start", "start", -1, 20f, 0f, 0f),
- Control("guide", "guide", -1, 22f, 0f, 0f),
- Control("qam", "qam", -1, 22f, 0f, 0f),
- )
-
- private val groups = controls.map { it.group }.distinct()
-
- private var buttonsOnly = false
- val isButtonsOnly: Boolean get() = buttonsOnly
- private var quickHidden = false
- private var quickPressedBy = -1
- private var keyboardPressedBy = -1
- private var forwardedPointerBits = 0
- var onTouchMiss: ((MotionEvent) -> Unit)? = null
- private var settings = ControllerPrefs.read(context)
- private var snap = settings.snap
- private var safe = Rect()
- private var selected: String? = null
- private var snapX: Float? = null
- private var snapY: Float? = null
- private var grabX = 0f
- private var grabY = 0f
- private var ignoreSaved = false
- private var fit = 1f
-
- private var idleFill = 0
- private var heldFill = 0
- private var idleStroke = 0
- private var heldStroke = 0
- private var idleText = 0
- private var stickFill = 0
- private var knobFill = 0
-
- private val fill = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
- private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
- private val arrow = Path()
- private val box = RectF()
- private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
- textAlign = Paint.Align.CENTER
- typeface = android.graphics.Typeface.DEFAULT_BOLD
- }
-
- init {
- applySettings()
- }
-
- private fun dp(value: Float) = value * resources.displayMetrics.density
-
- private fun scaled(value: Float) = dp(value) * settings.size / 100f * fit
-
- private fun fitScale(): Float {
- val metrics = resources.displayMetrics
- val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
- val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
- val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
- return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
- }
-
- fun reload() {
+ fun updateLayout(value: SavedInputLayout?) {
+ if (layout == value) return
releaseAll()
- settings = ControllerPrefs.read(context)
- setSnap(settings.snap)
- applySettings()
- relayout()
- }
-
- private fun clearSnapGuides() {
- if (snapX == null && snapY == null) return
- snapX = null
- snapY = null
- invalidate()
- }
-
- private fun applySettings() {
- for (control in controls) control.target = settings.mapping[control.id] ?: control.id
- val tint = settings.tint
- val alpha = settings.opacity / 100f
- fun shade(a: Int, f: Float) = Color.argb((a * alpha).toInt(), (Color.red(tint) * f).toInt(), (Color.green(tint) * f).toInt(), (Color.blue(tint) * f).toInt())
- fun light(a: Int, f: Float) = Color.argb(
- (a * alpha).toInt(),
- (Color.red(tint) + (255 - Color.red(tint)) * f).toInt(),
- (Color.green(tint) + (255 - Color.green(tint)) * f).toInt(),
- (Color.blue(tint) + (255 - Color.blue(tint)) * f).toInt(),
- )
- idleFill = shade(80, 0.12f)
- heldFill = shade(160, 1f)
- idleStroke = light(150, 0.25f)
- heldStroke = light(230, 0.7f)
- idleText = light(210, 0.75f)
- stickFill = shade(60, 0.12f)
- knobFill = shade(120, 0.35f)
- stroke.strokeWidth = dp(1.5f)
+ layout = value
+ render()
}
fun setButtonsOnly(enabled: Boolean) {
- if (buttonsOnly == enabled) return
+ if (isButtonsOnly == enabled) return
releaseAll()
- buttonsOnly = enabled
- quickHidden = false
- relayout()
+ isButtonsOnly = enabled
+ render()
}
- fun setQuickHidden(hidden: Boolean) {
- if (buttonsOnly || editing || quickHidden == hidden) return
- if (hidden) releaseAll()
- quickHidden = hidden
- invalidate()
+ private fun render() {
+ val elements = layout?.elements.orEmpty()
+ surface.updateCustomLayout(if (isButtonsOnly) elements.filter { it.control == InputControl.GUIDE || it.control == InputControl.QAM || it.id == "builtin:keyboard" } else elements)
+ surface.updateStyle(layout?.style ?: InputSurfaceStyle())
}
- fun setSnap(on: Boolean) {
- snap = on
- if (!on) clearSnapGuides()
- }
+ fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y)
+ fun releaseAll() = surface.releaseInputs()
+ fun reload() { releaseAll(); render() }
- override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
- super.onSizeChanged(w, h, oldw, oldh)
- relayout()
- }
-
- override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
- val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
- val fresh = Rect(cutout?.safeInsetLeft ?: 0, cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
- if (fresh != safe) { safe = fresh; relayout() }
- return super.onApplyWindowInsets(insets)
- }
-
- override fun onDetachedFromWindow() {
- stickRedraw.cancel()
- releaseAll()
- super.onDetachedFromWindow()
- }
-
- private fun relayout() {
- if (width <= 0 || height <= 0) return
- fit = if (buttonsOnly && !editing) 1f else fitScale()
- for (control in controls) control.radius = if (buttonsOnly && !editing && (control.id == "guide" || control.id == "qam")) dp(30f) else scaled(control.radiusDp)
- if (buttonsOnly && !editing) {
- val inset = dp(44f)
- put("guide", safe.left + inset, height - safe.bottom - inset)
- put("qam", width - safe.right - inset, height - safe.bottom - inset)
- } else {
- placeAuto(width.toFloat(), height.toFloat())
- if (!ignoreSaved) for ((group, pos) in ControllerPrefs.layout(context, width, height)) {
- if (group in groups) put(group, pos.first * width, pos.second * height)
- }
- }
- groups.forEach { clamp(it) }
- invalidate()
- }
-
- private fun pxPerMm(dpi: Float): Float {
- val nominal = resources.displayMetrics.densityDpi.toFloat()
- return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
- }
-
- private fun placeAuto(w: Float, h: Float) {
- val metrics = resources.displayMetrics
- val mmX = pxPerMm(metrics.xdpi)
- val mmY = pxPerMm(metrics.ydpi)
- val usableW = w - safe.left - safe.right
- val usableH = h - safe.top - safe.bottom
- val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
- val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
- val gap = dp(12f)
- val floor = BOTTOM_MARGIN_MM * mmY
- val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
- val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
- put("ls", safe.left + inboard, restY)
- put("face", w - safe.right - inboard, restY)
- besideBelow("dpad", "ls", 1f, gap, floor)
- besideBelow("rs", "face", -1f, gap, floor)
- val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
- val shoulderY = if (phone) safe.top + floor + halfH("lb")
- else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
- shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
- shoulders("face", "rb", "rt", -1f, gap, shoulderY)
- val bottom = h - safe.bottom - floor - extent("guide")
- val spread = extent("guide") + gap / 2f
- put("guide", w / 2f - spread, bottom)
- put("qam", w / 2f + spread, bottom)
- val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
- put("select", inner, restY)
- put("start", w - inner, restY)
- if (phone) {
- val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
- put("select", top, shoulderY)
- put("start", w - top, shoulderY)
- }
- if (crowded("select", gap) || crowded("start", gap)) {
- above("select", "dpad", gap)
- val (sx, sy) = centre("select")
- put("start", w - sx, sy)
- if (crowded("start", gap)) above("start", "rs", gap)
- }
- if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
- val row = centre("select").second
- put("guide", w / 2f - spread, row)
- put("qam", w / 2f + spread, row)
- if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
- val top = safe.top + dp(8f) + extent("guide")
- put("guide", w / 2f - spread, top)
- put("qam", w / 2f + spread, top)
- }
- }
- }
-
- private fun drop(group: String, anchor: String, gap: Float): Float =
- (extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
-
- private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
- val (ax, ay) = centre(anchor)
- val reach = extent(anchor) + extent(group) + gap
- val floor = height - safe.bottom - margin - extent(group)
- val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
- val dx = sqrt(max(0f, reach * reach - dy * dy))
- put(group, ax + inward * dx, ay + dy)
- }
-
- private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
- val (ax, _) = centre(anchor)
- val spread = extent(bumper) + gap / 2f
- put(bumper, ax + inward * spread, y)
- put(trigger, ax - inward * spread, y)
- }
-
- private fun above(group: String, anchor: String, gap: Float) {
- val (ax, ay) = centre(anchor)
- put(group, ax, ay - extent(anchor) - gap - extent(group))
- }
-
- private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
- val (x, y) = centre(group)
- return groups.any { other ->
- if (other == group || other == except) return@any false
- val (ox, oy) = centre(other)
- val dx = x - ox
- val dy = y - oy
- sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
- }
- }
-
- private fun members(group: String) = controls.filter { it.group == group }
-
- private fun centre(group: String): Pair {
- val first = members(group).first()
- return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
- }
-
- private fun extent(group: String): Float = members(group).maxOf { control ->
- sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
- }
-
- private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
-
- private fun put(group: String, x: Float, y: Float) {
- for (control in members(group)) {
- control.cx = x + scaled(control.offsetXDp)
- control.cy = y + scaled(control.offsetYDp)
- }
- }
-
- private fun clamp(group: String) {
- val list = members(group)
- val margin = dp(4f)
- val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
- val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
- val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
- val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
- val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
- val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
- if (dx == 0f && dy == 0f) return
- for (control in list) { control.cx += dx; control.cy += dy }
- }
-
- fun saveLayout() {
- if (width <= 0 || height <= 0) return
- if (ignoreSaved) { ControllerPrefs.resetLayout(context, width, height); return }
- ControllerPrefs.setLayout(context, width, height, groups.associateWith { group ->
- val (x, y) = centre(group)
- x / width to y / height
- })
- }
-
- fun resetLayout() {
- ControllerPrefs.resetLayout(context, width, height)
- ignoreSaved = true
- selected = null
- relayout()
- }
-
- private fun label(control: Control): String = when (control.target) {
- "ls" -> "L"
- "rs" -> "R"
- "select" -> "⧉"
- "start" -> "☰"
- "guide" -> if (buttonsOnly && !editing) "Steam" else "◉"
- "qam" -> "⋯"
- else -> control.target.uppercase()
- }
-
- override fun onDraw(canvas: Canvas) {
- if (!quickHidden) for (control in controls) {
- if (!isVisible(control)) continue
- if (control.stick >= 0 && settings.adaptiveSticks && !editing && control.pressedBy == -1) continue
- val held = control.pressedBy != -1
- val radius = control.radius
- if (control.stick >= 0) {
- val bx = if (held) control.ax else control.cx
- val by = if (held) control.ay else control.cy
- fill.color = if (held) heldFill else stickFill
- canvas.drawCircle(bx, by, radius, fill)
- stroke.color = if (held) heldStroke else idleStroke
- canvas.drawCircle(bx, by, radius, stroke)
- val knob = radius * 0.46f
- fill.color = if (held || control.clicked) heldFill else knobFill
- canvas.drawCircle(bx + control.kx, by + control.ky, knob, fill)
- stroke.color = if (held) heldStroke else idleStroke
- canvas.drawCircle(bx + control.kx, by + control.ky, knob, stroke)
- text.color = if (held) Color.WHITE else idleText
- text.textSize = knob * 0.8f
- canvas.drawText(label(control), bx + control.kx, by + control.ky + text.textSize * 0.35f, text)
- } else if (control.wide) {
- box.set(control.cx - control.halfW, control.cy - control.halfH, control.cx + control.halfW, control.cy + control.halfH)
- val corner = control.halfH * 0.55f
- fill.color = if (held) heldFill else idleFill
- canvas.drawRoundRect(box, corner, corner, fill)
- stroke.color = if (held) heldStroke else idleStroke
- canvas.drawRoundRect(box, corner, corner, stroke)
- text.color = if (held) Color.WHITE else idleText
- text.textSize = control.halfH * 0.8f
- canvas.drawText(label(control), control.cx, control.cy + text.textSize * 0.35f, text)
- } else {
- fill.color = if (held) heldFill else idleFill
- canvas.drawCircle(control.cx, control.cy, radius, fill)
- stroke.color = if (held) heldStroke else idleStroke
- canvas.drawCircle(control.cx, control.cy, radius, stroke)
- text.color = if (held) Color.WHITE else idleText
- val direction = directions.indexOf(control.target)
- if (direction >= 0) {
- drawArrow(canvas, control.cx, control.cy, radius * 0.34f, direction)
- continue
- }
- val name = label(control)
- text.textSize = if (name.length > 2) dp(11f) else radius * if (name.length == 2) 0.62f else 0.85f
- canvas.drawText(name, control.cx, control.cy + text.textSize * 0.35f, text)
- }
- }
- if (editing) {
- stroke.color = heldStroke
- snapX?.let { canvas.drawLine(it, safe.top.toFloat(), it, (height - safe.bottom).toFloat(), stroke) }
- snapY?.let { canvas.drawLine(safe.left.toFloat(), it, (width - safe.right).toFloat(), it, stroke) }
- selected?.let { group ->
- val (x, y) = centre(group)
- val single = members(group).singleOrNull()
- if (single?.wide == true) {
- val pad = dp(6f)
- box.set(x - single.halfW - pad, y - single.halfH - pad, x + single.halfW + pad, y + single.halfH + pad)
- canvas.drawRoundRect(box, single.halfH, single.halfH, stroke)
- } else canvas.drawCircle(x, y, extent(group) + dp(6f), stroke)
- }
- } else if (!buttonsOnly) {
- val (x, y) = quickCenter()
- val radius = dp(18f)
- fill.color = Color.argb(190, Color.red(idleFill), Color.green(idleFill), Color.blue(idleFill))
- canvas.drawCircle(x, y, radius, fill)
- stroke.color = idleStroke
- canvas.drawCircle(x, y, radius, stroke)
- text.color = idleText
- text.textSize = dp(22f)
- canvas.drawText(if (quickHidden) "+" else "−", x, y + text.textSize * 0.35f, text)
- }
- if (!editing && settings.keyboardButton && onKeyboard != null) {
- val (x, y) = keyboardCenter()
- fill.color = Color.argb(190, Color.red(idleFill), Color.green(idleFill), Color.blue(idleFill))
- canvas.drawCircle(x, y, dp(18f), fill)
- stroke.color = if (keyboardPressedBy == -1) idleStroke else heldStroke
- canvas.drawCircle(x, y, dp(18f), stroke)
- box.set(x - dp(10f), y - dp(7f), x + dp(10f), y + dp(7f))
- canvas.drawRoundRect(box, dp(2f), dp(2f), stroke)
- for (row in 0..1) for (col in 0..2) {
- val kx = x + dp(-6f + col * 5f)
- val ky = y + dp(-3f + row * 4f)
- canvas.drawLine(kx, ky, kx + dp(2f), ky, stroke)
- }
- canvas.drawLine(x - dp(5f), y + dp(4f), x + dp(5f), y + dp(4f), stroke)
- }
- }
-
- private fun quickCenter() = (safe.left + dp(34f)) to (height - safe.bottom - dp(34f))
-
- private fun keyboardCenter() = if (buttonsOnly)
- width / 2f to (height - safe.bottom - dp(44f))
- else (safe.left + dp(90f)) to (height - safe.bottom - dp(34f))
-
- private fun keyboardContains(x: Float, y: Float): Boolean {
- if (!settings.keyboardButton || onKeyboard == null) return false
- val (cx, cy) = keyboardCenter()
- val dx = x - cx
- val dy = y - cy
- return dx * dx + dy * dy <= dp(26f) * dp(26f)
- }
-
- private fun quickContains(x: Float, y: Float): Boolean {
- val (cx, cy) = quickCenter()
- val radius = dp(26f)
- val dx = x - cx
- val dy = y - cy
- return dx * dx + dy * dy <= radius * radius
- }
-
- private fun drawArrow(canvas: Canvas, x: Float, y: Float, size: Float, direction: Int) {
- val (fx, fy) = when (direction) {
- 0 -> 0f to -1f
- 1 -> 1f to 0f
- 2 -> 0f to 1f
- else -> -1f to 0f
- }
- arrow.reset()
- arrow.moveTo(x + fx * size, y + fy * size)
- arrow.lineTo(x - fx * size * 0.7f - fy * size, y - fy * size * 0.7f + fx * size)
- arrow.lineTo(x - fx * size * 0.7f + fy * size, y - fy * size * 0.7f - fx * size)
- arrow.close()
- fill.color = text.color
- canvas.drawPath(arrow, fill)
- }
-
- @SuppressLint("ClickableViewAccessibility")
- override fun onTouchEvent(event: MotionEvent): Boolean {
- if (editing) return onEditTouch(event)
- if (event.getToolType(event.actionIndex) == MotionEvent.TOOL_TYPE_MOUSE) return false
- when (event.actionMasked) {
- MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
- val index = event.actionIndex
- val x = event.getX(index)
- val y = event.getY(index)
- if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointerBits = 0
- if (event.actionMasked == MotionEvent.ACTION_POINTER_DOWN && forwardMiss(event, x, y)) return true
- if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
- if (event.actionMasked == MotionEvent.ACTION_DOWN && keyboardContains(x, y)) {
- keyboardPressedBy = event.getPointerId(index)
- invalidate()
- return true
- }
- if (keyboardPressedBy != -1) return true
- if (!buttonsOnly && event.actionMasked == MotionEvent.ACTION_DOWN && quickContains(x, y)) {
- quickPressedBy = event.getPointerId(index)
- return true
- }
- if (quickPressedBy != -1) return true
- if (quickHidden) return false
- val control = controlAt(x, y) ?: adaptiveStickAt(x, y) ?: return false
- if (control.pressedBy != -1) return true
- control.pressedBy = event.getPointerId(index)
- if (control.stick >= 0) {
- control.clicked = settings.stickClick && control.lastUp > 0L && event.eventTime - control.lastUp < DOUBLE_TAP_MS
- control.downAt = event.eventTime
- control.downX = event.getX(index)
- control.downY = event.getY(index)
- control.travel = 0f
- val adaptive = settings.adaptiveSticks
- control.ax = if (adaptive) event.getX(index) else control.cx
- control.ay = if (adaptive) event.getY(index) else control.cy
- control.drag(event.getX(index), event.getY(index))
- control.dirty = true
- }
- if (SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
- apply()
- return true
- }
- MotionEvent.ACTION_MOVE -> {
- if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
- if (keyboardPressedBy != -1) return true
- if (quickPressedBy != -1) return true
- var changed = false
- var stickMoved = false
- for (index in 0 until event.pointerCount) {
- val pointer = event.getPointerId(index)
- if (forwardedPointerBits and (1 shl pointer) != 0) continue
- val x = event.getX(index)
- val y = event.getY(index)
- val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
- if (stick != null) { stickMoved = stick.drag(x, y) || stickMoved; continue }
- val over = controlAt(x, y)?.takeIf { it.stick < 0 }
- for (control in controls) {
- if (control.stick < 0 && control.pressedBy == pointer && control !== over) {
- control.pressedBy = -1
- changed = true
- }
- }
- if (over != null && over.pressedBy == -1) {
- over.pressedBy = pointer
- changed = true
- }
- }
- if (changed) apply() else if (stickMoved) apply(stickOnly = true)
- return true
- }
- MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
- val pointer = event.getPointerId(event.actionIndex)
- if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
- if (event.actionMasked == MotionEvent.ACTION_CANCEL) {
- forwardedPointerBits = 0
- releaseAll()
- return true
- }
- if (forwardedPointerBits and (1 shl pointer) != 0) {
- forwardedPointerBits = forwardedPointerBits and (1 shl pointer).inv()
- return true
- }
- if (keyboardPressedBy == pointer) {
- val tapped = event.actionMasked == MotionEvent.ACTION_UP && keyboardContains(event.x, event.y)
- keyboardPressedBy = -1
- invalidate()
- if (tapped) { releaseAll(); onKeyboard?.invoke() }
- return true
- }
- if (quickPressedBy == pointer) {
- val toggled = event.actionMasked == MotionEvent.ACTION_UP && quickContains(event.x, event.y)
- quickPressedBy = -1
- if (toggled) setQuickHidden(!quickHidden)
- return true
- }
- if (quickHidden) return false
- var changed = false
- for (control in controls) {
- if (control.pressedBy == pointer || event.actionMasked == MotionEvent.ACTION_CANCEL) {
- if (control.pressedBy != -1) changed = true
- if (control.stick >= 0 && control.pressedBy != -1) control.lastUp = if (stickTap(control, event)) event.eventTime else 0L
- control.pressedBy = -1
- control.clicked = false
- if (control.stick >= 0 && (control.kx != 0f || control.ky != 0f)) control.dirty = true
- control.kx = 0f; control.ky = 0f
- }
- }
- if (changed) apply()
- return true
- }
- }
- return false
- }
-
- private fun forwardMiss(event: MotionEvent, x: Float, y: Float): Boolean {
- if (onTouchMiss == null || keyboardPressedBy != -1 || quickPressedBy != -1) return false
- if (!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null) return false
- forwardedPointerBits = forwardedPointerBits or (1 shl event.getPointerId(event.actionIndex))
- forwardPointers(event, forwardedPointerBits)
- return true
- }
-
- private fun forwardPointers(event: MotionEvent, pointerIdBits: Int) {
- val split = event.pointerSubset(pointerIdBits) ?: return
- try {
- onTouchMiss?.invoke(split)
- } finally {
- split.recycle()
- }
- }
-
- private fun onEditTouch(event: MotionEvent): Boolean {
- when (event.actionMasked) {
- MotionEvent.ACTION_DOWN -> {
- clearSnapGuides()
- val control = controlAt(event.x, event.y)
- selected = control?.group
- val group = selected ?: run { invalidate(); return false }
- val (x, y) = centre(group)
- grabX = x - event.x
- grabY = y - event.y
- invalidate()
- }
- MotionEvent.ACTION_MOVE -> {
- val group = selected ?: return true
- ignoreSaved = false
- val rawX = event.x + grabX
- val rawY = event.y + grabY
- val others = groups.filter { it != group && members(it).any(::isVisible) }.map { centre(it) }
- val nextX = if (snap) closestSnap(rawX, others.map { it.first } + width / 2f) else null
- val nextY = if (snap) closestSnap(rawY, others.map { it.second }) else null
- put(group, nextX ?: rawX, nextY ?: rawY)
- clamp(group)
- val (x, y) = centre(group)
- val visibleX = nextX?.takeIf { abs(x - it) <= SNAP_TOLERANCE_PX }
- val visibleY = nextY?.takeIf { abs(y - it) <= SNAP_TOLERANCE_PX }
- if ((visibleX != null && visibleX != snapX) || (visibleY != null && visibleY != snapY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
- snapX = visibleX
- snapY = visibleY
- invalidate()
- }
- MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> clearSnapGuides()
- }
- return true
- }
-
- private fun closestSnap(position: Float, targets: List): Float? =
- targets.minByOrNull { abs(position - it) }?.takeIf { abs(position - it) <= dp(SNAP_DP) }
-
- fun takesTouchAt(x: Float, y: Float): Boolean =
- editing || keyboardContains(x, y) || (!buttonsOnly && quickContains(x, y)) ||
- (!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null)
-
- private fun controlAt(x: Float, y: Float): Control? =
- controls.firstOrNull {
- !quickHidden && isVisible(it) && (editing || !settings.adaptiveSticks || it.stick < 0) && it.contains(x, y, it.radius)
- }
-
- private fun adaptiveStickAt(x: Float, y: Float): Control? {
- if (!settings.adaptiveSticks || editing || buttonsOnly || quickHidden) return null
- if (x < safe.left || x >= width - safe.right || y < safe.top || y >= height - safe.bottom) return null
- if (controls.any { control ->
- control.stick < 0 && isVisible(control) && control.contains(x, y, control.radius, 5f)
- }) return null
- return controls.filter { control ->
- val dx = if (control.stick == 0) max(0f, x - control.cx) else x - control.cx
- val dy = y - control.cy
- val reach = control.radius * 1.4f * sqrt(1.5f)
- control.stick >= 0 && isVisible(control) && control.pressedBy == -1 &&
- dx * dx + dy * dy <= reach * reach
- }.minByOrNull { control ->
- val dx = x - control.cx
- val dy = y - control.cy
- dx * dx + dy * dy
- }
- }
-
- private fun isVisible(control: Control): Boolean = when {
- !editing && control.id == "guide" && !settings.steamButton -> false
- !editing && control.id == "qam" && !settings.qamButton -> false
- buttonsOnly && !editing -> control.id == "guide" || control.id == "qam"
- else -> control.target != ControllerPrefs.OFF
- }
-
- private fun apply(stickOnly: Boolean = false) {
- val bridge = pad
- if (bridge == null || editing) { invalidate(); return }
- val qamHeld = controls.any { it.id == "qam" && it.pressedBy != -1 }
- if (buttonsOnly) {
- bridge.setSystemButtons(controls.any { it.id == "guide" && it.pressedBy != -1 }, qamHeld)
- } else {
- bridge.setSystemButtons(false, qamHeld)
- val stickWrites = controls.filter { it.stick >= 0 && it.dirty }.fold(0) { mask, control ->
- mask or if (control.stick == 0) PadBridge.LEFT_STICK else PadBridge.RIGHT_STICK
- }
- bridge.applyTouch(stickWrites) { state ->
- val used = HashSet()
- val held = HashSet()
- for (control in controls) {
- when {
- control.stick >= 0 -> {
- val click = if (control.stick == 0) "l3" else "r3"
- if (settings.stickClick) used.add(click)
- if (control.clicked) held.add(click)
- if (!control.dirty) continue
- if (control.stick == 0) { state.leftX = control.kx / control.radius; state.leftY = control.ky / control.radius }
- else { state.rightX = control.kx / control.radius; state.rightY = control.ky / control.radius }
- control.dirty = false
- }
- control.id == "qam" || control.target == ControllerPrefs.OFF -> {}
- else -> {
- used.add(control.target)
- if (control.pressedBy != -1) held.add(control.target)
- }
- }
- }
- for (target in used) write(state, target, target in held)
- }
- }
- if (stickOnly) stickRedraw.request() else invalidate()
- }
-
- private fun write(state: PadState, target: String, down: Boolean) {
- when (target) {
- "a" -> state.press(PadState.A, down)
- "b" -> state.press(PadState.B, down)
- "x" -> state.press(PadState.X, down)
- "y" -> state.press(PadState.Y, down)
- "lb" -> state.press(PadState.LB, down)
- "rb" -> state.press(PadState.RB, down)
- "select" -> state.press(PadState.SELECT, down)
- "start" -> state.press(PadState.START, down)
- "l3" -> state.press(PadState.L3, down)
- "r3" -> state.press(PadState.R3, down)
- "guide" -> state.press(PadState.GUIDE, down)
- "lt" -> state.leftTrigger = if (down) 1f else 0f
- "rt" -> state.rightTrigger = if (down) 1f else 0f
- "up" -> state.up = down
- "right" -> state.right = down
- "down" -> state.down = down
- "left" -> state.left = down
- }
- }
-
- fun releaseAll() {
- quickPressedBy = -1
- keyboardPressedBy = -1
- invalidate()
- if (controls.none { it.pressedBy != -1 || it.clicked } && !buttonsOnly) return
- controls.forEach {
- it.pressedBy = -1
- it.clicked = false
- it.lastUp = 0L
- if (it.stick >= 0 && (it.kx != 0f || it.ky != 0f)) it.dirty = true
- it.kx = 0f; it.ky = 0f
- }
- apply()
- }
-
- private companion object {
- const val DOUBLE_TAP_MS = 300L
- const val STICK_TAP_MS = 200L
-
- internal fun stickTap(downAt: Long, upAt: Long, travel: Float, slop: Float, clicked: Boolean, cancelled: Boolean): Boolean =
- !clicked && !cancelled && upAt - downAt <= STICK_TAP_MS && travel <= slop
- const val STICK_REDRAW_MS = 33L
- const val MIN_STICK_MOVE_PX = 1f
- const val MIN_FACE_MM = 9.5f
- const val FULL_SIZE_HEIGHT_MM = 85f
- const val BOTTOM_MARGIN_MM = 5f
- const val DROP_DEGREES = 35.0
- const val PHONE_MAX_HEIGHT_MM = 90f
- const val SHOULDER_WIDTH = 1.45f
- const val SHOULDER_HEIGHT = 0.8f
- const val SNAP_DP = 9f
- const val SNAP_TOLERANCE_PX = 1f
- val shoulderIds = setOf("lb", "rb", "lt", "rt")
- val directions = listOf("up", "right", "down", "left")
- }
+ override fun onDetachedFromWindow() { releaseAll(); super.onDetachedFromWindow() }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
index 4bf45e9fee..0d0dbc2f71 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
+++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
@@ -59,11 +59,25 @@ public final class PadBridge {
private final int[] retainedSticks = new int[SLOTS];
private final PadState effectiveState = new PadState();
private final PadState homeGuideReport = new PadState();
+ private final PadState combinedState = new PadState();
+ private InputRouter inputRouter;
+ private final InputRouter.PadSource[] physicalRoutes = new InputRouter.PadSource[SLOTS];
+ private final java.util.IdentityHashMap