revert(input): restore pre-overhaul controls (#2958)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-20 19:43:09 -05:00
1 parent 33761c30ab
commit 9925873764
170 files changed
+3980 -4927

No files matched your search

@@ -171,6 +171,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var pipAutoEnter by mutableStateOf(false)
private var unfoldedControls by mutableStateOf(false)
private var unfoldedControlsWithController by mutableStateOf(false)
private var adaptiveSticks by mutableStateOf<Boolean?>(null)
private var quickButtons by mutableStateOf<Map<InputCommand, Boolean>>(emptyMap())
private var picturePosition by mutableStateOf("center")
private var integerScaling by mutableStateOf(false)
@@ -189,7 +191,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private var unfoldedPanel by mutableStateOf<OnScreenControls?>(null)
private var unfoldedColumn: android.widget.LinearLayout? = null
private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null
private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null
private var unfoldedDeckPanel by mutableStateOf<com.droiddeck.launcher.input.DeckPanel?>(null)
private var deckPanelLayouts: Map<com.droiddeck.launcher.input.DeckPanel, com.droiddeck.launcher.input.SavedInputLayout?> = emptyMap()
private lateinit var sessionRoot: FrameLayout
private var inputRouter: InputRouter? = null
@@ -260,7 +264,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var steamController: SteamControllerBle? = null
private var onScreenControls: OnScreenControls? = null
private var bottomInputControls: OnScreenControls? = null
private var primaryInputLayout by mutableStateOf<com.droiddeck.launcher.input.SavedInputLayout?>(null)
private var primaryInputLayout: com.droiddeck.launcher.input.SavedInputLayout? = null
private var secondaryInputLayout by mutableStateOf<com.droiddeck.launcher.input.SavedInputLayout?>(null)
private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null
private var steamTouchAvailable by mutableStateOf(false)
@@ -643,18 +647,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var oscRearButtons by mutableStateOf(false)
private var oscTrackpads by mutableStateOf(false)
private var onScreenButtonsVisible by mutableStateOf(false)
private var layoutOptions by mutableStateOf<List<com.droiddeck.launcher.input.ControlsChoice.Option>>(emptyList())
private var layoutChoice by mutableStateOf("")
private var layoutHint by mutableStateOf<String?>(null)
private var layoutEditor by mutableStateOf<Triple<String, String, String>?>(null)
private var layoutEditorScope: String? = null
private var layoutEditorSplit: com.droiddeck.launcher.ui.InputEditorSplit? = null
private var controlsGame: Long? = null
private var controllerInUse = false
private var controlsHiddenByTap = false
private var secondScreenMode by mutableStateOf(SessionState.secondScreenMode)
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private var selectedSecondScreenDisplay by mutableStateOf(SessionState.secondScreenDisplay)
@@ -857,7 +850,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
bridge.setStickDeadZone(ControllerPrefs.deadZone(this))
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, ::noteRemappedControllerUse) }
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
@@ -871,15 +864,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
bridge.setExcluded(vr::owns)
joyConVr = vr
}
SteamControllerBle.listener = {
uiHandler.post {
if (isDestroyed) return@post
if (SteamControllerBle.connected) controllerInUse = true
updatePadMotion()
refreshControls()
}
}
steamController = SteamControllerBle(this, inputRouter, ::noteSteamControllerUse).also { it.start() }
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
!SessionPrefs.bluetoothAsked(this)) {
SessionPrefs.setBluetoothAsked(this)
@@ -892,12 +878,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionState.deckPadListener = deckPadListener
openDeckRing("activity created")
bridge.setOnPlayerInput(::onPadInput)
bridge.setOnPhysicalInput(::noteControllerUse)
controllerInUse = PadBridge.anyControllerConnected() || SteamControllerBle.connected
onScreenControls = OnScreenControls(this, bridge).also { controls ->
controls.updateLayout(primaryInputLayout)
controls.onCornerTap = ::onControlsCornerTap
controls.onCornerHold = ::openControllerMenu
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())
@@ -977,7 +959,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
hud = DroidDeckHudHost(this)
hud.onConfigChanged = { hudConfig = DroidDeckHudConfig.load(this) }
hud.passesTouchAt = ::controlTakesTouchAt
hud.attach(root, onScreenControls?.let(root::indexOfChild)?.takeIf { it >= 0 } ?: root.childCount)
hud.attach(root, root.childCount)
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
hud.onPresentingWindowChanged = {
CompositorHost.rearmFrameGen { applyFrameGen(force = true) }
@@ -1269,19 +1251,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
layoutEditor?.let { (profile, layout, bindings) ->
com.droiddeck.launcher.ui.InputSurfaceDialog(profile, onDismiss = {
layoutEditor = null; inputSettingsOpen = false
refreshInputProfile(); updateOnScreenControls()
}, onChanged = { refreshInputProfile() }, role = InputRole.PRIMARY, layoutId = layout, bindingsId = bindings,
scope = layoutEditorScope, split = layoutEditorSplit)
}
if (inputSettingsOpen && layoutEditor == null) com.droiddeck.launcher.ui.InputSettingsDialog(
desktop = loadingMode() == SessionService.MODE_DESKTOP,
if (inputSettingsOpen) com.droiddeck.launcher.ui.InputSettingsDialog(
onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() },
onChanged = {
controllerSettings = ControllerPrefs.read(this@SessionActivity)
oscMode = sessionOscMode()
oscMode = SessionPrefs.oscMode(this@SessionActivity, SessionState.mode == SessionService.MODE_STEAM)
padBridge?.setStickDeadZone(ControllerPrefs.deadZone(this@SessionActivity))
joyConVr?.refresh()
onScreenControls?.reload()
@@ -1462,7 +1436,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
frameGen = frameGen,
frameGenTargetGameId = frameGenTargetGameId()?.toString(),
frameGenTargetGameName = frameGenTargetGameName(),
frameGenTargetGameName = when {
!drawerGameProfileFollowState.followsSteam ->
drawerGameProfileRefresh.data?.profiles
?.firstOrNull { it.first == frameGenTargetGameId() }?.second
SessionState.mode == SessionService.MODE_STEAM -> frameGenActiveGameName
SessionState.mode == SessionService.MODE_RUN ->
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program)
else -> drawerGameProfileRefresh.data?.profiles
?.firstOrNull { it.first == frameGenTargetGameId() }?.second
},
hasGameOverride = frameGenHasGameOverride,
lossless = lossless,
oscMode = oscMode, suspendPolicy = suspendPolicy,
@@ -1470,7 +1453,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
micAvailable = SessionState.micAvailable && !SessionState.suspended,
micEnabled = SessionState.micEnabled,
onMicEnabled = { SessionService.setMicEnabled(this@SessionActivity, it) },
touchAuto = getString(if (usingTouchpad(SessionPrefs.TOUCH_AUTO)) R.string.mode_touch_touchpad else R.string.mode_touch_mouse),
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
pen = penSettings.takeIf { penSeen },
onPen = { key, value -> SessionPrefs.setPenSetting(this@SessionActivity, key, value); readPrefs() },
fexPreset = fexPreset,
@@ -1702,7 +1685,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id))
com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id))
padType = id
refreshInputProfile()
},
backHold = backHold,
onBackHold = { on ->
@@ -1739,43 +1721,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
},
onOsc = { v ->
SessionPrefs.setOscMode(this@SessionActivity, v)
controlsHiddenByTap = false
readPrefs()
applyUnfoldedControls()
updateOnScreenControls()
if (v == SessionPrefs.OSC_STEAM_TOUCH && com.droiddeck.launcher.input.SteamTouchDevice.current == null)
Toast.makeText(this@SessionActivity, R.string.osc_style_next_session, Toast.LENGTH_LONG).show()
},
layoutGame = controlsGameName(),
layoutOptions = layoutOptions,
layoutChoice = layoutChoice,
layoutHint = layoutHint,
onLayout = ::chooseLayout,
onDeleteLayout = ::deleteLayout,
oscRearButtons = oscRearButtons.takeIf {
unfoldedPanel == null && oscMode != SessionPrefs.OSC_STEAM_QAM &&
!usesSteamTouchLayout() && com.droiddeck.launcher.input.PadKit.current(this).steam &&
primaryInputLayout?.let(com.droiddeck.launcher.input.OnScreenLayout::hasBuiltInKit) == true
},
oscTrackpads = oscTrackpads,
onOscRearButtons = { shown ->
SessionPrefs.setOscRearButtons(this, shown)
oscRearButtons = shown
onScreenControls?.reload()
bottomInputControls?.reload()
},
onOscTrackpads = { shown ->
SessionPrefs.setOscTrackpads(this, shown)
oscTrackpads = shown
onScreenControls?.reload()
bottomInputControls?.reload()
},
onEditLayout = when {
layoutChoice == com.droiddeck.launcher.input.GameControls.STEAM -> steamTouchControls?.takeIf { steamTouchAvailable && onScreenButtonsVisible && it.visibility == View.VISIBLE }?.let { view -> {
drawerOpen = false
view.startEditing()
} }
primaryInputLayout?.editable == true -> ({ openLayoutEditor() })
else -> null
},
onEditSteamTouch = if (steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && onScreenButtonsVisible) ({
drawerOpen = false
steamTouchControls?.startEditing()
}) else null,
onSuspendPolicy = { policy ->
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
suspendPolicy = policy
@@ -1835,6 +1789,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
},
unfoldedControls = unfoldedControls,
onUnfoldedControls = ::chooseUnfoldedControls,
adaptiveSticks = adaptiveSticks.takeIf {
unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && oscMode != SessionPrefs.OSC_STEAM_QAM && !steamTouchInUse
},
onAdaptiveSticks = { on ->
primaryInputLayout?.let { com.droiddeck.launcher.input.InputLibraries.setAdaptiveSticks(this@SessionActivity, it.id, on) }
refreshInputProfile()
},
quickButtons = quickButtons.takeIf {
unfoldedPanel != null || oscMode != SessionPrefs.OSC_NEVER && !steamTouchInUse
}.orEmpty(),
onQuickButton = { button, on ->
primaryInputLayout?.let { com.droiddeck.launcher.input.InputLibraries.setQuickButton(this@SessionActivity, it.id, button, on) }
refreshInputProfile()
updateOnScreenControls()
},
unfoldedControlsWithController = unfoldedControlsWithController,
onUnfoldedControlsWithController = ::chooseUnfoldedControlsWithController,
onBackground = { drawerOpen = false; pip.background(); moveTaskToBack(true) },
@@ -2054,17 +2023,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}, "drawer-components").start()
}
private fun frameGenTargetGameName(): String? = when {
!drawerGameProfileFollowState.followsSteam ->
drawerGameProfileRefresh.data?.profiles
?.firstOrNull { it.first == frameGenTargetGameId() }?.second
SessionState.mode == SessionService.MODE_STEAM -> frameGenActiveGameName
SessionState.mode == SessionService.MODE_RUN ->
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program)
else -> drawerGameProfileRefresh.data?.profiles
?.firstOrNull { it.first == frameGenTargetGameId() }?.second
}
private fun frameGenTargetGameId(): Long? {
if (!drawerGameProfileFollowState.followsSteam) {
return drawerGameProfileId
@@ -2082,8 +2040,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun loadFrameGenFor(appId: Long?) {
val layoutGame = controlsGameId()
if (layoutGame != controlsGame) { controlsGame = layoutGame; uiHandler.post { refreshInputProfile(); updateOnScreenControls() } }
val profileId = appId?.toString()
frameGen = FrameGen.mode(this, profileId)
frameGenHasGameOverride = appId?.let {
@@ -2578,9 +2534,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this)
oscMode = sessionOscMode()
oscRearButtons = SessionPrefs.oscRearButtons(this)
oscTrackpads = SessionPrefs.oscTrackpads(this)
oscMode = SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM)
backHold = SessionPrefs.backHold(this)
backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this)
@@ -3666,6 +3620,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
return onScreenControls?.let { takes(it, it::takesTouchAt) } == true ||
steamTouchControls?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedDeckSurface?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedColumn?.getChildAt(0)?.let { takes(it) { _, _ -> true } } == true
}
@@ -3676,7 +3631,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
(event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN) || PenStream.penIndex(event) >= 0)) {
drawerControllerActive = false
gestureTouchStreamGate.reset()
if (event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) noteScreenTouch(event)
}
return super.dispatchTouchEvent(event)
}
@@ -4426,73 +4380,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (started && displayId !in inputWindowDisplays && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
}
private fun controlsGameId(): Long? = frameGenTargetGameId()
private fun controlsGameName(): String? = controlsGameId()?.let { frameGenTargetGameName() }
private fun gameLibrary(): com.droiddeck.launcher.input.InputLibrary =
com.droiddeck.launcher.input.ControlsChoice.library(this, controlsGameId(), loadingMode() == SessionService.MODE_DESKTOP)
private fun refreshLayoutOptions() {
val steam = SessionState.mode == SessionService.MODE_STEAM
val game = controlsGameId()
val desktop = loadingMode() == SessionService.MODE_DESKTOP
layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName(), desktop)
layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, desktop)
layoutHint = if (com.droiddeck.launcher.input.ControlsChoice.steamUnavailable(this, game, steam)) getString(R.string.osc_layout_steam_unavailable) else null
}
private fun deleteLayout(id: String) {
runCatching { com.droiddeck.launcher.input.ControlsChoice.delete(this, id) }.onFailure { Log.w(TAG, "could not delete layout $id", it) }
refreshLayoutOptions()
}
private fun chooseLayout(id: String) {
val game = controlsGameId()
val name = controlsGameName()
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val created = runCatching {
if (id == com.droiddeck.launcher.input.ControlsChoice.NEW) {
if (game != null && name != null) com.droiddeck.launcher.input.ControlsChoice.newForGame(this, game, name, desktop) else null
} else { com.droiddeck.launcher.input.ControlsChoice.choose(this, game, id, desktop, name); null }
}.onFailure { Log.w(TAG, "could not choose layout $id", it) }.getOrNull()
releasePads()
refreshInputProfile()
updateOnScreenControls()
if (created != null) openLayoutEditor()
}
private fun openLayoutEditor() {
val game = controlsGameId()
val name = controlsGameName()
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val target = com.droiddeck.launcher.input.ControlsChoice.editTarget(this, game, desktop) ?: return
val layoutName = com.droiddeck.launcher.input.InputLibraries.read(this).layouts.firstOrNull { it.id == target.second }?.name ?: return
val own = com.droiddeck.launcher.input.ControlsChoice.hasOwn(this, game)
val shared = com.droiddeck.launcher.input.ControlsChoice.shared(this, game)
layoutEditorScope = when {
game == null || name == null || !own -> getString(R.string.osc_scope_default, layoutName)
shared -> getString(R.string.osc_scope_shared, layoutName)
layoutName == name -> getString(R.string.osc_scope_own, name)
else -> getString(R.string.osc_scope_game, layoutName, name)
}
layoutEditorSplit = if (game != null && name != null && shared) com.droiddeck.launcher.ui.InputEditorSplit(getString(R.string.osc_just_this_game),
getString(R.string.osc_scope_game, layoutName, name),
{ library, layoutId, bindingsId -> com.droiddeck.launcher.input.ControlsChoice.copyForGame(this, library, game, name, desktop, layoutId, bindingsId) },
{ bindingsId -> com.droiddeck.launcher.input.ControlsChoice.useForGame(this, game, name, bindingsId) }) else null
releasePads()
drawerOpen = false
layoutEditor = target
inputSettingsOpen = true
}
private fun refreshInputProfile() {
val library = gameLibrary()
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
val desktop = loadingMode() == SessionService.MODE_DESKTOP
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this))
stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this))
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
refreshLayoutOptions()
adaptiveSticks = primaryInputLayout?.adaptiveSticks
quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty()
secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.panel(this))
deckPanelLayouts = com.droiddeck.launcher.input.DeckPanel.entries.associateWith { library.panelLayout(desktop, it.bindings) }
inputUsesLocalActions = InputControl.padControls.any { inputProfile.action(InputRole.PHYSICAL, it) !is InputAction.Native }
@@ -4508,7 +4403,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
onScreenControls?.updateLayout(primaryInputLayout)
bottomInputControls?.updateLayout(primaryInputLayout)
unfoldedPanel?.updateLayout(primaryInputLayout)
if (onScreenControls != null) applyUnfoldedControls()
if (unfoldedPanel != null) applyUnfoldedControls()
showUnfoldedDeckPanel()
updateOnScreenPad()
secondScreenPresentation?.refreshControls()
}
@@ -4543,8 +4439,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun controlsBelowWanted(): Boolean {
if (!::sessionRoot.isInitialized || glassesScreen != null || bottomGame != null || cardboard.enabled) return false
val mode = sessionOscMode()
if (mode == SessionPrefs.OSC_NEVER || mode == SessionPrefs.OSC_STEAM_QAM || usesSteamTouchLayout()) return false
return SessionPrefs.controlsBelowWanted(this, SessionState.mode, sessionRoot.width, sessionRoot.height,
pipUi || isInPictureInPictureMode)
}
@@ -4557,8 +4451,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val tabRow = unfoldedColumn?.getChildAt(0)?.height?.let {
it - (com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()
} ?: 0
val aspect = if (SessionState.followScreen) 16f / 9f else outputSize().let { (w, h) -> w.toFloat() / h.coerceAtLeast(1) }
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow, aspect)
val gameHeight = if (wanted) com.droiddeck.launcher.session.SessionDisplay.unfoldedGameHeight(width, height, tabRow)
else FrameLayout.LayoutParams.MATCH_PARENT
val params = surfaceView.layoutParams as FrameLayout.LayoutParams
if (params.height != gameHeight) {
@@ -4573,6 +4466,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (panel != null && (!wanted || panel.dock != dock)) {
sessionRoot.removeView(unfoldedColumn)
unfoldedColumn = null
unfoldedDeckSurface = null
unfoldedDeckPanel = null
unfoldedPanel = null
panel = null
if (!wanted) updateOnScreenControls()
@@ -4593,14 +4488,36 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
sessionRoot.addView(column, sessionRoot.indexOfChild(surfaceView) + 1)
unfoldedColumn = column
unfoldedPanel = panel
showUnfoldedDeckPanel()
updateOnScreenControls()
}
unfoldedColumn?.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
}
private fun unfoldedBar(): View = com.droiddeck.launcher.ui.bottomScreenBarView(this) {
com.droiddeck.launcher.ui.sessionBarModel(getString(R.string.deck_tab_gamepad),
{ chooseUnfoldedControls(false) }, { drawerOpen = true }, ::tapSteamButton, ::tapQam)
val deck = unfoldedDeckPanel
com.droiddeck.launcher.ui.sessionBarModel(getString(if (deck != null) R.string.second_mode_deck_controls else R.string.deck_tab_gamepad),
{ chooseUnfoldedControls(false) }, { drawerOpen = true }, ::tapSteamButton, ::tapQam,
tabs = deck?.let { com.droiddeck.launcher.ui.deckPanelTabs(this, it, ::selectDeckPanel) })
}
private fun showUnfoldedDeckPanel() {
val column = unfoldedColumn
val panel = unfoldedPanel
val selected = SessionPrefs.deckPanel(this).takeIf { column != null && panel?.dock?.grips == true }
unfoldedDeckPanel = selected
val layout = selected?.takeIf { it != com.droiddeck.launcher.input.DeckPanel.GAMEPAD }?.let { deckPanelLayouts[it] }
if (layout != null && unfoldedDeckSurface?.tag == layout) return
unfoldedDeckSurface?.let { it.releaseInputs(); column?.removeView(it) }
unfoldedDeckSurface = null
if (column == null || panel == null) return
if (layout == null) { panel.visibility = View.VISIBLE; return }
panel.releaseAll()
panel.visibility = View.GONE
unfoldedDeckSurface = com.droiddeck.launcher.ui.InputSurfaceView(this, padBridge, layout.elements, InputRole.PRIMARY, layout.style, haptics = true).also {
it.tag = layout
column.addView(it, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
}
}
private fun bottomKeyboardPresentation(): SecondScreenPresentation? {
@@ -4810,7 +4727,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun deliversTouches(mode: String) =
mode == SessionPrefs.TOUCH_DIRECT || mode == SessionPrefs.TOUCH_AUTO
private fun usingTouchpad(mode: String = routedTouchMode): Boolean = when (mode) {
private fun usingTouchpad(): Boolean = when (routedTouchMode) {
SessionPrefs.TOUCH_PAD -> true
SessionPrefs.TOUCH_DIRECT -> false
else -> SessionState.mode != SessionService.MODE_STEAM || SessionState.steamUi == "desktop"
@@ -4954,7 +4871,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var screenTapsClick = true
private fun onScreenMouseButtonShown(): Boolean = listOfNotNull(
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface,
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
secondScreenPresentation?.controlsView, swappedInputSurface,
).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
@@ -5378,7 +5295,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
val root = onScreenControls?.parent as? android.view.ViewGroup ?: return null
val view = com.droiddeck.launcher.input.SteamTouchControls(this, device,
onMenu = ::openControllerMenu, onKeyboard = ::togglePcKeyboard)
onMenu = { drawerOpen = true }, onKeyboard = ::togglePcKeyboard)
view.visibility = View.GONE
view.onEditingChanged = { touchEditorChanged() }
view.onOptions = { options ->
@@ -5408,141 +5325,99 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
updateOnScreenPad()
val c = onScreenControls
glassesSlot = when {
c == null || c.visibility != View.VISIBLE || c.hidden != null -> 0
c.shortcutsOnly -> -1
c.inputSurface.shownElements.any { it.id == com.droiddeck.launcher.input.KitLayout.KEYBOARD_ID } -> 2
c == null || c.visibility != View.VISIBLE || c.isPinnedOnly -> 0
c.isButtonsOnly -> -1
primaryInputLayout?.let { l -> l.elements.any { it.quickButton == InputCommand.KEYBOARD && !l.style.hides(it) } }
?: (controllerSettings?.keyboardButton != false) -> 2
else -> 1
}
}
private fun sessionOscMode() = SessionPrefs.oscMode(this, steamSession = SessionState.mode == SessionService.MODE_STEAM)
private fun usesSteamTouchLayout() = SessionState.mode == SessionService.MODE_STEAM &&
com.droiddeck.launcher.input.GameControls.steamLayout(this, controlsGameId())
private fun controlsPlan(): com.droiddeck.launcher.input.ControlsPresenter.Plan {
val steam = SessionState.mode == SessionService.MODE_STEAM
if (!PadBridge.anyControllerConnected() && !SteamControllerBle.connected) controllerInUse = false
return com.droiddeck.launcher.input.ControlsPresenter.plan(com.droiddeck.launcher.input.ControlsPresenter.State(
mode = sessionOscMode(),
desktop = SessionState.mode == SessionService.MODE_DESKTOP,
virtualPad = !steam || SessionPrefs.builtinPad(this),
covered = controlsCovered(),
controllerInUse = controllerInUse,
hiddenByTap = controlsHiddenByTap,
steamLayout = usesSteamTouchLayout(),
bottomScreen = bottomGame?.surfaceView?.parent is android.view.ViewGroup,
))
}
private fun controlsCovered() = pipUi || unfoldedPanel != null || pcKeyboardOpen || inputSettingsOpen || keyboardCoversPad()
private fun updateOnScreenPad() {
val controls = onScreenControls ?: return
fun hideBottomControls() { bottomInputControls?.takeIf { it.visibility == View.VISIBLE }?.let { it.releaseAll(); it.visibility = View.GONE } }
fun hideSteam() {
steamTouchControls?.let { it.cancelEditing(); it.releaseAll(); it.visibility = View.GONE }
val keyboardOver = controlsCovered() && usesSteamTouchLayout() && sessionOscMode() != SessionPrefs.OSC_STEAM_QAM
if (!keyboardOver) com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc")
.takeIf { it.isFile }
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM)
val controls = onScreenControls ?: return
fun showPinned() {
controls.setPinnedOnly(true)
val pinned = controls.hasPinned && !pipUi && !inputSettingsOpen
if (!pinned) controls.releaseAll()
controls.visibility = if (pinned) View.VISIBLE else View.GONE
}
val plan = controlsPlan()
onScreenButtonsVisible = plan.shown
val wantsSteam = plan.place == com.droiddeck.launcher.input.ControlsPresenter.Place.STEAM
val steam = if (wantsSteam) steamTouch() else null
steamTouchInUse = steam != null
uiHandler.removeCallbacks(steamTouchRetry)
if (wantsSteam && steam == null && !isFinishing && !isDestroyed) {
uiHandler.postDelayed(steamTouchRetry, 1000)
}
if (steam != null) {
if (pipUi || unfoldedPanel != null || pcKeyboardOpen || inputSettingsOpen ||
(SessionState.mode == SessionService.MODE_STEAM && !SessionPrefs.builtinPad(this))) {
onScreenButtonsVisible = false
hideBottomControls()
controls.releaseAll(); controls.visibility = View.GONE
if (!plan.shown) { steam.cancelEditing(); steam.releaseAll() }
steam.visibility = if (plan.shown) View.VISIBLE else View.GONE
// Steam takes seconds to configure a newly plugged touch controller, so hiding the layout keeps it plugged.
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = true
showPinned()
steamTouchControls?.let { it.cancelEditing(); it.releaseAll(); it.visibility = View.GONE }
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
applyTouchRouting()
return
}
hideSteam()
applyTouchRouting()
when (plan.place) {
com.droiddeck.launcher.input.ControlsPresenter.Place.BOTTOM -> {
val bottomRoot = bottomGame?.surfaceView?.parent as android.view.ViewGroup
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) }
view.onCornerTap = ::onControlsCornerTap
view.onCornerHold = ::openControllerMenu
bottomRoot.addView(view, android.view.ViewGroup.LayoutParams(-1, -1))
}
bottomInputControls = bottom
val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM
val wantsSteam = forced == SessionPrefs.OSC_STEAM_TOUCH && SessionState.mode == SessionService.MODE_STEAM
val steam = if (wantsSteam) steamTouch() else null
steamTouchInUse = steam != null
if (wantsSteam && steam == null && !isFinishing && !isDestroyed) {
uiHandler.removeCallbacks(steamTouchRetry)
uiHandler.postDelayed(steamTouchRetry, 1000)
}
if (steam == null) {
steamTouchControls?.let { it.cancelEditing(); it.releaseAll(); it.visibility = View.GONE }
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
applyTouchRouting()
}
controls.setButtonsOnly(buttonsOnly)
val show = when (forced) {
SessionPrefs.OSC_ALWAYS -> true
SessionPrefs.OSC_STEAM_QAM -> true
SessionPrefs.OSC_NEVER -> false
SessionPrefs.OSC_STEAM_TOUCH -> SessionState.mode == SessionService.MODE_STEAM ||
(!PadBridge.anyControllerConnected() && SessionState.mode != SessionService.MODE_DESKTOP)
else -> !PadBridge.anyControllerConnected() && !SteamControllerBle.connected &&
SessionState.mode != SessionService.MODE_DESKTOP
}
onScreenButtonsVisible = show
val drawn = show && !keyboardCoversPad()
if (steam != null) {
hideBottomControls()
showPinned()
if (!drawn) { steam.cancelEditing(); steam.releaseAll() }
steam.visibility = if (drawn) View.VISIBLE else View.GONE
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = show
applyTouchRouting()
Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden")
return
}
val bottomRoot = bottomGame?.surfaceView?.parent as? android.view.ViewGroup
if (bottomRoot != null && (drawn || controls.hasPinned)) {
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))
}
bottom.updateLayout(primaryInputLayout)
bottom.setPresentation(plan.hidden, plan.shortcutsOnly)
bottom.visibility = View.VISIBLE
}
com.droiddeck.launcher.input.ControlsPresenter.Place.MAIN,
com.droiddeck.launcher.input.ControlsPresenter.Place.STEAM -> {
hideBottomControls()
controls.setPresentation(plan.hidden, plan.shortcutsOnly)
controls.visibility = View.VISIBLE
}
else -> {
hideBottomControls()
controls.releaseAll()
controls.visibility = View.GONE
bottomInputControls = bottom
}
bottom.updateLayout(primaryInputLayout)
bottom.setButtonsOnly(buttonsOnly)
bottom.setPinnedOnly(!drawn)
bottom.visibility = View.VISIBLE
return
}
}
private fun onControlsCornerTap(next: OnScreenControls.Hidden?) {
controlsHiddenByTap = next == OnScreenControls.Hidden.BY_TAP
if (next == null) controllerInUse = false
updateOnScreenControls()
}
private fun openControllerMenu() {
drawerPage = SessionDrawerPage.CONTROLLER
drawerOpen = true
}
private fun noteRemappedControllerUse(event: KeyEvent) {
if (PadBridge.isControllerKeyEvent(event) ||
(event.isFromSource(InputDevice.SOURCE_GAMEPAD) && PadBridge.isFromController(event.device))) {
noteControllerUse()
}
}
private fun noteSteamControllerUse() {
uiHandler.post {
if (!isDestroyed && SteamControllerBle.connected) noteControllerUse()
}
}
private fun noteControllerUse() {
if (controllerInUse) return
controllerInUse = true
uiHandler.post {
val wasShown = onScreenButtonsVisible
updateOnScreenControls()
if (wasShown && controlsPlan().hidden == OnScreenControls.Hidden.BY_CONTROLLER)
Toast.makeText(this, R.string.osc_hidden_controller, Toast.LENGTH_SHORT).show()
}
}
private fun noteScreenTouch(event: MotionEvent) {
if (!controllerInUse) return
val corner = onScreenControls?.takeIf { it.isShown }?.let { c ->
val at = IntArray(2).also(c::getLocationOnScreen)
c.cornerTakes(event.rawX - at[0], event.rawY - at[1])
} == true
if (corner) return
controllerInUse = false
updateOnScreenControls()
hideBottomControls()
val wasDrawn = controls.visibility == View.VISIBLE && !controls.isPinnedOnly
if (!drawn) showPinned() else { controls.setPinnedOnly(false); controls.visibility = View.VISIBLE }
if (drawn == wasDrawn) return
Log.i(TAG, "on-screen controls " + when {
!drawn -> "hidden"
buttonsOnly -> "Steam + QAM"
else -> "full pad"
})
}
private fun desktopTextInput() =
@@ -5926,7 +5801,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!screenOff) {
gestureSettingsOpen = false
inputSettingsOpen = false
layoutEditor = null
}
releasePads()
heldKeys.clear()
@@ -6304,7 +6178,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
drawerControllerActive = false
gestureTouchStreamGate.reset()
if (controllerInUse && event.isFromSource(InputDevice.SOURCE_TOUCHSCREEN)) { controllerInUse = false; updateOnScreenControls() }
}
if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) return false
return onTouchEvent(event)
@@ -6350,7 +6223,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
androidx.compose.runtime.key(profileLayout) {
androidx.compose.ui.viewinterop.AndroidView(
factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge).also { it.showLayout(profileLayout); swappedInputSurface = it } },
factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(),
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } },
modifier = Modifier.fillMaxWidth().weight(1f),
onRelease = { if (swappedInputSurface === it) swappedInputSurface = null },
)
@@ -6677,7 +6551,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode != REQUEST_BLUETOOTH || grantResults.firstOrNull() != android.content.pm.PackageManager.PERMISSION_GRANTED) return
steamController?.stop()
steamController = SteamControllerBle(this, inputRouter, ::noteSteamControllerUse).also { it.start() }
steamController = SteamControllerBle(this, inputRouter).also { it.start() }
}
companion object {
@@ -7,6 +7,21 @@ object ControllerPrefs {
const val STEAM_BLUE = 0xFF1A9FFF.toInt()
const val OFF = "off"
val tints = listOf(
STEAM_BLUE to R.string.ctrl_tint_steam_blue,
0xFF66C0F4.toInt() to R.string.ctrl_tint_sky,
0xFFE8EEF4.toInt() to R.string.ctrl_tint_white,
0xFFC77DFF.toInt() to R.string.ctrl_tint_violet,
0xFF3DDC84.toInt() to R.string.ctrl_tint_green,
0xFFFFA726.toInt() to R.string.ctrl_tint_amber,
0xFFFF5252.toInt() to R.string.ctrl_tint_red,
0xFFFF6FB5.toInt() to R.string.ctrl_tint_pink,
)
val opacities = listOf(40, 60, 80, 100)
val sizes = listOf(80, 90, 100, 110, 125)
val deadZones = listOf(0, 5, 8, 12, 15, 20, 25)
const val DEFAULT_DEAD_ZONE_PERCENT = 12
@@ -24,15 +39,20 @@ object ControllerPrefs {
OFF to R.string.ctrl_target_hidden,
)
/** Settings still read: the rest only seed the one-time library and layout migrations. */
class Settings(
val tint: Int,
val opacity: Int,
val size: Int,
val stickClick: Boolean,
val adaptiveSticks: Boolean,
val rumble: Boolean,
val steamButton: Boolean,
val qamButton: Boolean,
val keyboardButton: Boolean,
val selectSteam: Boolean,
val joyConVr: Boolean,
val snap: Boolean,
val customLayout: Boolean,
val mapping: Map<String, String>,
val deadZone: Int,
)
@@ -43,17 +63,50 @@ object ControllerPrefs {
val p = prefs(context)
return Settings(
tint = p.getInt("tint", STEAM_BLUE),
opacity = p.getInt("opacity", 100).coerceIn(1, 100),
opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100,
size = p.getInt("size", 100).takeIf { it in sizes } ?: 100,
stickClick = p.getBoolean("stickClick", true),
adaptiveSticks = p.getBoolean("adaptiveSticks", true),
rumble = rumbleEnabled(context),
steamButton = p.getBoolean("steamButton", true),
qamButton = p.getBoolean("qamButton", true),
keyboardButton = p.getBoolean("keyboardButton", true),
selectSteam = p.getBoolean("selectSteam", false),
joyConVr = joyConVr(context),
snap = snap(context),
mapping = mappable.associate { (id, _) -> id to (p.getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id) },
customLayout = p.all.keys.any { it.startsWith("layout.") },
mapping = mappable.associate { (id, _) -> id to target(context, id) },
deadZone = deadZone(context),
)
}
fun target(context: Context, id: String): String =
prefs(context).getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id
fun setTarget(context: Context, id: String, target: String) {
prefs(context).edit().putString("map.$id", target).apply()
}
fun setTint(context: Context, tint: Int) {
prefs(context).edit().putInt("tint", tint).apply()
}
fun setOpacity(context: Context, percent: Int) {
prefs(context).edit().putInt("opacity", percent).apply()
}
fun setSize(context: Context, percent: Int) {
prefs(context).edit().putInt("size", percent).apply()
}
fun setStickClick(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("stickClick", on).apply()
}
fun setAdaptiveSticks(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
}
fun rumbleEnabled(context: Context): Boolean = prefs(context).getBoolean("rumble", true)
fun deadZone(context: Context): Int =
@@ -67,6 +120,18 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("rumble", on).apply()
}
fun setSteamButton(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("steamButton", on).apply()
}
fun setKeyboardButton(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("keyboardButton", on).apply()
}
fun setSelectSteam(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("selectSteam", on).apply()
}
fun joyConVr(context: Context): Boolean = prefs(context).getBoolean("joyConVr", true)
fun setJoyConVr(context: Context, on: Boolean) {
@@ -79,6 +144,24 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("snap", on).apply()
}
fun layout(context: Context, width: Int, height: Int): Map<String, Pair<Float, Float>> {
val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap()
return raw.split(';').mapNotNull { entry ->
val (group, pos) = entry.split(':').takeIf { it.size == 2 } ?: return@mapNotNull null
val (x, y) = pos.split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 2 } ?: return@mapNotNull null
group to (x to y)
}.toMap()
}
fun setLayout(context: Context, width: Int, height: Int, positions: Map<String, Pair<Float, Float>>) {
val raw = positions.entries.joinToString(";") { (group, pos) -> "$group:${pos.first},${pos.second}" }
prefs(context).edit().putString("layout.${width}x$height", raw).apply()
}
fun resetLayout(context: Context, width: Int, height: Int) {
prefs(context).edit().remove("layout.${width}x$height").apply()
}
fun resetAll(context: Context) {
prefs(context).edit().clear().putBoolean("rumble", true).apply()
}
@@ -1,216 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/** The on-screen layout each game draws, shared by the in-game Controller page and Settings › Controller. A null game is the default. */
object ControlsChoice {
const val NEW = "new"
const val DEFAULT = "default"
data class Game(val id: Long, val name: String, val layout: String)
private fun own(library: InputLibrary, id: String?): String? = id?.takeIf { bindings ->
library.bindings.any { it.id == bindings && !it.physical && it.layoutId?.let { l -> library.layouts.any { x -> x.id == l && x.supports(InputRole.PRIMARY) } } == true }
}
private fun own(context: Context, library: InputLibrary, game: Long?) = own(library, GameControls.bindings(context, game))
/** The input library with [game]'s main-screen layout selected, without saving it. */
fun library(context: Context, game: Long?, desktop: Boolean): InputLibrary {
val library = InputLibraries.read(context)
val chosen = own(context, library, game)
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
}
data class Option(val id: String, val name: String, val detail: String? = null, val deletable: Boolean = false)
/** Layouts made for one game, so they're listed only for that game. Layouts made before that was recorded are recognised by carrying the name of the game that draws them. */
private fun owners(context: Context, library: InputLibrary): Map<String, Set<Long>> {
val named = GameControls.games(context).mapNotNull { game ->
val layout = own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } ?: return@mapNotNull null
val name = GameControls.name(context, game) ?: return@mapNotNull null
(layout to game).takeIf { library.layouts.any { it.id == layout && it.name == name } }
}
return (named + GameControls.madeFor(context).toList()).groupBy({ it.first }, { it.second }).mapValues { it.value.toSet() }
}
private fun defaults(library: InputLibrary) =
listOf(false, true).mapNotNull { library.activeLayout(it, InputRole.PRIMARY)?.id }.toSet()
private fun deletable(context: Context, library: InputLibrary, layout: SavedInputLayout): Boolean {
if (!layout.editable || layout.id == InputLibraries.OVERLAY || layout.id in defaults(library)) return false
if (GameControls.games(context).any { game -> own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } == layout.id }) return false
return library.profiles.none { p -> p.parts.any { (role, part) -> part.layout == layout.id && drawn(library, p.id, role) } } &&
library.bindings.none { it.layoutId == layout.id && library.selectedBindings(it.id) }
}
/** Whether [profile]'s [role] part is what a mode shows, rather than one a choice made since covers. */
private fun drawn(library: InputLibrary, profile: String, role: InputRole) =
listOf(false, true).any { desktop -> library.activeId(desktop) == profile && library.selection(desktop).parts[role] == null }
private fun keeps(library: InputLibrary, profile: String) =
profile == InputProfile.GAME || profile == InputProfile.DESKTOP || listOf(false, true).any { library.activeId(it) == profile }
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null, desktop: Boolean = false): List<Option> {
val library = InputLibraries.read(context)
val own = game != null && game in GameControls.games(context)
val current = current(context, game, steamMode, desktop)
val owners = owners(context, library)
val defaults = defaults(library)
val forGame = gameName?.takeIf { game != null && it.isNotBlank() }
val newKitDetail = context.getString(R.string.osc_try_new_layout)
fun detail(layout: SavedInputLayout): String? = when {
OnScreenLayout.generated(layout) && current == InputLibraries.previousLayoutId(layout.id) -> newKitDetail
layout.kitless && layout.id.startsWith("kept.") && layout.id != current -> context.getString(R.string.osc_restore_previous_layout)
game != null && game in owners[layout.id].orEmpty() && layout.id !in defaults && forGame != null ->
context.getString(R.string.osc_layout_detail_game, forGame)
else -> null
}
val saved = library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }
.filter { l -> l.id == current || l.id in defaults || owners[l.id].isNullOrEmpty() || game in owners[l.id].orEmpty() }
.map { l -> Option(l.id, l.name, detail(l), l.id != current && deletable(context, library, l)) }
val stock = library.layouts.firstOrNull { it.id == InputLibraries.OVERLAY }
return (if (own) listOf(Option(DEFAULT, context.getString(R.string.osc_default))) else emptyList()) +
Option(InputLibraries.OVERLAY, context.getString(R.string.osc_layout_gamepad),
stock?.let(::detail) ?: context.getString(R.string.osc_layout_gamepad_detail)) +
(if (steamMode) listOf(Option(GameControls.STEAM, context.getString(R.string.osc_layout_steam), context.getString(R.string.osc_layout_steam_detail))) else emptyList()) +
saved +
(if (forGame != null) listOf(Option(NEW, context.getString(R.string.osc_layout_new_for, forGame))) else emptyList())
}
/** Whether [game] chose Steam's touch controls but runs where they can't be shown. */
fun steamUnavailable(context: Context, game: Long?, steamMode: Boolean) = !steamMode && GameControls.steamLayout(context, game)
/** Deletes the saved layout [id] and its actions. A profile that can no longer be chosen goes with it; one that can falls back to the stock layout. */
fun delete(context: Context, id: String) {
val games = GameControls.games(context).mapNotNull { GameControls.bindings(context, it) }.toSet()
InputLibraries.update(context) { library ->
val layout = library.layouts.first { it.id == id }
require(deletable(context, library, layout))
val users = library.usersOfLayout(id)
val orphans = users.filterNot { keeps(library, it.id) }
var result = users.filter { keeps(library, it.id) }.fold(library) { acc, p ->
p.parts.filterValues { it.layout == id }.keys.fold(acc) { lib, role ->
lib.chooseLayout(p.id, role, when {
role == InputRole.PRIMARY -> InputLibraries.OVERLAY
p.base == InputProfile.DESKTOP -> InputLibraries.TRACKPAD
else -> InputLibraries.DECK
})
}
}
result = orphans.fold(result) { acc, p -> acc.removeProfile(p.id) }
val loose = orphans.flatMap { p -> p.parts.values.map { it.bindings } }.toSet()
.filter { b -> b !in games && result.usersOfBindings(b).isEmpty() && !result.selectedBindings(b) && result.bindings.any { it.id == b } }
.filterNot { b -> InputStockLayouts.presets(InputStockLayouts.layouts()).any { it.id == b } }
result = loose.fold(result) { acc, b -> acc.removeBindings(b) }
result.removeLayout(id)
}
GameControls.forgetLayout(context, id)
}
fun current(context: Context, game: Long?, steamMode: Boolean, desktop: Boolean = false): String =
if (steamMode && GameControls.steamLayout(context, game)) GameControls.STEAM
else library(context, game, desktop).activeLayout(desktop, InputRole.PRIMARY)?.id ?: InputLibraries.OVERLAY
fun choose(context: Context, game: Long?, id: String, desktop: Boolean, gameName: String? = null) {
require(id != NEW)
if (id == DEFAULT) { if (game != null) useDefault(context, game); return }
val steam = id == GameControls.STEAM
val bindings = if (steam) null else {
val library = InputLibraries.read(context)
val layout = library.layouts.first { it.id == id }
val available = library.bindings.filter { !it.physical && it.layoutId == layout.id && it.compatible(layout) }
val preferred = listOfNotNull(own(context, library, game), library.activePart(desktop, InputRole.PRIMARY).bindings,
library.profile(library.activeId(desktop)).binding(InputRole.PRIMARY))
preferred.firstNotNullOfOrNull { id -> relatedPreset(library, available, id, layout.id) }
?: available.firstOrNull { it.id != InputLibraries.primaryOf(library, !desktop) }?.id ?: newInputId().also { newId ->
InputLibraries.update(context) { it.withPreset(SavedInputBindings(newId, layout.name, false, layout.id)) }
}
}
if (game != null) GameControls.choose(context, game, bindings, steam, gameName)
else {
if (bindings != null) InputLibraries.update(context) { it.selectPart(desktop, InputRole.PRIMARY, bindings) }
SessionPrefs.setSteamTouchLayout(context, steam)
}
}
private fun relatedPreset(library: InputLibrary, available: List<SavedInputBindings>, id: String, target: String): String? {
val from = library.preset(id).layoutId ?: return null
return available.firstOrNull { candidate ->
candidate.id == id ||
target == InputLibraries.previousLayoutId(from) && candidate.id == InputLibraries.previousBindingsId(id, target) ||
from == InputLibraries.previousLayoutId(target) && id == InputLibraries.previousBindingsId(candidate.id, from)
}?.id
}
/** Copies the layout [game] draws now, actions included, into a layout of its own and chooses it for that game only. */
fun newForGame(context: Context, game: Long, name: String, desktop: Boolean): Pair<String, String> {
val layoutId = newInputId()
val bindingsId = newInputId()
InputLibraries.update(context) { latest -> copyForGame(context, latest, game, name, desktop, layoutId, bindingsId) }
GameControls.markMadeFor(context, layoutId, game)
GameControls.choose(context, game, bindingsId, steam = false, name = name)
return layoutId to bindingsId
}
/** [latest] with a copy of the layout [game] draws now, actions included, under the given ids. Nothing is chosen for the game. */
fun copyForGame(context: Context, latest: InputLibrary, game: Long, name: String, desktop: Boolean, layoutId: String, bindingsId: String): InputLibrary {
run {
val chosen = own(context, latest, game)
val part = (if (chosen == null) latest else latest.selectPart(desktop, InputRole.PRIMARY, chosen)).activePart(desktop, InputRole.PRIMARY)
val source = latest.layouts.firstOrNull { it.id == part.layout && it.editable } ?: latest.layouts.first { it.id == InputLibraries.OVERLAY }
val actions = latest.bindings.firstOrNull { it.id == part.bindings && it.compatible(source) }
?: latest.bindings.firstOrNull { !it.physical && it.compatible(source) }
?: SavedInputBindings(bindingsId, source.name, false, source.id)
val title = name.trim().take(80).ifEmpty { source.name }
return latest.withLayout(source.derived(layoutId, title)).withPreset(actions.copy(id = bindingsId, name = title, layoutId = layoutId))
}
}
/** Uses [bindingsId], made by [copyForGame], for [game] only. */
fun useForGame(context: Context, game: Long, name: String, bindingsId: String) {
InputLibraries.read(context).bindings.firstOrNull { it.id == bindingsId }?.layoutId?.let { GameControls.markMadeFor(context, it, game) }
GameControls.choose(context, game, bindingsId, steam = false, name = name)
}
/** The profile, layout and actions the editor opens for [game], or null when its layout can't be edited here. */
fun editTarget(context: Context, game: Long?, desktop: Boolean): Triple<String, String, String>? {
val library = library(context, game, desktop)
val layout = library.activeLayout(desktop, InputRole.PRIMARY)?.takeIf { it.editable } ?: return null
return Triple(library.activeId(desktop), layout.id, library.activePart(desktop, InputRole.PRIMARY).bindings)
}
/** Whether [game] has a layout of its own, rather than the default. */
fun hasOwn(context: Context, game: Long?): Boolean = own(context, InputLibraries.read(context), game) != null
/** Whether saving an edit of [game]'s layout would also change the default or another game. */
fun shared(context: Context, game: Long?): Boolean {
game ?: return false
val library = InputLibraries.read(context)
val bindings = own(context, library, game) ?: return true
val layout = library.preset(bindings).layoutId
fun drawsLayout(id: String) = library.bindings.firstOrNull { it.id == id }?.layoutId == layout
return library.usersOfLayout(layout ?: return true).isNotEmpty() ||
library.selections.values.any { s -> s.parts[InputRole.PRIMARY]?.let(::drawsLayout) == true } ||
GameControls.games(context).any { it != game && own(context, library, it)?.let(::drawsLayout) == true }
}
fun useDefault(context: Context, game: Long) = GameControls.clear(context, game)
/** Games with a layout of their own, by name. */
fun games(context: Context): List<Game> {
val library = InputLibraries.read(context)
return GameControls.games(context).mapNotNull { id ->
val layout = when {
GameControls.steamLayout(context, id) -> context.getString(R.string.osc_layout_steam)
else -> own(context, library, id)?.let { b -> library.layouts.firstOrNull { it.id == library.preset(b).layoutId }?.name } ?: return@mapNotNull null
}
val name = GameControls.name(context, id)
?: id.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.let { runCatching { SteamTouchConfig.gameName(context, it.toInt()) }.getOrNull() }
?: id.toString()
Game(id, name, layout)
}.sortedBy { it.name.lowercase() }
}
}
@@ -1,41 +0,0 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
/** Decides where the on-screen controls go and why they're hidden, from the session's state alone. */
object ControlsPresenter {
enum class Place { NONE, MAIN, BOTTOM, STEAM }
data class State(
val mode: String,
val desktop: Boolean,
val virtualPad: Boolean,
val covered: Boolean,
val controllerInUse: Boolean,
val hiddenByTap: Boolean,
val steamLayout: Boolean,
val bottomScreen: Boolean,
)
data class Plan(val place: Place, val hidden: OnScreenControls.Hidden? = null, val shortcutsOnly: Boolean = false) {
val shown get() = place != Place.NONE && hidden == null
}
fun plan(state: State): Plan = when {
state.covered || !state.virtualPad || state.mode == SessionPrefs.OSC_NEVER -> Plan(Place.NONE)
state.mode == SessionPrefs.OSC_AUTO && state.desktop -> Plan(Place.NONE)
else -> Plan(
when {
state.bottomScreen -> Place.BOTTOM
state.steamLayout && state.mode != SessionPrefs.OSC_STEAM_QAM -> Place.STEAM
else -> Place.MAIN
},
when {
state.hiddenByTap -> OnScreenControls.Hidden.BY_TAP
state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse -> OnScreenControls.Hidden.BY_CONTROLLER
else -> null
},
shortcutsOnly = state.mode == SessionPrefs.OSC_STEAM_QAM,
)
}
}
@@ -1,46 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
/** Which on-screen layout each game uses. Games without a choice use the default profile's main-screen layout. */
object GameControls {
const val STEAM = "steam"
private const val MADE_FOR = "layout-for."
private fun prefs(context: Context) = context.getSharedPreferences("game-controls", Context.MODE_PRIVATE)
/** The main-screen bindings preset saved for [game], whose layout is the one drawn. */
fun bindings(context: Context, game: Long?): String? = game?.let { prefs(context).getString("$it.bindings", null) }
fun steamLayout(context: Context, game: Long?): Boolean {
val p = prefs(context)
return if (game != null && p.contains("$game.steam")) p.getBoolean("$game.steam", false) else SessionPrefs.steamTouchLayout(context)
}
fun choose(context: Context, game: Long, bindings: String?, steam: Boolean, name: String? = null) {
prefs(context).edit().apply { if (bindings == null) remove("$game.bindings") else putString("$game.bindings", bindings) }
.apply { if (!name.isNullOrBlank()) putString("$game.name", name) }
.putBoolean("$game.steam", steam).apply()
}
/** Games with their own choice, in the order of their ids. */
fun games(context: Context): List<Long> = prefs(context).all.keys
.filter { it.endsWith(".steam") || it.endsWith(".bindings") }
.mapNotNull { it.substringBeforeLast('.').toLongOrNull() }.distinct().sorted()
/** Layouts made for one game, by layout id. */
fun madeFor(context: Context): Map<String, Long> = prefs(context).all.mapNotNull { (key, value) ->
if (key.startsWith(MADE_FOR) && value is Long) key.removePrefix(MADE_FOR) to value else null
}.toMap()
fun markMadeFor(context: Context, layout: String, game: Long) { prefs(context).edit().putLong(MADE_FOR + layout, game).apply() }
fun forgetLayout(context: Context, layout: String) { prefs(context).edit().remove(MADE_FOR + layout).apply() }
fun name(context: Context, game: Long): String? = prefs(context).getString("$game.name", null)
fun clear(context: Context, game: Long) {
prefs(context).edit().remove("$game.bindings").remove("$game.steam").apply()
}
}
@@ -9,7 +9,6 @@ object GamepadGeometry {
VIEW, STEAM, QAM, MENU,
PANELS,
L4, L5, R5, R4,
LEFT_TOUCH, RIGHT_TOUCH,
}
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
@@ -27,11 +26,10 @@ object GamepadGeometry {
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false, grips: Boolean = false, upright: Boolean = false,
trackpads: Boolean = false): Map<Slot, Box> {
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> {
if (w <= 0f || h <= 0f) return emptyMap()
if (upright || portraitDock && h >= w * 0.6f && w >= 300 * density && h >= 300 * density) {
return portraitLayout(w, h, density, grips, trackpads)
if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) {
return portraitLayout(w, h, density)
}
val pad = 8 * density
val buttonH = 40 * density
@@ -72,7 +70,6 @@ object GamepadGeometry {
else -> 1
}
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
if (grips) gripsBetween(boxes, w, gap - 2 * gutter, boxes.values.maxOf { if (it.cx in (w - gap) / 2f..(w + gap) / 2f) it.bottom else 0f } + gutter, h - pad, density)
} else {
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
val main = side * 0.62f
@@ -88,75 +85,45 @@ object GamepadGeometry {
val gap = w - 2 * (side * 0.40f + main / 2f)
val columns = if (gap >= 2 * gridButton) 2 else 1
val rows = (middle.size + columns - 1) / columns
val gridTop = h - pad - rows * buttonH - (rows - 1) * 10 * density
middleGrid(columns, gap - 2 * gutter, gridTop)
if (grips) gripsBetween(boxes, w, w - 2 * (side * 0.74f + second / 2f) - 2 * gutter, shoulderY + buttonH / 2f + gutter, gridTop - gutter, density)
middleGrid(columns, gap - 2 * gutter, h - pad - rows * buttonH - (rows - 1) * 10 * density)
val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter)
if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
}
return boxes
}
/** The back grips in the gap between a landscape panel's two clusters: one row of four, or two rows of two. */
private fun gripsBetween(boxes: MutableMap<Slot, Box>, w: Float, span: Float, top: Float, bottom: Float, density: Float) {
val gap = 8 * density
val minimum = 44 * density
val rows = if ((span - 3 * gap) / 4f >= minimum) 1 else if ((span - gap) / 2f >= minimum) 2 else return
val perRow = 4 / rows
val cellW = ((span - (perRow - 1) * gap) / perRow).coerceAtMost(96 * density)
val cellH = ((bottom - top - (rows - 1) * gap) / rows).coerceAtMost(64 * density)
if (cellH < minimum) return
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
val col = i % perRow; val row = i / perRow
boxes[slot] = Box(w / 2f + (col - (perRow - 1) / 2f) * (cellW + gap), bottom - (rows - 1 - row) * (cellH + gap) - cellH / 2f, cellW, cellH)
}
}
/**
* The panel under a portrait game: shoulders with View and Menu across the top, the back grips under them when the kit has
* them, then the d-pad and face buttons and, along the bottom edge, the sticks or trackpads, each as large as the panel allows.
*/
private fun portraitLayout(w: Float, h: Float, density: Float, grips: Boolean, trackpads: Boolean): Map<Slot, Box> {
private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> {
val pad = 8 * density
val gap = 8 * density
val buttonH = 44 * density
val boxes = LinkedHashMap<Slot, Box>()
val topGap = 4 * density
val topW = (w - 2 * pad - 5 * topGap) / 6f
val top = listOf(Slot.LEFT_OUTER_SHOULDER, Slot.LEFT_INNER_SHOULDER, Slot.VIEW, Slot.MENU, Slot.RIGHT_INNER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER)
for ((i, slot) in top.withIndex()) boxes[slot] = Box(pad + topW / 2f + i * (topW + topGap), pad + buttonH / 2f, topW, buttonH)
var areaTop = pad + buttonH + gap
if (grips) {
val gripW = (w - 2 * pad - 3 * gap) / 4f
val gripH = min(56 * density, (h - areaTop) * 0.12f).coerceAtLeast(buttonH)
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex())
boxes[slot] = Box(pad + gripW / 2f + i * (gripW + gap), areaTop + gripH / 2f, gripW, gripH)
areaTop += gripH + gap
}
val area = h - pad - areaTop - gap
if (trackpads) {
val second = min(w * 0.42f, area * 0.5f)
val rowH = area - second
val col = (w - 2 * pad - 3 * gap) / 4f
val stick = min(col, rowH)
val rowY = h - pad - rowH / 2f
val secondY = areaTop + second / 2f
boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second)
boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second)
boxes[Slot.LEFT_TOUCH] = Box(pad + col / 2f, rowY, col, rowH)
boxes[Slot.LEFT_MAIN] = Box(pad + col * 1.5f + gap, rowY, stick, stick)
boxes[Slot.RIGHT_MAIN] = Box(w - pad - col * 1.5f - gap, rowY, stick, stick)
boxes[Slot.RIGHT_TOUCH] = Box(w - pad - col / 2f, rowY, col, rowH)
return boxes
}
val main = min(w * 0.46f, area * 0.53f)
val second = min(w * 0.42f, area - main)
val secondY = areaTop + second / 2f
val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f))
val main = w * 0.4f * scale
val second = w * 0.3f * scale
val mainY = h - pad - main / 2f
boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second)
boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second)
boxes[Slot.LEFT_MAIN] = Box(w * 0.25f, mainY, main, main)
boxes[Slot.RIGHT_MAIN] = Box(w * 0.75f, mainY, main, main)
val secondY = mainY - main / 2f - gap - second / 2f
val shoulderY = secondY - second / 2f - gap - buttonH / 2f
val boxes = linkedMapOf(
Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main),
Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main),
Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second),
Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second),
)
val utilityW = (w - 2 * pad - 3 * gap) / 4f
for ((i, slot) in middle.withIndex()) {
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH)
}
val gripTop = pad + buttonH + gap
val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop)
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH)
}
val panelsW = min(112 * density, w * 0.22f)
val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f
boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH)
boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH)
boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH)
boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH)
return boxes
}
}
@@ -10,7 +10,11 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 16
private const val VERSION = 14
private val redesignVersions = 15..16
private const val KIT_DPAD = "kit:dpad"
private const val KEYBOARD = "builtin:keyboard"
private const val REDESIGN_BACKUP = "library-before-controller-revert"
private const val KEY = "library"
private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay"
@@ -23,17 +27,24 @@ object InputLibraries {
fun read(context: Context): InputLibrary {
val p = prefs(context)
val raw = p.getString(KEY, null)
val decoded = raw?.let(::decode)
val decoded = raw?.let { decode(it, context) }
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 in redesignVersions && raw != null) {
val encoded = encode(library)
if (encoded.length > 2_000_000) return library
if (!commitWithBackup(p, raw, REDESIGN_BACKUP, encoded)) {
android.util.Log.e("InputLibraries", "Could not save the restored input library")
return library
}
}
if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library)))
if (version < 11) library = neutralStockLayouts(library)
if (version < 10) library = restyleGamepads(context, library)
if (version < 12) library = barStockLayouts(library)
if (version < 13) library = LegacyScreenKeyMigration.pin(library)
if (version < 14) library = deckGamepadSurfaces(context, library)
if (version < 15) library = kitGamepads(context, library, version)
if (version < 16) library = ownModeSelections(library)
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) {
@@ -76,24 +87,35 @@ object InputLibraries {
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
val invalid = stored != null && decode(stored, context) == 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 backupKey = when {
invalid -> RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8))
stored != null && p.getString(KEY, null) == stored &&
JSONObject(stored).getInt("version") in redesignVersions -> REDESIGN_BACKUP
else -> null
}
if (backupKey != null) {
val encoded = encode(updated)
require(encoded.length <= 2_000_000) { "The input library is too large to save." }
val recovery = RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8))
if (!p.edit().putString(recovery, stored).putString(KEY, encoded).commit()) {
// A failed commit has already changed the in-memory preferences; put the previous library back.
p.edit().putString(KEY, stored).remove(recovery).apply()
error("Could not save the input library and its recovery copy.")
check(commitWithBackup(p, requireNotNull(stored), backupKey, encoded)) {
"Could not save the input library and its recovery copy."
}
} else write(context, updated)
return updated
}
private fun commitWithBackup(prefs: android.content.SharedPreferences, raw: String, backupKey: String, encoded: String): Boolean {
val previousBackup = prefs.getString(backupKey, null)
if (prefs.edit().putString(backupKey, raw).putString(KEY, encoded).commit()) return true
// SharedPreferences updates its in-memory values even when the disk write fails.
prefs.edit().putString(KEY, raw).putString(backupKey, previousBackup).apply()
return false
}
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." }
@@ -130,14 +152,27 @@ object InputLibraries {
return InputLibrary(profiles, layouts, bindings, selected).validate()
}
fun setAdaptiveSticks(context: Context, layoutId: String, on: Boolean): Boolean = runCatching {
update(context) { library ->
library.copy(layouts = library.layouts.map { layout ->
if (layout.id != layoutId || !layout.editable) layout
else layout.copy(elements = layout.elements.map { if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = on) else it })
})
}
}.onSuccess { ControllerPrefs.setAdaptiveSticks(context, on) }.isSuccess
fun setQuickButton(context: Context, layoutId: String, button: InputCommand, shown: Boolean): Boolean = runCatching {
update(context) { library -> library.layouts.firstOrNull { it.id == layoutId && it.editable }?.let { library.withLayout(it.withQuickButton(button, shown)) } ?: library }
}.isSuccess
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): Pair<List<InputSurfaceElement>, Float>? {
val origin = layout.origin ?: layout.id
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements to it.aspect }
if (origin == OVERLAY) {
if (origin == OVERLAY || origin.startsWith("migrated.layout.")) {
val (surfaceContext, metrics) = primaryDisplay(context)
val w = metrics.widthPixels.coerceAtLeast(1)
val h = metrics.heightPixels.coerceAtLeast(1)
return KitLayout.elements(surfaceContext, PadKit.current(context), w, h, scale = layout.scale) to w.toFloat() / h
val size = if (origin == OVERLAY) listOf(metrics.widthPixels, metrics.heightPixels)
else origin.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() to it[0].toFloat() / it[1] }
}
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect }
}
@@ -149,12 +184,29 @@ object InputLibraries {
return surfaceContext to DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) }
}
private fun restyleGamepads(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.none { it.id == OVERLAY || it.id.startsWith("migrated.layout.") }) return library
val (surfaceContext, metrics) = primaryDisplay(context)
return library.copy(layouts = library.layouts.map { layout ->
val size = when {
layout.id == OVERLAY -> listOf(metrics.widthPixels, metrics.heightPixels)
layout.id.startsWith("migrated.layout.") -> layout.id.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
else -> emptyList()
}
if (size.size != 2 || size.any { it <= 0 }) layout
else layout.copy(elements = LegacyGamepadLayout(surfaceContext, size[0], size[1]).restyle(layout.elements))
})
}
private fun upgradeOverlay(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.none { it.template == InputLayoutTemplate.OVERLAY }) return library
val (surfaceContext, metrics) = primaryDisplay(context)
val settings = ControllerPrefs.read(context)
val style = InputSurfaceStyle(opacity = settings.opacity)
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 = emptyList(), template = InputLayoutTemplate.CUSTOM, style = style)
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style,
aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f))
}
var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
val migrated = mutableMapOf<Pair<String, String>, String>()
@@ -165,8 +217,9 @@ object InputLibraries {
val id = migrated.getOrPut(key) {
val old = library.preset(part.bindings)
val newId = migrationBindingId(result, old.id, layout.id)
val clicks = if (settings.stickClick) old.clicks else old.clicks + KitLayout.clickIds.associateWith { InputAction.Disabled }
result = result.withPreset(old.copy(id = newId, layoutId = layout.id, clicks = clicks))
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)
@@ -175,6 +228,15 @@ object InputLibraries {
}
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, aspect = (size[0].toFloat() / size[1]).coerceIn(.05f, 20f)))
}
return result.validate()
}
@@ -240,90 +302,6 @@ object InputLibraries {
return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate()
}
private fun kitGamepads(context: Context, library: InputLibrary, version: Int): InputLibrary {
fun old(layout: SavedInputLayout) = (layout.origin ?: layout.id).let { it == OVERLAY || it.startsWith("migrated.layout.") }
fun follow(layout: SavedInputLayout): SavedInputLayout {
val extras = layout.elements.filterNot { KitLayout.isKit(it.id) }
return layout.copy(elements = extras, origin = if (layout.id == OVERLAY) null else OVERLAY, aspect = if (extras.isEmpty()) 0f else layout.aspect, scale = 1f)
}
val positioned = library.layouts.filter { layout ->
if (!old(layout)) return@filter false
val hasKit = layout.elements.any { KitLayout.isKit(it.id) }
if (hasKit) !stockLegacyGeometry(context, layout)
else version == 14 && layout.aspect > 0f
}
val inPlace = positioned.fold(library.copy(layouts = library.layouts.map { if (old(it) && it !in positioned) follow(it) else it })) { acc, layout ->
acc.withLayout(layout.copy(kitless = true))
}
var result = library.copy(layouts = library.layouts.map { if (old(it)) follow(it) else it })
val replacements = mutableMapOf<String, InputPart>()
for (layout in positioned) {
val id = previousLayoutId(layout.id)
val presets = library.bindings.filter { it.layoutId == layout.id }
if (result.layouts.any { it.id == id } || result.layouts.size >= 256 || result.bindings.size + presets.size > 512) {
result = result.copy(layouts = result.layouts.map { if (it.id == layout.id) layout else it }).withLayout(layout.copy(kitless = true))
continue
}
val name = "${layout.name} (old layout)".take(80)
val saved = layout.copy(id = id, name = name, origin = null, kitless = true)
val savedPresets = presets.map { preset ->
val binding = previousBindingsId(preset.id, id)
replacements[preset.id] = InputPart(binding, id)
preset.copy(id = binding, name = name, layoutId = id,
elements = preset.elements.filterKeys { saved.element(it) != null },
clicks = preset.clicks.filterKeys { saved.element(it)?.hasClick == true })
}
result = result.copy(bindings = result.bindings + savedPresets).withLayout(saved)
}
val migrated = result.copy(
profiles = result.profiles.map { profile ->
profile.copy(parts = profile.parts.mapValues { (_, part) -> replacements[part.bindings] ?: part })
},
selections = result.selections.mapValues { (_, selection) ->
selection.copy(parts = selection.parts.mapValues { (_, bindings) -> replacements[bindings]?.bindings ?: bindings })
},
)
val expanded = runCatching { migrated.validate() }.getOrNull()
return if (expanded != null && encode(expanded).length <= 2_000_000) expanded else inPlace.validate()
}
internal fun previousLayoutId(layout: String) =
"kept." + UUID.nameUUIDFromBytes(layout.toByteArray(Charsets.UTF_8))
internal fun previousBindingsId(binding: String, previousLayout: String) =
"kept." + UUID.nameUUIDFromBytes((binding + "\u0000" + previousLayout).toByteArray(Charsets.UTF_8))
private fun stockLegacyGeometry(context: Context, layout: SavedInputLayout): Boolean {
if (layout.scale != 1f) return false
val (display, metrics) = primaryDisplay(context)
val width = metrics.widthPixels.coerceAtLeast(1)
val height = metrics.heightPixels.coerceAtLeast(1)
val named = (layout.origin ?: layout.id).removePrefix("migrated.layout.").split("x")
.mapNotNull(String::toIntOrNull).takeIf { it.size == 2 && it.all { side -> side > 0 } }
?.let { it[0] to it[1] }
val sizes = listOfNotNull(named, width to height, height to width).distinct()
val positions = layout.elements.filter { KitLayout.isKit(it.id) }.associateBy { it.id }
return sizes.any { (w, h) ->
if (layout.aspect != (w.toFloat() / h).coerceIn(.05f, 20f)) return@any false
val stock = LegacyLayoutGeometry(display, w, h)
listOf(stock.elements(), stock.elements(previousStickGeometry = true)).any { elements ->
elements.size == positions.size && elements.all { element -> positions[element.id] == element }
}
}
}
internal fun primaryOf(library: InputLibrary, desktop: Boolean) =
library.profiles.firstOrNull { it.id == library.activeId(desktop) }?.parts?.get(InputRole.PRIMARY)?.bindings
/** Choosing a layout used to take the first actions saved for it, which could be the other mode's mouse and keys. */
private fun ownModeSelections(library: InputLibrary): InputLibrary = library.copy(selections = library.selections.mapValues { (mode, selection) ->
val desktop = mode == InputProfile.DESKTOP
val chosen = selection.parts[InputRole.PRIMARY]
if (chosen != null && chosen == primaryOf(library, !desktop) && chosen != primaryOf(library, desktop))
selection.copy(parts = selection.parts - InputRole.PRIMARY)
else selection
})
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)
@@ -356,7 +334,7 @@ object InputLibraries {
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL).put("kitless", layout.kitless))
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
}
val bindings = JSONArray()
for (b in library.bindings) {
@@ -385,22 +363,32 @@ object InputLibraries {
.put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).toString()
}
internal fun decode(raw: String): InputLibrary? = runCatching {
internal fun decode(raw: String, context: Context? = null): InputLibrary? = runCatching {
require(raw.length <= 2_000_000)
val doc = JSONObject(raw); require(doc.getInt("version") in 2..VERSION)
val doc = JSONObject(raw)
val version = doc.getInt("version")
val restore = context != null && version in redesignVersions
require(version in 2..VERSION || restore)
val generated = mutableSetOf<String>()
val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
val elements = layout.getJSONArray("elements").objects(64).map { e ->
val stored = 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), e.optBoolean("alwaysShown", false))
}
SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")),
val id = layout.getString("id")
val origin = layout.optionalString("origin")
val followsGamepad = restore && !layout.optBoolean("kitless") &&
(id == OVERLAY || origin == OVERLAY) &&
stored.none { it.id.startsWith("legacy:") || it.id == KIT_DPAD || it.id == KEYBOARD }
if (followsGamepad) generated += id
SavedInputLayout(id, layout.getString("name"), if (restore) stored.map { it.bounded() } else stored, InputLayoutTemplate.valueOf(layout.getString("template")),
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), layout.optionalString("origin"),
layout.optDouble("scale", 1.0).toFloat(), layout.optBoolean("kitless", false))
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin,
layout.optDouble("scale", 1.0).toFloat())
}
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
@@ -427,9 +415,41 @@ object InputLibraries {
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()
val library = InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections)
(if (restore) restoreGamepads(requireNotNull(context), library, generated) else library).validate()
}.getOrNull()
private fun restoreGamepads(context: Context, library: InputLibrary, generated: Set<String>): InputLibrary {
val (display, metrics) = primaryDisplay(context)
val height = metrics.heightPixels.coerceAtLeast(1)
val layouts = library.layouts.map { layout ->
if (layout.id !in generated) return@map layout
val width = if (layout.aspect > 0f) (layout.aspect * height).toInt().coerceAtLeast(1)
else metrics.widthPixels.coerceAtLeast(1)
val gamepad = LegacyGamepadLayout(display, width, height, scale = layout.scale).elements()
layout.copy(elements = gamepad.take(64 - layout.elements.size) + layout.elements,
aspect = (width.toFloat() / height).coerceIn(.05f, 20f))
}
val byId = layouts.associateBy { it.id }
val bindings = library.bindings.map { preset ->
val layout = byId[preset.layoutId] ?: return@map preset
val elements = layout.elements.associateBy { it.id }
val defaults = layout.elements.mapNotNull { element ->
val action = when (element.id) {
KEYBOARD -> InputAction.Command(InputCommand.KEYBOARD)
KIT_DPAD -> InputAction.Native()
else -> return@mapNotNull null
}
element.id to action
}.toMap()
preset.copy(
elements = defaults + preset.elements.filter { (id, action) -> elements[id]?.let { action.validFor(it) } == true },
clicks = preset.clicks.filter { (id, action) -> elements[id]?.hasClick == true && action.validForClick() },
)
}
return library.copy(layouts = layouts, bindings = bindings)
}
private fun JSONArray.objects(limit: Int): List<JSONObject> {
require(length() <= limit)
return (0 until length()).map { getJSONObject(it) }
@@ -22,8 +22,6 @@ data class SavedInputLayout(
val aspect: Float = 0f,
val origin: String? = null,
val scale: Float = 1f,
/** The player removed every kit control from this gamepad, so it must not follow the virtual controller again. */
val kitless: Boolean = false,
) {
val editable get() = template == InputLayoutTemplate.CUSTOM
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
@@ -51,7 +49,7 @@ data class SavedInputBindings(
fun action(element: InputSurfaceElement) = elements[element.id]
?: if (element.id == "legacy:${element.control.id}") controls[element.control] ?: InputAction.Native()
else defaultElementAction(element.id)
else InputAction.Disabled
fun clickAction(element: InputSurfaceElement) = clicks[element.id]
?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() }
@@ -138,8 +136,8 @@ data class InputLibrary(
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.element(id)?.let { action.validFor(it) } == true },
clicks = preset.clicks.filter { (id, action) -> value.element(id)?.hasClick == true && action.validForClick() }) })
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)
@@ -273,8 +271,8 @@ data class InputLibrary(
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?.element(id)?.let { action.validFor(it) } == true })
require(preset.clicks.all { (id, action) -> layout?.element(id)?.hasClick == true && action.validForClick() })
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) })
}
@@ -314,12 +312,3 @@ internal fun InputAction.validFor(element: InputSurfaceElement): Boolean = when
element.kind == InputElementKind.TRIGGER -> target == InputControl.LT || target == InputControl.RT
else -> target.dimensions == 1 && target != InputControl.LT && target != InputControl.RT
}
/**
* A saved element, or the kit control that [id] names: in a layout made from the built-in gamepad every kit control keeps its
* binding while it's removed, so Reset or Restore brings it back with its action.
*/
internal fun SavedInputLayout.element(id: String): InputSurfaceElement? =
elements.firstOrNull { it.id == id } ?: KitLayout.element(id)?.takeIf {
this.id == InputLibraries.OVERLAY || origin == InputLibraries.OVERLAY || KitLayout.bindsTo(id, elements)
}
@@ -48,7 +48,7 @@ data class InputProfile(
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 defaultElementAction(id)
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) }
@@ -115,12 +115,3 @@ internal fun InputAction.validFor(control: InputControl): Boolean = when (this)
is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f
else -> true
}
/** What an on-screen element with no saved action does: kit controls press their own button, everything else is unassigned. */
internal fun defaultElementAction(id: String): InputAction = when (id) {
KitLayout.DPAD_ID -> InputAction.Native()
KitLayout.KEYBOARD_ID -> InputAction.Command(InputCommand.KEYBOARD)
OnScreenLayout.STEAM_SHORTCUT_ID -> InputAction.Command(InputCommand.STEAM)
OnScreenLayout.QAM_SHORTCUT_ID -> InputAction.Command(InputCommand.QUICK_ACCESS)
else -> InputAction.Disabled
}
@@ -38,13 +38,8 @@ data class InputSurfaceElement(
) {
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
fun bounded() = copy(x = x.coerceIn(0f, 1f - MIN_SIZE), y = y.coerceIn(0f, 1f - MIN_SIZE),
width = width.coerceIn(MIN_SIZE, (1f - x.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)),
height = height.coerceIn(MIN_SIZE, (1f - y.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)))
companion object {
const val MIN_SIZE = .01f
}
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)).coerceAtLeast(0.03f)), height = height.coerceIn(0.03f, (1f - y.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)))
}
internal val QUICK_BUTTONS = listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.KEYBOARD)
@@ -56,31 +51,15 @@ val InputSurfaceElement.quickButton: InputCommand? get() = when {
else -> null
}
/** Controls whose boxes touch, grown by 15%, scale around one shared anchor so a cluster such as the face buttons keeps its shape. */
internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> {
internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> = map { e ->
fun anchor(centre: Float) = when { centre < 1f / 3f -> 0f; centre > 2f / 3f -> 1f; else -> .5f }
val group = IntArray(size) { it }
fun root(i: Int): Int = if (group[i] == i) i else root(group[i]).also { group[i] = it }
for (i in indices) for (j in i + 1 until size) {
val a = this[i]; val b = this[j]
val near = kotlin.math.abs(a.x + a.width / 2 - b.x - b.width / 2) < (a.width + b.width) / 2 * 1.15f &&
kotlin.math.abs(a.y + a.height / 2 - b.y - b.height / 2) < (a.height + b.height) / 2 * 1.15f
if (near) group[root(i)] = root(j)
}
val anchors = indices.groupBy(::root).mapValues { (_, members) ->
anchor(members.map { this[it].x + this[it].width / 2 }.average().toFloat()) to anchor(members.map { this[it].y + this[it].height / 2 }.average().toFloat())
}
return mapIndexed { i, e -> e.scaledAround(factor, anchors.getValue(root(i))) }
}
private fun InputSurfaceElement.scaledAround(factor: Float, anchor: Pair<Float, Float>): InputSurfaceElement {
val e = this
val w = (e.width * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val h = (e.height * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val w = (e.width * factor).coerceIn(.03f, 1f)
val h = (e.height * factor).coerceIn(.03f, 1f)
val cx = e.x + e.width / 2
val cy = e.y + e.height / 2
val (ax, ay) = anchor
return e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h),
val ax = anchor(cx)
val ay = anchor(cy)
e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h),
width = w, height = h).bounded()
}
@@ -3,10 +3,6 @@ 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)
/** The kit's D-pad keeps each direction's own binding, as the separate direction buttons it replaced did. */
private val arms = if (element.id == KitLayout.DPAD_ID && router != null)
listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { router.channel(role, it, element = KitLayout.element("legacy:${it.id}")) }
else emptyList()
private val deck = DeckControls.source(role, routed = true)
private val clickDeck = DeckControls.source(role, routed = true)
private val clickOwner = Any()
@@ -59,15 +55,6 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
fingerDown = down
if (latched) 1f else 0f
} else value
if (arms.isNotEmpty() && route?.action is InputAction.Native) {
val ready = route.update(x, y, touching) != null
val values = listOf(y < -.5f, x > .5f, y > .5f, x < -.5f).map { if (it && ready) 1f else 0f }
val toPad = arms.mapIndexed { i, arm -> arm.update(values[i])?.takeIf { it.isPad }?.let { it to values[i] } }.filterNotNull()
if (toPad.isNotEmpty() || nativePad) writePad(this, null) { state -> state.clear(); for ((t, v) in toPad) state.add(t, v) }
nativePad = toPad.isNotEmpty()
InputTiming.end(timing)
return
}
val target = if (router == null) element.control else route?.update(x, y, touching)
val toPad = target?.isPad == true
val toDeck = target != null && !target.isPad
@@ -88,7 +75,6 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
fun cancel() {
if (closed) return
route?.takeIf { it.action is InputAction.Command }?.release()
arms.filter { it.action is InputAction.Command }.forEach { it.release() }
update(0f)
}
@@ -126,13 +112,13 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
closed = true
router?.removeSnapshot(snapshot)
releaseNative(); resetLatch()
route?.close(); arms.forEach { it.close() }; clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close()
route?.close(); clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close()
}
fun release() {
if (closed) return
releaseNative(); resetLatch()
route?.release(); arms.forEach { it.release() }; clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release()
route?.release(); clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release()
}
}
@@ -1,297 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import android.graphics.RectF
import kotlin.math.max
import kotlin.math.min
/**
* Places a virtual controller's default on-screen controls. Each kit is drawn on a 1600 × 900 reference screen; controls keep
* their distance from the nearest edge, so wider screens spread them apart instead of stretching them. Clusters such as the face
* buttons are placed by their centre so they move as one, and the row along the bottom-left edge always starts after DroidDeck's
* corner button.
*/
object KitLayout {
const val DPAD_ID = "kit:dpad"
const val KEYBOARD_ID = "builtin:keyboard"
/** Whether [id] names one of a kit's own controls rather than a key or control the player added. */
fun isKit(id: String) = id.startsWith("legacy:") || id == DPAD_ID || id == KEYBOARD_ID
internal fun visibleOnOverlay(control: InputControl, rearButtons: Boolean, trackpads: Boolean): Boolean = when (control) {
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> rearButtons
InputControl.LEFT_PAD, InputControl.RIGHT_PAD -> trackpads
else -> true
}
/** The control a kit id stands for in a layout that keeps no kit positions, so bindings saved for it stay valid. */
fun element(id: String): InputSurfaceElement? = when {
id == DPAD_ID -> InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, id, InputElementKind.DPAD)
id == KEYBOARD_ID -> InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, id)
id.startsWith("legacy:") -> InputControl.entries.firstOrNull { "legacy:${it.id}" == id }
?.let { InputSurfaceElement(it, 0f, 0f, .1f, .1f, id, InputElementKind.from(it)) }
else -> null
}
/** The direction buttons the kit's D-pad stands in for; their saved overrides stay with the D-pad. */
val dpadDirectionIds = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { "legacy:${it.id}" }
/** Whether a binding for [id] belongs to a layout made of [elements]. */
fun bindsTo(id: String, elements: List<InputSurfaceElement>) =
elements.any { it.id == id } || id in dpadDirectionIds && elements.any { it.id == DPAD_ID }
/** Every kit control that has a click, across all virtual controllers. */
val clickIds = listOf(InputControl.LS, InputControl.RS, InputControl.LEFT_PAD, InputControl.RIGHT_PAD).map { "legacy:${it.id}" }
private const val REF_W = 1600f
private const val REF_H = 900f
/** The widest pair of side controls on any kit: a larger size never pushes the two halves, or the rows, into each other. */
private const val MIN_SPAN = 1200f
private const val MAX_HEIGHT_MM = 80f
/** The smallest half-size of any kit control in reference units. */
private const val SMALLEST_HALF = 26f
private const val CORNER_DP = 52f
private const val ROW_DP = 60f
private const val BUTTON_DP = 44f
private const val GAP_DP = 8f
private class Spec(val control: InputControl, val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw, val id: String = "legacy:${control.id}",
val kind: InputElementKind = InputElementKind.from(control), val shape: InputButtonShape = InputButtonShape.CIRCLE, val icon: Int = 0, val name: String = control.label,
val ax: Float = cx, val ay: Float = cy)
private fun shoulders() = listOf(
Spec(InputControl.LT, 140f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.LB, 140f, 148f, 88f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.RT, 1460f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.RB, 1460f, 148f, 88f, 30f, shape = InputButtonShape.PILL))
private fun face(cx: Float, cy: Float, r: Float, off: Float) = listOf(
Spec(InputControl.Y, cx, cy - off, r, ax = cx, ay = cy), Spec(InputControl.X, cx - off, cy, r, ax = cx, ay = cy),
Spec(InputControl.B, cx + off, cy, r, ax = cx, ay = cy), Spec(InputControl.A, cx, cy + off, r, ax = cx, ay = cy))
private fun dpad(cx: Float, cy: Float, half: Float) =
Spec(InputControl.LS, cx, cy, half, id = DPAD_ID, kind = InputElementKind.DPAD, shape = InputButtonShape.ROUNDED, name = "D-pad")
private fun keyboard(cx: Float) = Spec(InputControl.A, cx, 848f, 46f, id = KEYBOARD_ID, icon = InputButtonIcons.KEYBOARD, name = "Keyboard")
private fun specs(kit: PadKit): List<Spec> = when {
kit.steam -> shoulders() + listOf(
Spec(InputControl.L4, 30f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.L5, 30f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.R4, 1570f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.R5, 1570f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED),
dpad(220f, 345f, 150f)) + face(1375f, 345f, 58f, 96f) + listOf(
Spec(InputControl.LS, 290f, 640f, 96f), Spec(InputControl.RS, 1310f, 640f, 96f),
Spec(InputControl.LEFT_PAD, 470f, 360f, 88f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1130f, 360f, 88f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.SELECT, 660f, 850f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 850f, 46f, 26f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL),
keyboard(136f))
kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 58f, 96f) + listOf(
Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f),
Spec(InputControl.L3, 430f, 590f, 42f, ax = 565f, ay = 690f), Spec(InputControl.R3, 1170f, 590f, 42f, ax = 1035f, ay = 690f),
Spec(InputControl.SELECT, 640f, 850f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 850f, 50f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 800f, 850f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 675f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf(
Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f, ax = 235f, ay = 400f), Spec(InputControl.R3, 1290f, 790f, 42f, ax = 1130f, ay = 690f),
Spec(InputControl.SELECT, 690f, 850f, 38f), Spec(InputControl.GUIDE, 800f, 850f, 46f), Spec(InputControl.START, 910f, 850f, 38f),
Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
}
/** The default controls for [kit] on a [width] × [height] screen. */
fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f,
cutouts: List<Rect> = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true,
addedControls: List<InputSurfaceElement> = emptyList()): List<InputSurfaceElement> {
if (width <= 0 || height <= 0) return emptyList()
// Insets stay as reported unless what's left is too small to keep every control above the minimum element size.
val smallestUnit = InputSurfaceElement.MIN_SIZE * max(width, height) / (2 * SMALLEST_HALF)
fun fit(a: Int, b: Int, side: Int, reference: Float): Pair<Int, Int> {
val first = a.coerceAtLeast(0); val second = b.coerceAtLeast(0)
val room = (side - (smallestUnit * reference).toInt() - 1).coerceAtLeast(0)
return if (first + second <= room) first to second else (first.toLong() * room / (first + second)).toInt() to (second.toLong() * room / (first + second)).toInt()
}
val (left, right) = fit(inset.left, inset.right, width, MIN_SPAN)
val (top, bottom) = fit(inset.top, inset.bottom, height, REF_H)
val safe = Rect(left, top, right, bottom)
if (height > width) return portrait(context, kit, width, height, safe, scale)
.filter { visibleOnOverlay(it.control, rearButtons, trackpads) }
val controls = specs(kit).filter { visibleOnOverlay(it.control, rearButtons, trackpads) }
val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left }
val rightCutouts = cutouts.filter { inset.right > 0 && it.left >= width - inset.right }
if ((leftCutouts.isNotEmpty() || rightCutouts.isNotEmpty()) &&
(left == 0 || leftCutouts.isNotEmpty()) && (right == 0 || rightCutouts.isNotEmpty())) {
val corner = cornerInset(safe, cutouts, height, context.resources.displayMetrics.density)
val fullWidth = landscape(context, kit, width, height, Rect(0, top, 0, bottom), scale, corner, controls)
avoidSideCutouts(fullWidth, leftCutouts, rightCutouts, width, height, addedControls)?.let { return it }
}
return landscape(context, kit, width, height, safe, scale, left, controls)
}
internal fun cornerInset(inset: Rect, cutouts: List<Rect>, height: Int, density: Float): Int {
val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left }
val floor = height - inset.bottom
return if (height <= 0 || leftCutouts.isEmpty() ||
leftCutouts.any { it.top < floor && it.bottom > floor - CORNER_DP * density && it.left < CORNER_DP * density })
inset.left else 0
}
private fun landscape(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float,
cornerInset: Int, controls: List<Spec>): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val unit = (min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale).coerceAtMost(min((w - safe.left - safe.right).coerceAtLeast(1f) / MIN_SPAN, (h - safe.top - safe.bottom).coerceAtLeast(1f) / REF_H))
fun x(ref: Float) = when {
ref < REF_W / 3f -> safe.left + ref * unit
ref > REF_W * 2f / 3f -> w - safe.right - (REF_W - ref) * unit
else -> (w / 2f + (ref - REF_W / 2f) * unit).between(safe.left + ref * unit, w - safe.right - (REF_W - ref) * unit)
}
fun y(ref: Float) = when {
ref < REF_H / 3f -> safe.top + ref * unit
ref > REF_H * 2f / 3f -> h - safe.bottom - (REF_H - ref) * unit
else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit)
}
val density = context.resources.displayMetrics.density
var edge = cornerInset + CORNER_DP * density
val row = controls.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s ->
val hw = s.hw * unit
max(x(s.cx), edge + hw).also { edge = it + hw + GAP_DP * density }
}
return controls.map { s ->
val cx = if (s.cy > REF_H * .88f && s.cx > REF_W / 3f && s.cx < REF_W * 2f / 3f) (w + safe.left - safe.right) / 2f + (s.cx - REF_W / 2f) * unit
else row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit)
val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit
InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, if (s.name == s.control.label) kit.name(s.control) else s.name,
floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded()
}
}
private fun avoidSideCutouts(elements: List<InputSurfaceElement>, leftCutouts: List<Rect>, rightCutouts: List<Rect>,
width: Int, height: Int, addedControls: List<InputSurfaceElement>): List<InputSurfaceElement>? {
fun bounds(e: InputSurfaceElement) = RectF(e.x * width, e.y * height, (e.x + e.width) * width, (e.y + e.height) * height)
val boxes = elements.map(::bounds)
val addedBoxes = addedControls.map(::bounds)
// Move a face-button cross or a stick and its click button together.
val groups = elements.indices.groupBy { index ->
val element = elements[index]
when (element.control) {
InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> if (element.id == KEYBOARD_ID) element.id else "face"
InputControl.L3 -> "legacy:ls"
InputControl.R3 -> "legacy:rs"
else -> element.id
}
}.values
val shifts = FloatArray(elements.size)
val left = leftCutouts.map(::RectF)
val right = rightCutouts.map(::RectF)
val obstacles = left + right
for (group in groups) {
val leftEdge = left.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.maxOfOrNull { it.right }
val rightEdge = right.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.minOfOrNull { it.left }
val shift = when {
leftEdge != null && rightEdge != null -> return null
leftEdge != null -> leftEdge - group.minOf { boxes[it].left } + 1f
rightEdge != null -> rightEdge - group.maxOf { boxes[it].right } - 1f
else -> continue
}
for (index in group) shifts[index] = shift
}
val moved = boxes.mapIndexed { index, box -> RectF(box).apply { offset(shifts[index], 0f) } }
for (i in moved.indices) {
if (moved[i].left < 0f || moved[i].right > width || obstacles.any { RectF.intersects(moved[i], it) }) return null
if (shifts[i] != 0f && addedBoxes.any { RectF.intersects(moved[i], it) }) return null
for (j in 0 until i) {
if (shifts[i] != shifts[j] && RectF.intersects(moved[i], moved[j]) && !RectF.intersects(boxes[i], boxes[j])) return null
}
}
return elements.mapIndexed { index, e -> e.copy(x = e.x + shifts[index] / width).bounded() }
}
/**
* A portrait surface gets the same pad as the panel under the game, in the lower part of the screen, with the keyboard,
* Steam, Quick Access, Start, Select and stick-click buttons in a row along the bottom edge.
*/
private fun portrait(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val density = context.resources.displayMetrics.density
val row = ROW_DP * density
val inner = (w - safe.left - safe.right).coerceAtLeast(1f)
val area = (min(h * .6f, inner * 1.15f) * scale).coerceAtMost(h - safe.top - safe.bottom - row).coerceAtLeast(1f)
val top = h - safe.bottom - row - area
val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true)
.filterNot { it.control == InputControl.SELECT || it.control == InputControl.START }.map { e ->
e.copy(x = (safe.left + e.x * inner) / w, y = (top + e.y * area) / h, width = e.width * inner / w, height = e.height * area / h,
floating = e.kind == InputElementKind.STICK)
}
val specs = specs(kit)
fun spec(control: InputControl, id: String = "legacy:${control.id}") = specs.firstOrNull { it.control == control && it.id == id }
val gap = GAP_DP * density
val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3), spec(InputControl.SELECT))
val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3), spec(InputControl.START))
val start = safe.left + CORNER_DP * density
val span = (w - safe.right - gap - start - gap * (leftRow.size + rightRow.size - 1)).coerceAtLeast(1f)
val size = min(BUTTON_DP * density, span / (leftRow + rightRow).sumOf { (it.hw / it.hh).toDouble() }.toFloat())
val cy = h - safe.bottom - row / 2f
val placed = mutableListOf<InputSurfaceElement>()
fun put(s: Spec, cx: Float) {
val bw = size * s.hw / s.hh
placed += InputSurfaceElement(s.control, (cx - bw / 2) / w, (cy - size / 2) / h, bw / w, size / h, s.id, s.kind,
if (s.name == s.control.label) kit.name(s.control) else s.name, buttonShape = s.shape, icon = s.icon)
}
var left = start
for (s in leftRow) {
val bw = size * s.hw / s.hh
put(s, left + bw / 2); left += bw + gap
}
var right = w - safe.right - gap
for (s in rightRow) {
val bw = size * s.hw / s.hh
put(s, right - bw / 2); right -= bw + gap
}
return pad + placed
}
/** Controls for the panel below the game, in [GamepadGeometry]'s slots. */
fun dock(context: Context, kit: PadKit, width: Int, height: Int, portrait: Boolean, left: InputControl, right: InputControl,
upright: Boolean = false): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val boxes = GamepadGeometry.layout(w, h, context.resources.displayMetrics.density, portrait, grips = kit.steam, upright = upright,
trackpads = kit.steam)
val placed = mutableListOf<InputSurfaceElement>()
fun put(control: InputControl, box: GamepadGeometry.Box?, shape: InputButtonShape, id: String = "legacy:${control.id}",
kind: InputElementKind = InputElementKind.from(control), name: String = kit.name(control)) {
val b = box ?: return
placed += InputSurfaceElement(control, b.left / w, b.top / h, b.width / w, b.height / h, id, kind, name, floating = false, buttonShape = shape).bounded()
}
fun square(box: GamepadGeometry.Box?) = box?.let { val side = min(it.width, it.height); GamepadGeometry.Box(it.cx, it.cy, side, side) }
val four = GamepadGeometry.Slot.LEFT_TOUCH in boxes
val leftMain = if (four || !kit.steam && left == InputControl.LEFT_PAD) InputControl.LS else left
val rightMain = if (four || !kit.steam && right == InputControl.RIGHT_PAD) InputControl.RS else right
if (four) {
put(InputControl.LEFT_PAD, boxes[GamepadGeometry.Slot.LEFT_TOUCH], InputButtonShape.ROUNDED)
put(InputControl.RIGHT_PAD, boxes[GamepadGeometry.Slot.RIGHT_TOUCH], InputButtonShape.ROUNDED)
}
put(leftMain, square(boxes[GamepadGeometry.Slot.LEFT_MAIN]), InputButtonShape.CIRCLE)
put(InputControl.LS, square(boxes[GamepadGeometry.Slot.LEFT_SECOND]), InputButtonShape.ROUNDED, DPAD_ID, InputElementKind.DPAD, "D-pad")
put(rightMain, square(boxes[GamepadGeometry.Slot.RIGHT_MAIN]), InputButtonShape.CIRCLE)
square(boxes[GamepadGeometry.Slot.RIGHT_SECOND])?.let { b ->
val r = b.width * .17f; val off = b.width * .3f
listOf(InputControl.Y to (0f to -1f), InputControl.B to (1f to 0f), InputControl.A to (0f to 1f), InputControl.X to (-1f to 0f)).forEach { (c, d) ->
put(c, GamepadGeometry.Box(b.cx + d.first * off, b.cy + d.second * off, 2 * r, 2 * r), InputButtonShape.CIRCLE)
}
}
put(InputControl.LT, boxes[GamepadGeometry.Slot.LEFT_OUTER_SHOULDER], InputButtonShape.PILL)
put(InputControl.LB, boxes[GamepadGeometry.Slot.LEFT_INNER_SHOULDER], InputButtonShape.PILL)
put(InputControl.RB, boxes[GamepadGeometry.Slot.RIGHT_INNER_SHOULDER], InputButtonShape.PILL)
put(InputControl.RT, boxes[GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER], InputButtonShape.PILL)
put(InputControl.SELECT, boxes[GamepadGeometry.Slot.VIEW], InputButtonShape.PILL)
put(InputControl.START, boxes[GamepadGeometry.Slot.MENU], InputButtonShape.PILL)
if (kit.steam) listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4).forEach { (c, slot) -> put(c, boxes[slot], InputButtonShape.ROUNDED) }
return placed
}
private fun cap(context: Context, shortSide: Int): Float {
val metrics = context.resources.displayMetrics
val nominal = metrics.densityDpi.toFloat()
val dpi = metrics.ydpi.takeIf { it > nominal * .6f && it < nominal * 1.6f } ?: nominal
val mm = shortSide / dpi * 25.4f
return min(1f, MAX_HEIGHT_MM / max(mm, 1f))
}
/** The middle band never comes closer to an edge than the edge rows' own reference spacing allows. */
private fun Float.between(low: Float, high: Float) = coerceIn(low, max(low, high))
}
@@ -2,16 +2,12 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sqrt
import kotlin.math.sin
import kotlin.math.*
// Recreates the stock geometry written by schema 14 so its migration can recognise unedited layouts.
internal class LegacyLayoutGeometry(context: Context, private val width: Int, private val height: Int) {
private val safe = Rect()
private val resources = context.resources
internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int, private val safe: Rect = Rect(),
private val scale: Float = 1f) {
private val resources get() = context.resources
private val settings = ControllerPrefs.read(context)
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
@@ -45,7 +41,7 @@ internal class LegacyLayoutGeometry(context: Context, private val width: Int, pr
private fun dp(value: Float) = value * resources.displayMetrics.density
private fun scaled(value: Float) = dp(value) * fit
private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit
private fun fitScale(): Float {
val metrics = resources.displayMetrics
@@ -184,22 +180,139 @@ internal class LegacyLayoutGeometry(context: Context, private val width: Int, pr
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.map { c ->
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, hideWhenIdle = c.stick >= 0,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded()
}.toMutableList()
result += keyboard()
if (settings.keyboardButton) result += keyboard()
return result
}
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
val before = from.elements().associateBy { it.id }
val after = elements().associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
val inset = dp(BUTTONS_ONLY_INSET_DP)
val bottom = height - safe.bottom - inset
val radius = dp(BUTTONS_ONLY_RADIUS_DP)
fun pick(control: InputControl, shown: Boolean) = stored.firstOrNull { it.id == "legacy:${control.id}" }
?: stored.firstOrNull { it.control == control && it.kind == InputElementKind.BUTTON }
?: InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE).takeIf { shown }
return listOfNotNull(
pick(InputControl.GUIDE, settings.steamButton)?.let { circle(it, safe.left + inset, bottom, radius) },
pick(InputControl.QAM, settings.qamButton)?.let { circle(it, width - safe.right - inset, bottom, radius) },
stored.firstOrNull { it.id == KEYBOARD_ID }?.let { circle(it, width / 2f, bottom, dp(KEYBOARD_RADIUS_DP)) },
)
}
fun dock(stored: List<InputSurfaceElement>, portrait: Boolean, grips: Boolean, left: InputControl = InputControl.LS,
right: InputControl = InputControl.RS): List<InputSurfaceElement> {
val boxes = GamepadGeometry.layout(width.toFloat(), height.toFloat(), resources.displayMetrics.density, portrait)
val placed = mutableListOf<InputSurfaceElement>()
fun box(control: InputControl, slot: GamepadGeometry.Slot, shape: InputButtonShape) {
val b = boxes[slot] ?: return
placed += InputSurfaceElement(control, b.left / width, b.top / height, b.width / width, b.height / height,
floating = false, buttonShape = shape).bounded()
}
fun cross(controls: List<InputControl>, slot: GamepadGeometry.Slot) {
val b = boxes[slot] ?: return
val side = min(b.width, b.height)
val spread = side * CROSS_SPREAD
val radius = side * CROSS_RADIUS
controls.zip(listOf(0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f)).forEach { (control, direction) ->
placed += circle(InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE),
b.cx + direction.first * spread, b.cy + direction.second * spread, radius)
}
}
box(left, GamepadGeometry.Slot.LEFT_MAIN, InputButtonShape.CIRCLE)
cross(DPAD_ORDER, GamepadGeometry.Slot.LEFT_SECOND)
box(right, GamepadGeometry.Slot.RIGHT_MAIN, InputButtonShape.CIRCLE)
cross(FACE_ORDER, GamepadGeometry.Slot.RIGHT_SECOND)
box(InputControl.LT, GamepadGeometry.Slot.LEFT_OUTER_SHOULDER, InputButtonShape.PILL)
box(InputControl.LB, GamepadGeometry.Slot.LEFT_INNER_SHOULDER, InputButtonShape.PILL)
box(InputControl.RB, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER, InputButtonShape.PILL)
box(InputControl.RT, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER, InputButtonShape.PILL)
box(InputControl.SELECT, GamepadGeometry.Slot.VIEW, InputButtonShape.PILL)
box(InputControl.START, GamepadGeometry.Slot.MENU, InputButtonShape.PILL)
if (grips) GRIPS.forEach { (control, slot) -> box(control, slot, InputButtonShape.ROUNDED) }
val surfaces = listOf(left, right).filter { it.isTrackpad }
return withGeometry(stored, placed) + placed.filter { p -> (GRIPS.any { it.first == p.control } || p.control in surfaces) && stored.none { it.id == p.id } }
}
private fun circle(e: InputSurfaceElement, cx: Float, cy: Float, radius: Float) =
e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height).bounded()
private fun withGeometry(stored: List<InputSurfaceElement>, placed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = placed.associateBy { it.id }
return stored.mapNotNull { e -> byId[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } }
}
private fun keyboard(): InputSurfaceElement {
val radius = dp(KEYBOARD_RADIUS_DP)
val cx = safe.left + dp(KEYBOARD_X_DP)
val cy = height - safe.bottom - dp(KEYBOARD_Y_DP)
return InputSurfaceElement(InputControl.A, (cx - radius) / width, (cy - radius) / height, 2 * radius / width, 2 * radius / height,
KitLayout.KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded()
KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded()
}
fun restyle(elements: List<InputSurfaceElement>): List<InputSurfaceElement> {
val dpad = elements.filter { it.id == "legacy:${it.control.id}" && it.control in DPAD && it.buttonShape == InputButtonShape.ROUNDED }
val centreX = dpad.map { (it.x + it.width / 2f) * width }.average().toFloat()
val centreY = dpad.map { (it.y + it.height / 2f) * height }.average().toFloat()
val resize = untouchedDpad(dpad, centreX, centreY)
return elements.map { e ->
when {
e.id == KEYBOARD_ID && e.icon == 0 && e.name == "Keyboard" && e.buttonShape == InputButtonShape.ROUNDED &&
e.x == .02f && e.y == .9f && e.width == .12f && e.height == .08f -> keyboard()
e.id == "legacy:${e.control.id}" && e.buttonShape == InputButtonShape.ROUNDED -> {
val round = e.copy(buttonShape = if (e.control.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE)
(if (resize && e.control in DPAD) resizeDpad(round, centreX, centreY) else widenStick(round)).bounded()
}
else -> e
}
}
}
private fun untouchedDpad(dpad: List<InputSurfaceElement>, centreX: Float, centreY: Float): Boolean {
if (dpad.size != DPAD.size) return false
val radius = dpad[0].width * width / 2f
val tolerance = 1.5f
val offset = radius * LEGACY_DPAD_OFFSET_DP / LEGACY_DPAD_RADIUS_DP
return dpad.all { e ->
val old = controls.first { it.id == e.control.id }
val dx = (e.x + e.width / 2f) * width - centreX
val dy = (e.y + e.height / 2f) * height - centreY
abs(e.width * width / 2f - radius) <= tolerance && abs(e.height * height / 2f - radius) <= tolerance &&
abs(dx - offset * sign(old.offsetXDp)) <= tolerance && abs(dy - offset * sign(old.offsetYDp)) <= tolerance
}
}
private fun resizeDpad(e: InputSurfaceElement, centreX: Float, centreY: Float): InputSurfaceElement {
val old = controls.first { it.id == e.control.id }
val radius = e.width * width / 2f * old.radiusDp / LEGACY_DPAD_RADIUS_DP
val cx = centreX + ((e.x + e.width / 2f) * width - centreX) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
val cy = centreY + ((e.y + e.height / 2f) * height - centreY) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height)
}
private fun widenStickPreviously(e: InputSurfaceElement): InputSurfaceElement {
@@ -230,8 +343,20 @@ internal class LegacyLayoutGeometry(context: Context, private val width: Int, pr
const val SHOULDER_HEIGHT = 0.8f
val shoulderIds = setOf("lb", "rb", "lt", "rt")
const val STICK_REACH = 1.25f
const val LEGACY_DPAD_RADIUS_DP = 26f
const val LEGACY_DPAD_OFFSET_DP = 52f
val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
const val KEYBOARD_ID = "builtin:keyboard"
const val KEYBOARD_RADIUS_DP = 18f
const val KEYBOARD_X_DP = 90f
const val KEYBOARD_Y_DP = 34f
const val BUTTONS_ONLY_RADIUS_DP = 30f
const val BUTTONS_ONLY_INSET_DP = 44f
const val CROSS_SPREAD = .30f
const val CROSS_RADIUS = .16f
val DPAD_ORDER = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
val FACE_ORDER = listOf(InputControl.Y, InputControl.B, InputControl.A, InputControl.X)
val GRIPS = listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
}
}
@@ -3,99 +3,103 @@ 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.Rect
import android.graphics.RectF
import android.graphics.Typeface
import android.os.Build
import android.view.Gravity
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.InputSurfaceView
import com.droiddeck.launcher.ui.PadArt
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
/** Why the controls are hidden while the corner button stays. */
enum class Hidden { BY_TAP, BY_CONTROLLER }
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
private var layout: SavedInputLayout? = null
private val safe = Rect()
private var cutouts = emptyList<Rect>()
private var viewWidth = 0
private var viewHeight = 0
private val corner = CornerButton(context)
var hidden: Hidden? = null
private val placements = object : LinkedHashMap<Placement, List<InputSurfaceElement>>(4, .75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Placement, List<InputSurfaceElement>>) = size > PLACEMENT_CACHE
}
private val quickToggle = QuickToggle(context)
var isButtonsOnly = false
private set
var shortcutsOnly = false
var isQuickHidden = false
private set
/** Holding the corner button opens DroidDeck's controller menu. */
var onCornerHold: (() -> Unit)? = null
/** The player tapped the corner button. */
var onCornerTap: ((Hidden?) -> Unit)? = null
val inputSurface: InputSurfaceView get() = surface
var isPinnedOnly = false
private set
val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true
val inputSurface: com.droiddeck.launcher.ui.InputSurfaceView get() = surface
var onTouchMiss: ((MotionEvent) -> Unit)?
get() = surface.onTouchMiss
set(value) { surface.onTouchMiss = value }
init {
addView(surface, LayoutParams(-1, -1))
val size = (CORNER_HIT_DP * resources.displayMetrics.density).toInt()
addView(corner, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
val size = (QUICK_HIT_DP * 2 * resources.displayMetrics.density).toInt()
addView(quickToggle, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
}
fun updateLayout(value: SavedInputLayout?) {
val kit = PadKit.current(context)
if (layout == value && surface.kit == kit) return
if (layout == value) return
releaseAll()
layout = value
surface.kit = kit
render()
}
fun setPresentation(value: Hidden?, shortcuts: Boolean = false) {
if (hidden == value && shortcutsOnly == shortcuts) return
fun setButtonsOnly(enabled: Boolean) {
if (isButtonsOnly == enabled) return
releaseAll()
hidden = value
shortcutsOnly = shortcuts
isButtonsOnly = enabled
isQuickHidden = false
render()
}
fun setQuickHidden(hidden: Boolean) {
if (isButtonsOnly || isQuickHidden == hidden) return
releaseAll()
isQuickHidden = hidden
render()
}
fun setPinnedOnly(enabled: Boolean) {
if (isPinnedOnly == enabled) return
releaseAll()
isPinnedOnly = enabled
render()
}
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
private fun placed(): List<InputSurfaceElement> {
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
return placements.getOrPut(key) {
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock)
}
}
private fun render() {
val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock, cutouts,
rearButtons = SessionPrefs.oscRearButtons(context), trackpads = SessionPrefs.oscTrackpads(context))
val elements = placed()
surface.updateCustomLayout(when {
isPinnedOnly -> elements.filter { it.alwaysShown }
isQuickHidden -> elements.filter { it.id == "builtin:keyboard" || it.alwaysShown }
else -> elements
})
val style = layout?.style ?: InputSurfaceStyle()
val visible = if (hidden == null && !shortcutsOnly) placed else {
val pinned = placed.filter { it.alwaysShown && !style.hides(it) }
if (hidden != null) pinned else pinned + OnScreenLayout.steamShortcuts(viewWidth, viewHeight, safe, resources.displayMetrics.density, pinned)
}
surface.updateCustomLayout(visible)
surface.updateStyle(style)
corner.visibility = if (layout == null || dock != null) GONE else VISIBLE
corner.alpha = (layout?.style?.opacity ?: 100) / 100f
val density = resources.displayMetrics.density
val margin = (CORNER_MARGIN_DP * density).toInt()
val params = corner.layoutParams as LayoutParams
val leftInset = if (dock == null && viewWidth >= viewHeight && layout?.let(OnScreenLayout::generated) == true)
KitLayout.cornerInset(safe, cutouts, viewHeight, density) else safe.left
if (params.leftMargin != leftInset + margin || params.bottomMargin != safe.bottom + margin) {
params.leftMargin = leftInset + margin
params.bottomMargin = safe.bottom + margin
corner.layoutParams = params
}
corner.invalidate()
quickToggle.tint = style.tint
quickToggle.alpha = style.opacity / 100f
quickToggle.visibility = if (isButtonsOnly || isPinnedOnly || layout == null || dock != null) GONE else VISIBLE
quickToggle.invalidate()
}
fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y) ||
corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
fun cornerTakes(x: Float, y: Float) = corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
quickToggle.visibility == VISIBLE && x >= quickToggle.left && x < quickToggle.right && y >= quickToggle.top && y < quickToggle.bottom
fun releaseAll() = surface.releaseInputs()
fun reload() { releaseAll(); surface.kit = PadKit.current(context); render() }
fun reload() { releaseAll(); placements.clear(); render() }
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val w = MeasureSpec.getSize(widthMeasureSpec)
@@ -112,55 +116,59 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
val offset = ((QUICK_CENTER_DP - QUICK_HIT_DP) * resources.displayMetrics.density).toInt()
val params = quickToggle.layoutParams as LayoutParams
val left = (cutout?.safeInsetLeft ?: 0) + offset
val bottom = (cutout?.safeInsetBottom ?: 0) + offset
if (params.leftMargin != left || params.bottomMargin != bottom) {
params.leftMargin = left
params.bottomMargin = bottom
quickToggle.layoutParams = params
}
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
val bounds = cutout?.boundingRects.orEmpty()
if (fresh != safe || bounds != cutouts) {
if (fresh != safe) {
safe.set(fresh)
cutouts = bounds
render()
}
return super.onApplyWindowInsets(insets)
}
private inner class CornerButton(context: Context) : View(context) {
private val art = PadArt(context)
private val badge = Paint(Paint.ANTI_ALIAS_FLAG)
private inner class QuickToggle(context: Context) : View(context) {
var tint: Int? = ControllerPrefs.STEAM_BLUE
private val density = resources.displayMetrics.density
private var armed = false
private var held = false
private val hold = Runnable { if (armed) { held = true; performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } }
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.5f * density }
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
textSize = 22 * density
}
override fun onDraw(canvas: Canvas) {
val w = width.toFloat(); val h = height.toFloat()
val dimmed = hidden != null && !armed
if (dimmed) canvas.saveLayerAlpha(0f, 0f, w, h, 170)
art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.MARK, armed)
if (dimmed) canvas.restore()
if (hidden == Hidden.BY_CONTROLLER) {
val d = art.density
val r = RectF(w - 15 * d, 3 * d, w - 2 * d, 12 * d)
badge.style = Paint.Style.FILL; badge.color = Color.rgb(0x16, 0x19, 0x1E)
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
badge.style = Paint.Style.STROKE; badge.strokeWidth = 1.3f * d; badge.color = Color.rgb(0xFF, 0xB3, 0x47)
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
}
val x = width / 2f
val y = height / 2f
val radius = QUICK_RADIUS_DP * density
val color = tint
fill.color = if (color != null) InputSurfaceView.shade(color, 190, 0.12f) else (InputSurfaceView.SURFACE and 0x00ffffff) or (190 shl 24)
canvas.drawCircle(x, y, radius, fill)
stroke.color = if (color != null) InputSurfaceView.light(color, 150, 0.25f) else InputSurfaceView.LINE
canvas.drawCircle(x, y, radius, stroke)
text.color = if (color != null) InputSurfaceView.light(color, 210, 0.75f) else InputSurfaceView.TEXT
canvas.drawText(if (isQuickHidden) "+" else "−", x, y + text.textSize * 0.35f, text)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> { armed = true; held = false; postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()); invalidate() }
MotionEvent.ACTION_CANCEL -> { armed = false; removeCallbacks(hold); invalidate() }
MotionEvent.ACTION_DOWN -> armed = true
MotionEvent.ACTION_CANCEL -> armed = false
MotionEvent.ACTION_UP -> {
removeCallbacks(hold)
if (armed && held) post { onCornerHold?.invoke() }
else if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
val next = if (hidden == null) Hidden.BY_TAP else null
setPresentation(next, shortcutsOnly)
onCornerTap?.invoke(next)
setQuickHidden(!isQuickHidden)
}
armed = false
invalidate()
}
}
return true
@@ -168,7 +176,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
}
private companion object {
const val CORNER_HIT_DP = 48f
const val CORNER_MARGIN_DP = 4f
const val QUICK_CENTER_DP = 34f
const val QUICK_HIT_DP = 26f
const val QUICK_RADIUS_DP = 18f
const val PLACEMENT_CACHE = 4
}
}
@@ -2,8 +2,10 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
object OnScreenLayout {
data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) {
@@ -19,66 +21,25 @@ object OnScreenLayout {
}
}
/**
* The built-in gamepad keeps no kit positions until its kit is edited; until then the kit follows the virtual controller and
* the layout stores only the keys and controls the player added on top.
*/
fun generated(layout: SavedInputLayout) = hasBuiltInKit(layout) && layout.elements.none { KitLayout.isKit(it.id) }
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
fun hasBuiltInKit(layout: SavedInputLayout) =
!layout.kitless && (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY)
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null,
cutouts: List<Rect> = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true): List<InputSurfaceElement> {
layout ?: return emptyList()
if (width <= 0 || height <= 0) return layout.elements
if (generated(layout)) {
val kit = PadKit.current(context)
val extras = if (layout.elements.isEmpty()) emptyList() else fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
return (if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right)
else KitLayout.elements(context, kit, width, height, safe, layout.scale, cutouts, rearButtons, trackpads, addedControls = extras)) + extras
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null): List<InputSurfaceElement> {
val stored = layout?.elements ?: return emptyList()
if (width <= 0 || height <= 0) return stored
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val (reference, generated) = reference(context, layout, width, height)
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
val placed = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
else -> generator.regenerate(gamepad)
}
val elements = if (dock == null && hasBuiltInKit(layout)) layout.elements.filter { element ->
!KitLayout.isKit(element.id) || KitLayout.visibleOnOverlay(element.control, rearButtons, trackpads)
} else layout.elements
return fit(elements, aspect(context, layout), 1f, width, height, safe)
}
internal const val STEAM_SHORTCUT_ID = "shortcut:steam"
internal const val QAM_SHORTCUT_ID = "shortcut:qam"
internal fun steamShortcuts(width: Int, height: Int, safe: Rect, density: Float,
pinned: List<InputSurfaceElement> = emptyList()): List<InputSurfaceElement> {
if (width <= 0 || height <= 0) return emptyList()
val size = min(48f * density, (width - safe.left - safe.right - 64f * density) / 2f)
if (size <= 0f || height - safe.bottom - safe.top < size) return emptyList()
val gap = 4f * density
val left = safe.left + 56f * density
val right = width - safe.right - size - gap
val middle = (left + right) / 2f
val pinnedFromBottom = pinned.sortedByDescending { it.y }
fun button(control: InputControl, id: String, leftSide: Boolean): InputSurfaceElement? {
val edge = if (leftSide) left else right
val range = if (leftSide) left..(middle - size / 2f) else (middle + size / 2f)..right
val candidates = listOf(edge) + pinned.map {
if (leftSide) (it.x + it.width) * width + gap else it.x * width - size - gap
}.filter { it in range }.sortedBy { kotlin.math.abs(it - edge) }
for (x in candidates) {
var y = max(safe.top.toFloat(), height - safe.bottom - size - gap)
for (element in pinnedFromBottom) {
if (x >= (element.x + element.width) * width || x + size <= element.x * width) continue
if (y >= (element.y + element.height) * height || y + size <= element.y * height) continue
y = element.y * height - size - gap
}
if (y >= safe.top) return InputSurfaceElement(control, x / width, y / height, size / width, size / height,
id, buttonShape = InputButtonShape.PILL).bounded()
}
return null
}
return listOfNotNull(
button(InputControl.GUIDE, STEAM_SHORTCUT_ID, leftSide = true),
button(InputControl.QAM, QAM_SHORTCUT_ID, leftSide = false),
)
val byId = (placed + others).associateBy { it.id }
return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
@@ -93,23 +54,15 @@ object OnScreenLayout {
val w = width.toFloat()
val h = height.toFloat()
val scale = min(w / referenceWidth, h / referenceHeight)
// A layout shown on a screen of the other orientation keeps its shape: spread by thirds, its clusters would come apart.
val turned = (w > h) != (referenceWidth > referenceHeight)
val blockX = turned && w > referenceWidth * scale * BLOCK_STRETCH
val blockY = turned && h > referenceHeight * scale * BLOCK_STRETCH
return elements.map { e ->
val ew = e.width * referenceWidth * scale
val eh = e.height * referenceHeight * scale
val x = if (blockX) (w + safe.left - safe.right) / 2f + (e.x - .5f) * referenceWidth * scale else anchor(e.x, e.width, referenceWidth, w, scale)
val y = if (blockY) h - safe.bottom - (1f - e.y) * referenceHeight * scale else anchor(e.y, e.height, referenceHeight, h, scale)
val left = x.coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - ew))
val top = y.coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - eh))
val left = anchor(e.x, e.width, referenceWidth, w, scale).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - ew))
val top = anchor(e.y, e.height, referenceHeight, h, scale).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - eh))
e.copy(x = left / w, y = top / h, width = ew / w, height = eh / h).bounded()
}
}
private const val BLOCK_STRETCH = 1.5f
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
val centre = start + size / 2f
val scaled = size * reference * scale
@@ -120,8 +73,35 @@ object OnScreenLayout {
}
}
private fun aspect(context: Context, layout: SavedInputLayout): Float = layout.aspect.takeIf { it > 0f } ?: run {
val metrics = InputLibraries.primaryDisplay(context).second
max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1).toFloat() / min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
reference(context, layout, width, height).takeIf { it.second }?.first?.let { it.first.toInt() to it.second.toInt() }
private fun reference(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Pair<Float, Float>, Boolean> {
val (display, metrics) = InputLibraries.primaryDisplay(context)
val long = max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val short = min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val gamepad = layout.elements.filter(::isGamepad)
if (gamepad.any { it.id.startsWith("legacy:") }) {
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f }
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true))) return (w.toFloat() to h.toFloat()) to true
}
}
val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short)
return (aspect to 1f) to false
}
private fun matches(stored: List<InputSurfaceElement>, generated: List<InputSurfaceElement>): Boolean {
val byId = generated.associateBy { it.id }
return stored.all { e ->
val g = byId[e.id] ?: return@all false
abs(e.x - g.x) <= TOLERANCE && abs(e.y - g.y) <= TOLERANCE && abs(e.width - g.width) <= TOLERANCE && abs(e.height - g.height) <= TOLERANCE
}
}
}
@@ -107,8 +107,6 @@ public final class PadBridge {
private volatile Runnable onPlayerInput;
private Runnable onChordInput;
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private volatile Runnable onPhysicalInput;
private final java.util.concurrent.atomic.AtomicBoolean physicalInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private static final long STATS_WINDOW_MS = 10_000;
private int statButtons, statAxes, statOnScreen, statDropped;
@@ -370,20 +368,6 @@ public final class PadBridge {
onPlayerInput = listener;
}
/** Input from a controller the player holds, never from the on-screen controls. */
public void setOnPhysicalInput(Runnable listener) {
onPhysicalInput = listener;
}
private void notePhysicalInput() {
Runnable listener = onPhysicalInput;
if (listener == null || !physicalInputPosted.compareAndSet(false, true)) return;
mainHandler.post(() -> {
physicalInputPosted.set(false);
listener.run();
});
}
public synchronized void setOnChordInput(Runnable listener) {
onChordInput = listener;
}
@@ -449,7 +433,7 @@ public final class PadBridge {
}
noteDevice(device, slot);
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
if (pressed) { notePlayerInput(); notePhysicalInput(); }
if (pressed) notePlayerInput();
statButtons++;
scheduleStats();
publish(slot);
@@ -537,7 +521,7 @@ public final class PadBridge {
retainStick(slot, side, x, y);
projectSticks(slot);
if (chordStickInput) noteChordInput(slot);
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) { notePlayerInput(); notePhysicalInput(); }
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
publish(slot);
InputTiming.end(timing);
return true;
@@ -579,7 +563,6 @@ public final class PadBridge {
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
notePlayerInput();
notePhysicalInput();
}
publish(slot);
InputTiming.end(timing);
@@ -1,48 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
enum class DpadStyle { CROSS, DISC, ARROWS }
enum class StickCap { RINGED, DISHED, KNURLED }
enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) {
STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true),
DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED),
DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED);
val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER
val playStation get() = this == DUALSHOCK || this == DUALSENSE
fun label(control: InputControl): String = when (control) {
InputControl.LB -> if (xbox) "LB" else "L1"
InputControl.RB -> if (xbox) "RB" else "R1"
InputControl.LT -> if (xbox) "LT" else "L2"
InputControl.RT -> if (xbox) "RT" else "R2"
else -> control.label
}
/** What the player calls [control] on this controller. */
fun name(control: InputControl): String = if (!playStation) label(control) else when (control) {
InputControl.A -> "Cross"
InputControl.B -> "Circle"
InputControl.X -> "Square"
InputControl.Y -> "Triangle"
else -> label(control)
}
companion object {
fun of(type: String) = when (type) {
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
else -> STEAM_DECK
}
fun current(context: Context) = of(SessionPrefs.steamController(context))
}
}
@@ -25,10 +25,7 @@ data class PhysicalInputKey(val device: String, val name: String, val keyCode: I
data class PhysicalInputBinding(val key: PhysicalInputKey, val action: InputAction)
class PhysicalInputBindings(
private val router: InputRouter,
private val onPress: (KeyEvent) -> Unit = {},
) {
class PhysicalInputBindings(private val router: InputRouter) {
private class Entry(val binding: PhysicalInputBinding, val channel: InputRouter.Channel) {
var heldDevice = -1
var suppressed = false
@@ -69,10 +66,7 @@ class PhysicalInputBindings(
if (identity != key.device) continue
entry.heldDevice = event.deviceId
entry.suppressed = event.repeatCount != 0
if (!entry.suppressed) {
entry.channel.update(1f)
onPress(event)
}
if (!entry.suppressed) entry.channel.update(1f)
return true
}
return false
@@ -20,11 +20,7 @@ import java.util.ArrayDeque
import java.util.UUID
@SuppressLint("MissingPermission")
class SteamControllerBle(
private val context: Context,
router: InputRouter? = null,
private val onPhysicalInput: (() -> Unit)? = null,
) {
class SteamControllerBle(private val context: Context, router: InputRouter? = null) {
private val inputLock = router ?: Any()
private var routedInput = router?.let(::TritonInputRouter)
@Volatile private var stopped = false
@@ -43,7 +39,6 @@ class SteamControllerBle(
private var outputSequence = 0L
private var outputWritePending = false
private var featureRead = 0L
private var lastPressedControls = 0
fun start(): Unit = synchronized(inputLock) {
if (stopped || started) return@synchronized
@@ -271,18 +266,12 @@ class SteamControllerBle(
val timing = InputTiming.begin()
FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data)
InputTiming.end(timing)
if (connected && onPhysicalInput != null) {
val pressed = TritonInputRouter.pressedControls(data)
if (pressed and lastPressedControls.inv() != 0) onPhysicalInput()
lastPressedControls = pressed
}
}
private fun release() = synchronized(inputLock) {
if (stopped) return@synchronized
routedInput?.release()
withSlot {
lastPressedControls = 0
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
}
}
@@ -119,7 +119,6 @@ class SteamTouchControls(
private var selectedArm = 0
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val art = com.droiddeck.launcher.ui.PadArt(context)
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; isFakeBoldText = true }
@@ -241,10 +240,7 @@ class SteamTouchControls(
private fun cx(e: Element) = e.x * width
private fun cy(e: Element) = e.y * height
private fun reach(e: Element, x: Float, y: Float): Float {
val dx = (x - cx(e)) / radius(e); val dy = (y - cy(e)) / radiusY(e)
return if (e.type in TRACKPADS) max(abs(dx), abs(dy)) else hypot(dx, dy)
}
private fun reach(e: Element, x: Float, y: Float) = hypot((x - cx(e)) / radius(e), (y - cy(e)) / radiusY(e))
private fun hit(list: List<Element>, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
@@ -285,61 +281,58 @@ class SteamTouchControls(
val r = radius(e)
val pressed = !editing && e.type in pressedTypes()
val alpha = (255 * alphaScale * if (faded) FADED else 1f).toInt().coerceIn(30, 255)
stroke.color = Color.rgb(Color.red(tint), Color.green(tint), Color.blue(tint)); stroke.strokeWidth = lineWidth()
fill.color = Color.argb(217, 230, 233, 236)
if (alpha < 255) canvas.saveLayerAlpha(x - r * 1.5f, y - r * 1.5f, x + r * 1.5f, y + r * 1.5f, alpha)
val ink = Color.argb(alpha, Color.red(tint), Color.green(tint), Color.blue(tint))
stroke.color = if (isSelected) Color.rgb(26, 159, 255) else ink
stroke.strokeWidth = if (isSelected) lineWidth() * 2f else lineWidth()
fill.color = Color.argb((alpha * 0.85f).toInt(), 230, 233, 236)
text.color = ink
text.typeface = android.graphics.Typeface.DEFAULT_BOLD
when (e.type) {
SteamTouchConfig.DPAD -> if (visuals[SteamTouchConfig.DPAD].orEmpty().any { it.binding?.hasIcon == true }) drawDpad(canvas, e, x, y, r) else {
val bits = if (editing) 0L else dpadBits(e)
val held = (if (bits and DPAD_UP != 0L) 1 else 0) or (if (bits and DPAD_RIGHT != 0L) 2 else 0) or
(if (bits and DPAD_DOWN != 0L) 4 else 0) or (if (bits and DPAD_LEFT != 0L) 8 else 0)
canvas.save(); canvas.translate(x - r, y - r)
art.dpad(canvas, 2 * r, 2 * r, PadKit.STEAM_DECK, held, ink = glyphInk())
canvas.restore()
}
SteamTouchConfig.DPAD -> drawDpad(canvas, e, x, y, r)
SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> {
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
var kx = 0f; var ky = 0f
if (f != null) {
canvas.drawCircle(x, y, r, stroke)
val f = fingers.values.firstOrNull { it.element?.type == e.type }
if (f != null && !editing) {
val d = hypot(f.x - x, f.y - y)
val k = if (d > r) r / d else 1f
kx = (f.x - x) * k * .54f; ky = (f.y - y) * k * .54f
val kx = x + (f.x - x) * k
val ky = y + (f.y - y) * k
canvas.drawCircle(kx, ky, r * 0.42f, fill)
}
art.stick(canvas, x, y, r, PadKit.STEAM_DECK, kx, ky, f != null)
}
SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> {
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
canvas.save(); canvas.translate(x - r, y - r)
art.trackpad(canvas, r * 2f, r * 2f, f != null, (f?.x ?: x) - x + r, (f?.y ?: y) - y + r)
canvas.restore()
if (editing) art.text(canvas, context.getString(R.string.deck_surface_trackpad), x, y, r * .3f, Color.argb(128, 255, 255, 255))
val rect = RectF(x - r * 1.3f, y - r * 0.85f, x + r * 1.3f, y + r * 0.85f)
if (pressed) canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, fill)
canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, stroke)
if (editing) {
text.textSize = r * 0.3f
text.color = Color.argb(alpha / 2, 255, 255, 255)
canvas.drawText(context.getString(R.string.deck_surface_trackpad), x, y - (text.descent() + text.ascent()) / 2, text)
}
}
SteamTouchConfig.STEAM -> {
if (isSelected) canvas.drawCircle(x, y, r, stroke)
drawMark(canvas, x, y, r * 0.5f, if (pressed) accent else ink, alpha)
}
SteamTouchConfig.STEAM -> systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.PILL, com.droiddeck.launcher.ui.PadArt.Icon.STEAM, pressed)
SteamTouchConfig.SELECT, SteamTouchConfig.START -> {
val binding = visuals[e.type]?.firstOrNull()?.binding
if (binding?.hasIcon == true) drawFace(canvas, e.type, binding, x, y, r, pressed)
else systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.CHIP,
if (e.type == SteamTouchConfig.START) com.droiddeck.launcher.ui.PadArt.Icon.MENU else com.droiddeck.launcher.ui.PadArt.Icon.VIEW, pressed)
if (binding?.hasIcon == true) {
drawFace(canvas, e.type, binding, x, y, r, alpha, pressed); return
}
val rect = RectF(x - r * 1.08f, y - r * 0.55f, x + r * 1.08f, y + r * 0.55f)
if (pressed) canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, fill)
canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, stroke)
val t = r * 0.26f
val dir = if (e.type == SteamTouchConfig.START) 1f else -1f
val tri = Path().apply {
moveTo(x + dir * t, y); lineTo(x - dir * t * 0.75f, y - t); lineTo(x - dir * t * 0.75f, y + t); close()
}
canvas.drawPath(tri, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (pressed) Color.argb(alpha, 23, 26, 33) else ink })
}
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, pressed)
}
if (alpha < 255) canvas.restore()
if (isSelected) {
stroke.color = accent; stroke.strokeWidth = lineWidth() * 2f
if (isSquare(e.type)) canvas.drawRoundRect(RectF(x - r, y - r, x + r, y + r), r * .3f, r * .3f, stroke) else canvas.drawCircle(x, y, r, stroke)
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, alpha, pressed)
}
}
private fun systemButton(canvas: Canvas, x: Float, y: Float, r: Float, shape: com.droiddeck.launcher.ui.PadArt.Shape,
icon: com.droiddeck.launcher.ui.PadArt.Icon, pressed: Boolean) {
canvas.save(); canvas.translate(x - r * 1.4f, y - r * 1.4f)
art.system(canvas, r * 2.8f, r * 2.8f, shape, icon, pressed, glyphInk())
canvas.restore()
}
/** Glyphs follow the colour picked for Steam touch controls; white keeps the shared artwork's own ink. */
private fun glyphInk() = if (tint != Color.WHITE) tint else com.droiddeck.launcher.ui.PadArt.INK
private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT,
SteamTouchConfig.TRIGGER_LEFT, SteamTouchConfig.TRIGGER_RIGHT, SteamTouchConfig.THUMB, SteamTouchConfig.KEYBOARD,
SteamTouchConfig.PASTE, SteamTouchConfig.MACRO_1_FINGER, SteamTouchConfig.MACRO_2_FINGER) ||
@@ -357,29 +350,53 @@ class SteamTouchControls(
canvas.restore()
}
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float, pressed: Boolean) {
val shape = if (isSquare(type)) art.roundRect(x - r, y - r, x + r, y + r, r * .3f) else art.circle(x, y, r)
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
alpha: Int, pressed: Boolean) {
val square = isSquare(type)
val rect = RectF(x - r, y - r, x + r, y + r)
val corner = r * 0.3f
fun shape(paint: Paint) = if (square) canvas.drawRoundRect(rect, corner, corner, paint) else canvas.drawCircle(x, y, r, paint)
val icon = binding?.icon?.takeIf { it.isNotEmpty() }?.let(::iconOrLoad)
val custom = binding != null && binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
art.glass(canvas, shape, pressed && !custom, if (custom) parseColor(binding!!.background, SteamTouchBindings.DEFAULT_BACKGROUND) else 0x850E1014.toInt())
val ink = if (pressed && !custom) com.droiddeck.launcher.ui.PadArt.ON_ACCENT else glyphInk()
if (icon != null) {
val s = r * 0.62f
if (custom) canvas.drawBitmap(tinted(binding!!.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s), Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
else canvas.drawBitmap(inked(binding!!.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN) })
val custom = binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
if (custom) {
shape(Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = parseColor(binding.background, SteamTouchBindings.DEFAULT_BACKGROUND)
this.alpha = if (pressed) alpha else (alpha * 0.85f).toInt()
})
canvas.drawBitmap(tinted(binding.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { this.alpha = alpha })
} else {
if (pressed) shape(fill)
val ink = if (pressed) Color.argb(alpha, 23, 26, 33) else stroke.color
canvas.drawBitmap(inked(binding.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply {
colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN)
})
}
shape(stroke)
return
}
if (type == SteamTouchConfig.THUMB) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.QAM, ink); return }
if (type == SteamTouchConfig.KEYBOARD) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.KEYBOARD, ink); return }
val shown = label(type)
val size = when {
if (pressed) shape(fill)
shape(stroke)
if (type == SteamTouchConfig.THUMB) { drawDots(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
if (type == SteamTouchConfig.KEYBOARD) { drawKeyboardGlyph(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
val own = label(type)
val shown = own
text.textSize = when {
shown.length <= 1 -> r * 0.9f
shown.length <= 2 -> r * 0.66f
shown.length <= 5 -> r * 0.4f
else -> r * 0.3f
}
art.text(canvas, if (shown.length > 10) shown.take(9) + "…" else shown, x, y, size, ink, r * 1.8f)
text.color = when {
pressed -> Color.argb(alpha, 23, 26, 33)
shown == own -> LABEL_COLORS[type]?.let { Color.argb(alpha, Color.red(it), Color.green(it), Color.blue(it)) } ?: text.color
else -> text.color
}
val line = if (shown.length > 10) shown.take(9) + "…" else shown
canvas.drawText(line, x, y - (text.descent() + text.ascent()) / 2, text)
}
private fun drawDots(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
@@ -387,6 +404,15 @@ class SteamTouchControls(
for (i in -1..1) canvas.drawCircle(x + i * r * 0.3f, y + r * 0.22f, r * 0.08f, p)
}
private fun drawKeyboardGlyph(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = lineWidth() * 0.8f }
val body = RectF(x - r * 0.6f, y - r * 0.34f, x + r * 0.6f, y + r * 0.34f)
canvas.drawRoundRect(body, r * 0.08f, r * 0.08f, p)
val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }
for (row in 0..1) for (i in 0..5) canvas.drawCircle(body.left + r * 0.15f + i * r * 0.18f, body.top + r * 0.18f + row * r * 0.17f, r * 0.035f, dot)
canvas.drawLine(x - r * 0.3f, body.bottom - r * 0.14f, x + r * 0.3f, body.bottom - r * 0.14f, p)
}
private val iconsLoading = HashSet<String>()
private val inkedIcons = android.util.LruCache<String, android.graphics.Bitmap>(48)
@@ -1452,7 +1478,6 @@ class SteamTouchControls(
var onSaved: () -> Unit = {}
companion object {
private val TRACKPADS = setOf(SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER)
private const val TAG = "SteamTouch"
private const val POLL_MS = 150L
private const val MOVE_REDRAW_MS = 33L
@@ -1494,5 +1519,11 @@ class SteamTouchControls(
put(SteamTouchConfig.PASTE, 0L)
}
private val LABEL_COLORS = mapOf(
SteamTouchConfig.A to Color.rgb(72, 133, 48),
SteamTouchConfig.B to Color.rgb(211, 68, 37),
SteamTouchConfig.X to Color.rgb(23, 60, 184),
SteamTouchConfig.Y to Color.rgb(235, 200, 70),
)
}
}
@@ -63,25 +63,16 @@ class TritonInputRouter(private val router: InputRouter) {
fun release() = synchronized(router) { channels.forEach { it.release() }; last = null }
fun close() = synchronized(router) { release(); channels.forEach { it.close() }; router.removeSnapshot(snapshot) }
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
private fun putBits(data: ByteArray, value: Int) { for (i in 0..3) data[i + 1] = (value ushr (i * 8)).toByte() }
private fun short(data: ByteArray, offset: Int) = ((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
private fun axis(data: ByteArray, offset: Int): Float = short(data, offset).let { it / if (it < 0) 32768f else 32767f }
private fun shortValue(value: Float) = (value * if (value < 0f) 32768f else 32767f).roundToInt().coerceIn(-32768, 32767)
private fun putShort(data: ByteArray, offset: Int, value: Int) { data[offset] = value.toByte(); data[offset + 1] = (value shr 8).toByte() }
companion object {
private const val CONTROL_BITS = 0x0fffffff
internal fun pressedControls(data: ByteArray): Int {
var active = bits(data) and CONTROL_BITS
if ((5..15 step 2).any { kotlin.math.abs(short(data, it)) > 16384 }) active = active or (1 shl 28)
return active
}
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
private fun short(data: ByteArray, offset: Int) =
((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
private fun bit(c: InputControl): Int = when (c) {
InputControl.A -> 0x1; InputControl.B -> 0x2; InputControl.X -> 0x4; InputControl.Y -> 0x8
InputControl.QAM -> 0x10; InputControl.R3 -> 0x20; InputControl.START -> 0x40
@@ -69,18 +69,8 @@ object SessionDisplay {
const val UNFOLDED_MIN_DP = 600
/**
* The game's share of a screen with the controls below it, at the game's [aspect] across the full width. A tab row under the bar
* comes out of the controls while they keep [UNFOLDED_MIN_CONTROLS_SHARE] of the screen, and out of the game otherwise.
*/
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0, aspect: Float = 16f / 9f): Int {
val game = minOf((width / aspect.coerceAtLeast(.5f)).toInt(), (height * UNFOLDED_MAX_GAME_SHARE).toInt())
val tabs = tabRow.coerceAtLeast(0)
val roomy = height - game - tabs >= height * UNFOLDED_MIN_CONTROLS_SHARE
return (if (roomy) game else game - tabs).coerceAtLeast(0) and 1.inv()
}
const val UNFOLDED_MIN_CONTROLS_SHARE = .45f
fun unfoldedGameHeight(width: Int, height: Int, tabRow: Int = 0): Int =
(minOf(width * 9 / 16, (height * UNFOLDED_MAX_GAME_SHARE).toInt()) - tabRow.coerceAtLeast(0)).coerceAtLeast(0) and 1.inv()
fun unfoldedControlsWanted(
enabled: Boolean,
@@ -664,38 +664,13 @@ object SessionPrefs {
prefs(context).getString("shape", null)
?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO
/** Overlay visibility. Older builds also stored the Steam layout here. */
fun oscMode(context: Context, steamSession: Boolean? = null): String = when (val mode = prefs(context).getString("osc", OSC_AUTO)) {
OSC_ALWAYS, OSC_NEVER -> mode
OSC_STEAM_QAM -> if (steamSession == false) OSC_AUTO else OSC_STEAM_QAM
OSC_STEAM_TOUCH -> if (steamSession == true) OSC_ALWAYS else OSC_AUTO
else -> OSC_AUTO
fun oscMode(context: Context, steamSession: Boolean = true): String {
val saved = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO
return if (!steamSession && saved == OSC_STEAM_QAM) OSC_AUTO else saved
}
fun setOscMode(context: Context, mode: String) {
val editor = prefs(context).edit()
if (!prefs(context).contains("steamTouchLayout")) editor.putBoolean("steamTouchLayout", steamTouchLayout(context))
editor.putString("osc", mode).apply()
}
fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false)
fun setOscRearButtons(context: Context, shown: Boolean) {
prefs(context).edit().putBoolean("oscRearButtons", shown).apply()
}
fun oscTrackpads(context: Context): Boolean = prefs(context).getBoolean("oscTrackpads", false)
fun setOscTrackpads(context: Context, shown: Boolean) {
prefs(context).edit().putBoolean("oscTrackpads", shown).apply()
}
/** Draw Steam's touch layout for the game instead of DroidDeck's own. */
fun steamTouchLayout(context: Context): Boolean =
prefs(context).getBoolean("steamTouchLayout", prefs(context).getString("osc", null) == OSC_STEAM_TOUCH)
fun setSteamTouchLayout(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("steamTouchLayout", on).apply()
prefs(context).edit().putString("osc", mode).apply()
}
fun linuxDriver(context: Context): String =
@@ -1974,7 +1949,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("pipAutoEnter", enabled).apply()
}
fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", true)
fun unfoldedControls(context: Context): Boolean = prefs(context).getBoolean("unfoldedControls", false)
fun controlsBelowWanted(context: Context, mode: String, width: Int, height: Int, pip: Boolean = false): Boolean =
SessionDisplay.unfoldedControlsWanted(
@@ -152,7 +152,7 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
suspendPolicy = suspend, onSuspendPolicy = { suspend = it },
backActionsInverted = inverted, onBackActionsInverted = { inverted = it },
touchMode = touch, onTouch = { touch = it },
touchAuto = stringResource(R.string.mode_touch_mouse),
touchAuto = stringResource(R.string.session_touch_auto_direct),
fexPreset = fex, onFexPreset = { fex = it },
fpsLimit = fps, onFpsLimit = { fps = it },
secondScreenMode = second, onSecondScreenMode = { second = it },
@@ -38,7 +38,7 @@ internal fun InputElementProperties(element: InputSurfaceElement, action: InputA
withContext(Dispatchers.IO) { InputButtonImages.import(context.applicationContext, uri) }?.let { change(current.copy(icon = 0, image = it)) }
}
}
ToggleRow(host, "element-toggle", stringResource(R.string.input_toggle_button), null, element.toggle) { onChange(element.copy(toggle = it)) }
ToggleRow(host, "element-toggle", stringResource(R.string.input_toggle_button), stringResource(R.string.input_toggle_button_hint), element.toggle) { onChange(element.copy(toggle = it)) }
ChoiceRow(host, "element-shape", stringResource(R.string.input_button_shape), null,
InputButtonShape.entries.map { it to stringResource(when (it) { InputButtonShape.ROUNDED -> R.string.input_shape_rounded; InputButtonShape.PILL -> R.string.input_shape_pill; InputButtonShape.CIRCLE -> R.string.input_shape_circle; InputButtonShape.RECTANGLE -> R.string.input_shape_rectangle }) },
element.buttonShape) { onChange(element.copy(buttonShape = it)) }
@@ -63,7 +63,7 @@ internal fun InputElementProperties(element: InputSurfaceElement, action: InputA
}
}
if (element.kind == InputElementKind.TRACKPAD) {
ToggleRow(rememberMenuHost(), "element-mouse-gestures", stringResource(R.string.input_mouse_gestures), null, element.mouseGestures) { onChange(element.copy(mouseGestures = it)) }
ToggleRow(rememberMenuHost(), "element-mouse-gestures", stringResource(R.string.input_mouse_gestures), stringResource(R.string.input_mouse_gestures_hint), element.mouseGestures) { onChange(element.copy(mouseGestures = it)) }
}
if (element.kind == InputElementKind.STICK) {
val host = rememberMenuHost()
@@ -3,16 +3,51 @@ package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Canvas
import android.view.View
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
@Composable
internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: String?, onManage: () -> Unit, onPick: () -> Unit) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.weight(1f).focusRow(onClick = onPick).padding(12.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
InputLayoutThumbnail(layout, role)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(layout.name, style = MaterialTheme.typography.titleMedium)
Text(detail ?: stringResource(R.string.input_layout_count, layout.elements.size),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
PadTextButton(onClick = onManage, modifier = Modifier.testTag("layout-manage-${layout.id}")) { Text("⋮", style = MaterialTheme.typography.titleLarge) }
}
}
@Composable
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole) {
AndroidView(factory = { InputLayoutPreviewView(it) }, modifier = Modifier.width(112.dp).height(76.dp).testTag("layout-preview-${layout.id}"),
update = { it.update(layout, role) })
}
internal class InputLayoutPreviewView(context: Context) : View(context) {
private val renderer = InputSurfaceView(context)
private var sourceHeight = 563
fun update(layout: SavedInputLayout, role: InputRole) {
sourceHeight = if (role == InputRole.PRIMARY) 563 else 870
renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY))
renderer.layout(0, 0, 1000, sourceHeight)
renderer.showLayout(layout.copy(style = layout.style.copy(opacity = 100)))
renderer.updateCustomLayout(layout.elements)
renderer.updateStyle(layout.style.copy(opacity = 100))
renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY))
renderer.layout(0, 0, 1000, sourceHeight)
contentDescription = layout.name
@@ -30,4 +65,28 @@ internal class InputLayoutPreviewView(context: Context) : View(context) {
}
}
@Composable
internal fun InputColorRow(host: MenuHost, value: Int?, onPick: (Int?) -> Unit) {
val open = host.open == "layout-color"
val tints = listOf<Pair<Int?, Int>>(null to R.string.ctrl_tint_gray) + ControllerPrefs.tints
SettingsRow(stringResource(R.string.ctrl_color), null, highlighted = open) {
Box {
ValueChip(tints.firstOrNull { it.first == value }?.second?.let { stringResource(it) }
?: stringResource(R.string.ctrl_custom), open, modifier = Modifier.testTag("setting-layout-color")) {
host.open = if (open) null else "layout-color"
}
AnchoredMenu(open, onDismiss = { if (host.open == "layout-color") host.open = null }, title = stringResource(R.string.ctrl_color)) { firstItemFocus ->
tints.forEachIndexed { index, (color, name) ->
MenuItem(stringResource(name), checked = value == color, leading = {
Box(Modifier.size(14.dp).background(Color(color ?: GRAY_SWATCH), CircleShape).border(1.dp, Color.White.copy(alpha = .35f), CircleShape))
}, focusRequester = if (index == 0) firstItemFocus else null) {
onPick(color)
host.open = null
}
}
}
}
}
}
private const val GRAY_SWATCH = 0xFF26292E.toInt()
@@ -0,0 +1,81 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.content.SharedPreferences
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import androidx.compose.ui.platform.testTag
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
@Composable
internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (InputRole?) -> Unit = {}, onEdit: () -> Unit = {}, track: (String) -> Modifier = { Modifier }) {
val context = LocalContext.current
var library by remember { mutableStateOf(InputLibraries.read(context)) }
var expanded by remember { mutableStateOf(false) }
var naming by remember { mutableStateOf(false) }
var failure by remember { mutableStateOf<String?>(null) }
DisposableEffect(context) {
val preferences = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == "library") library = InputLibraries.read(context) }
preferences.registerOnSharedPreferenceChangeListener(listener)
onDispose { preferences.unregisterOnSharedPreferenceChangeListener(listener) }
}
fun update(role: InputRole?, change: (InputLibrary) -> InputLibrary) {
runCatching { InputLibraries.update(context, change) }.onSuccess { library = it; onChanged(role) }
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
}
val selection = library.selection(desktop)
val mixed = selection.parts.isNotEmpty()
val active = library.profile(library.activeId(desktop))
val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.input_quick_auto, if (desktop) library.profile(library.desktop).name else library.profile(library.steam).name)) +
library.profiles.map { it.id to it.name } + if (mixed) listOf("mixed" to stringResource(R.string.input_quick_mixed, active.name)) else emptyList()
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.weight(1f).focusRow { expanded = !expanded }.padding(14.dp).testTag("input-profile-expand"),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Text(if (expanded) "▾" else "▸", color = MaterialTheme.colorScheme.onSurface)
Text(stringResource(R.string.input_profile), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface)
}
Box(Modifier.padding(end = 14.dp).widthIn(max = 280.dp)) {
ChoiceChip(host, "input-profile", stringResource(R.string.input_profile), profiles, if (mixed) "mixed" else selection.profile,
modifier = track("input-profile")) { id -> if (id != "mixed") update(null) { it.selectProfile(desktop, id) } }
}
}
if (expanded) Surface(
modifier = Modifier.fillMaxWidth().padding(start = 18.dp, end = 12.dp, bottom = 14.dp).testTag("input-profile-parts"),
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.primary.copy(alpha = .08f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = .35f)),
) {
Column(Modifier.padding(vertical = 6.dp)) {
for (role in InputRole.entries) {
val options = library.bindings.filter { binding ->
if (role == InputRole.PHYSICAL) binding.physical
else !binding.physical && library.layouts.any { it.id == binding.layoutId && it.supports(role) }
}.map { it.id to it.name }
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, library.activePart(desktop, role).bindings,
chipModifier = track("input-part-${role.name}")) { id -> update(role) { it.selectPart(desktop, role, id) } }
}
if (mixed) SecondaryButton(stringResource(R.string.input_save_combination)) { naming = true }
ActionRow(stringResource(R.string.input_settings), null, stringResource(R.string.ctrl_edit), onEdit,
modifier = track("input-settings").testTag("input-profile-edit"))
}
}
if (naming) {
var name by remember { mutableStateOf("") }
AlertDialog(onDismissRequest = { naming = false }, title = { Text(stringResource(R.string.input_save_combination)) },
text = { OutlinedTextField(name, { name = it.take(80) }, singleLine = true, label = { Text(stringResource(R.string.input_name)) }) },
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { it.saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
dismissButton = { PadTextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) } })
}
failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) },
text = { Text(message) }, confirmButton = { PadTextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) }
}
@@ -1,10 +1,18 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import android.util.DisplayMetrics
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.focus.focusRequester
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
@@ -12,85 +20,142 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/** The in-game Remap buttons page. */
@Composable
fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit, desktop: Boolean = false) {
fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit) {
val context = LocalContext.current
val activity = context.findActivity() as? com.droiddeck.launcher.SessionActivity
val target = activity?.inputEditorDisplay(InputRole.SECONDARY)
if (activity != null && target != null && target.displayId != activity.window.decorView.display?.displayId) {
InputDisplayContent(activity, target, onBack) { InputSettingsPane(onBack, onChanged, desktop) }
} else Dialog(onDismissRequest = onBack, properties = DialogProperties(usePlatformDefaultWidth = false)) {
InputSettingsPane(onBack, onChanged, desktop)
InputDisplayContent(activity, target, onBack) { InputSettingsPane(onBack, onChanged) }
} else InputSettingsWindow(onBack, onChanged)
}
@Composable
private fun InputSettingsWindow(onBack: () -> Unit, onChanged: () -> Unit) {
Dialog(onDismissRequest = onBack, properties = DialogProperties(usePlatformDefaultWidth = false)) {
InputSettingsPane(onBack, onChanged)
}
}
@Composable
private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit, desktop: Boolean) {
private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) {
var editingSurface by remember { mutableStateOf(false) }
val window = (androidx.compose.ui.platform.LocalView.current.parent as? androidx.compose.ui.window.DialogWindowProvider)?.window
DisposableEffect(window, editingSurface) {
window?.setDimAmount(if (editingSurface) 0f else .32f)
onDispose { }
}
BoxWithConstraints(Modifier.fillMaxSize().systemBarsPadding().padding(8.dp)) {
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < NarrowPaneWidth)) {
Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {
InputSettingsPage(onBack, onChanged, remapOnly = true, desktop = desktop)
Surface(Modifier.fillMaxSize(), color = if (editingSurface) androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) {
InputSettingsPage(onBack, onChanged, onSurfaceEditing = { editingSurface = it })
}
}
}
}
private enum class InputPage { HOME, REMAP }
private data class InputBindingEdit(val preset: String, val control: InputControl, val key: PhysicalInputKey? = null)
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE }
private data class InputBindingEdit(val preset: String, val control: InputControl, val element: InputSurfaceElement? = null, val key: PhysicalInputKey? = null, val click: Boolean = false)
private data class InputNameRequest(val title: Int, val initial: String, val sources: List<Pair<String, String>> = emptyList(),
val source: String = "", val offerSharing: Boolean = false, val save: (String, String, Boolean) -> Unit)
private data class InputConfirmation(val title: String, val detail: String, val action: () -> Unit)
private data class InputReuseRequest(val name: String, val layoutOnly: Boolean, val apply: (Boolean) -> Unit)
/** Settings › Controller: the in-game Controller page for the default, or with [remapOnly] just the physical controller's buttons. */
@Composable
fun InputSettingsPage(onBack: () -> Unit, onChanged: () -> Unit = {}, embedded: Boolean = false, onSurfaceEditing: (Boolean) -> Unit = {},
remapOnly: Boolean = false, desktop: Boolean = false) {
fun InputSettingsPage(onBack: () -> Unit, onChanged: () -> Unit = {}, embedded: Boolean = false, onSurfaceEditing: (Boolean) -> Unit = {}) {
CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onBackground) {
InputSettingsContent(onBack, onChanged, embedded, onSurfaceEditing, remapOnly, desktop)
InputSettingsContent(onBack, onChanged, embedded, onSurfaceEditing)
}
}
@Composable
private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embedded: Boolean, onSurfaceEditing: (Boolean) -> Unit,
remapOnly: Boolean, desktop: Boolean) {
private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embedded: Boolean, onSurfaceEditing: (Boolean) -> Unit) {
val context = LocalContext.current
val host = rememberMenuHost()
var library by remember { mutableStateOf(InputLibraries.read(context)) }
var page by remember { mutableStateOf(if (remapOnly) InputPage.REMAP else InputPage.HOME) }
var page by remember { mutableStateOf(InputPage.HOME) }
var bindingsTab by remember { mutableIntStateOf(0) }
var profileId by remember { mutableStateOf(InputProfile.GAME) }
var role by remember { mutableStateOf(InputRole.PHYSICAL) }
var edit by remember { mutableStateOf<InputBindingEdit?>(null) }
var naming by remember { mutableStateOf<InputNameRequest?>(null) }
var confirmation by remember { mutableStateOf<InputConfirmation?>(null) }
var reuse by remember { mutableStateOf<InputReuseRequest?>(null) }
var capture by remember { mutableStateOf(false) }
var surface by remember { mutableStateOf<Triple<String, String, String>?>(null) }
var revision by remember { mutableIntStateOf(0) }
LaunchedEffect(surface) { onSurfaceEditing(surface != null) }
var surface by remember { mutableStateOf(false) }
LaunchedEffect(surface) { onSurfaceEditing(surface) }
DisposableEffect(Unit) { onDispose { onSurfaceEditing(false) } }
var managingLayout by remember { mutableStateOf<SavedInputLayout?>(null) }
var exporting by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) }
val scope = rememberCoroutineScope()
val controller = rememberControllerSettings()
fun changed() { library = InputLibraries.read(context); revision++; onChanged() }
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
.onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess
fun go(next: InputPage) { page = next; host.open = null }
fun back() {
when {
edit != null -> edit = null
page == InputPage.REMAP && !remapOnly -> go(InputPage.HOME)
else -> onBack()
page == InputPage.HOME -> onBack()
page == InputPage.PROFILE -> go(InputPage.HOME)
page == InputPage.SOURCE -> go(InputPage.PROFILE)
else -> go(InputPage.SOURCE)
}
}
BackHandler(enabled = !embedded || page != InputPage.HOME || edit != null, onBack = ::back)
val profile = library.profile(library.activeId(desktop))
val preset = library.preset(library.activePart(desktop, InputRole.PHYSICAL).bindings)
val profile = library.profile(profileId)
val preset = library.preset(profile.binding(role))
val layout = library.layout(profileId, role)
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
val target = role
scope.launch {
val raw = withContext(Dispatchers.IO) { readLayoutFile(context, uri) }
val metrics = inputDisplayMetrics(context, target)
val imported = raw?.let { InputLayoutFile.import(context, it, layoutFileName(context, uri) ?: context.getString(R.string.ctrl_layout),
if (target == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY, layout?.style ?: InputSurfaceStyle(),
metrics.widthPixels, metrics.heightPixels, metrics.density) }
if (imported == null) error = context.getString(R.string.input_layout_import_failed)
else if (update { it.withLayout(imported.first).withPreset(imported.second).chooseLayout(profileId, target, imported.first.id) }) go(InputPage.SOURCE)
}
}
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri ->
val text = exporting
exporting = null
if (uri != null && text != null) scope.launch {
val saved = withContext(Dispatchers.IO) { runCatching { context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(text.toByteArray()) } != null }.getOrDefault(false) }
if (!saved) error = context.getString(R.string.input_save_failed)
}
}
fun rename(title: Int, name: String, save: (String) -> Unit) {
naming = InputNameRequest(title, name) { value, _, _ -> save(value) }
}
fun newProfile(copy: Boolean) {
naming = InputNameRequest(if (copy) R.string.input_copy_profile else R.string.input_new_profile,
if (copy) profile.name else "", library.profiles.map { it.id to it.name }, profileId, offerSharing = true) { name, source, shared ->
val id = newInputId()
if (update { it.duplicateProfile(source, name, id, sharePhysical = shared) }) { profileId = id; go(InputPage.PROFILE) }
}
}
fun editPart(nextRole: InputRole) { role = nextRole; bindingsTab = 0; go(InputPage.SOURCE) }
val pageFocus = remember { androidx.compose.ui.focus.FocusRequester() }
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
var settled by remember { mutableStateOf(false) }
LaunchedEffect(page, edit != null, surface) {
LaunchedEffect(page, role, profileId, edit != null, surface) {
if (!settled) { settled = true; return@LaunchedEffect }
if (surface != null || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
if (surface || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect
repeat(2) { withFrameNanos { } }
runCatching { pageFocus.requestFocus() }
}
@@ -98,46 +163,70 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
Box(Modifier.focusRequester(pageFocus).focusGroup()) {
if (editing != null) {
val b = library.preset(editing.preset)
val current = editing.key?.let { k -> b.keys.firstOrNull { it.key == k }?.action ?: InputAction.Disabled }
var elementProperties by remember(editing) { mutableStateOf(editing.element) }
val current = editing.element?.let { if (editing.click) b.clickAction(it) else b.action(it) }
?: editing.key?.let { k -> b.keys.firstOrNull { it.key == k }?.action ?: InputAction.Disabled }
?: b.controls[editing.control] ?: InputAction.Native()
InputActionEditor(editing.control, current, editing.key?.label ?: editing.control.label,
onBack = { edit = null }, nativeTargets = editing.key == null, detail = stringResource(R.string.input_remap_buttons), onSave = { action ->
if (update { l -> l.withPreset(when {
InputActionEditor(editing.control, current, if (editing.click) stringResource(R.string.input_click_name, editing.element!!.name)
else editing.element?.name ?: editing.key?.label ?: editing.control.label,
properties = { action -> if (!editing.click) elementProperties?.let { e -> InputElementProperties(e, action) { elementProperties = it } } },
onBack = { edit = null }, element = editing.element, nativeTargets = editing.key == null, click = editing.click,
detail = if (library.usersOfBindings(b.id).size > 1) stringResource(R.string.input_shared_detail, b.name, library.usersOfBindings(b.id).size)
else "${profile.name} · ${roleLabel(role)}", onSave = { action ->
if (update { l ->
val geometry = if (!editing.click && elementProperties != null && layout != null) l.withLayout(layout.copy(elements = layout.elements.map {
if (it.id == elementProperties!!.id) elementProperties!!.copy(name = elementProperties!!.name.trim().ifBlank { it.name }) else it
})) else l
geometry.withPreset(when {
editing.element != null && editing.click -> b.copy(clicks = b.clicks + (editing.element.id to action))
editing.element != null -> b.copy(elements = b.elements + (editing.element.id to action))
editing.key != null -> b.copy(keys = b.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action))
else -> b.copy(controls = b.controls + (editing.control to action))
}) }) edit = null
})
} else if (surface == null) key(page) {
} else if (!surface) key(page, profileId, role) {
SettingsPage(host, title = when (page) {
InputPage.HOME -> if (embedded) null else stringResource(R.string.setup_controller)
InputPage.REMAP -> stringResource(R.string.input_remap_buttons)
}, onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
InputPage.PROFILE -> profile.name
InputPage.SOURCE -> roleLabel(role)
InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts)
InputPage.REUSE -> stringResource(R.string.input_use_settings_from)
}, eyebrow = when (page) {
InputPage.SOURCE -> profile.name
InputPage.LAYOUTS, InputPage.REUSE -> "${profile.name} · ${roleLabel(role)}"
else -> null
},
onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
when (page) {
InputPage.HOME -> {
SettingsGroup(stringResource(R.string.input_default_profiles)) {
ChoiceRow(host, "auto-desktop", stringResource(R.string.input_desktop_mode), null,
library.profiles.map { it.id to it.name }, library.desktop) { id -> update { it.copy(desktop = id) } }
ChoiceRow(host, "auto-game", stringResource(R.string.input_game_mode), null,
library.profiles.map { it.id to it.name }, library.steam) { id -> update { it.copy(steam = id) } }
for (desktop in listOf(true, false)) {
val selection = library.selection(desktop)
if (selection.profile != InputProfiles.AUTO || selection.parts.isNotEmpty()) InputHint(stringResource(R.string.input_quick_override_hint,
stringResource(if (desktop) R.string.input_desktop_mode else R.string.input_game_mode)))
}
}
if (InputLibraries.hasPendingScreenKeyMigration(context)) InputHint(stringResource(R.string.input_import_failed))
if (InputLibraries.hasLibraryRecovery(context)) InputHint(stringResource(R.string.input_library_recovered))
DefaultControlsGroup(host, revision, onEdit = { surface = it }, onChanged = ::changed,
onFailure = { error = it.message ?: context.getString(R.string.input_save_failed) })
SettingsGroup(stringResource(R.string.drawer_page_controller)) {
var padType by remember { mutableStateOf(SessionPrefs.steamController(context)) }
ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), null,
listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam),
SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4),
SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)),
padType) { SessionPrefs.setSteamController(context, it); padType = it; onChanged() }
if (library.profiles.any { it.id.startsWith("migrated.screenkeys.") }) Text(stringResource(R.string.input_imported_keys_hint),
Modifier.padding(16.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
SettingsGroup(stringResource(R.string.input_profiles)) {
for (p in library.profiles) InputNavigationRow(p.name, when {
p.id == library.steam && p.id == library.desktop -> stringResource(R.string.input_default_both)
p.id == library.steam -> stringResource(R.string.input_default_game)
p.id == library.desktop -> stringResource(R.string.input_default_desktop)
else -> null
}, Modifier.testTag("input-profile-${p.id}")) { profileId = p.id; go(InputPage.PROFILE) }
PadTextButton(onClick = { newProfile(false) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_profile)) }
}
SettingsGroup(stringResource(R.string.input_device_settings)) {
ToggleRow(host, "controller-rumble", stringResource(R.string.ctrl_rumble), null, controller.rumble) { ControllerPrefs.setRumble(context, it); onChanged() }
ChoiceRow(host, "controller-dead-zone", stringResource(R.string.ctrl_dead_zone), null, ControllerPrefs.deadZones.map { it to stringResource(R.string.ctrl_percent, it) }, controller.deadZone) { ControllerPrefs.setDeadZone(context, it); onChanged() }
ToggleRow(host, "controller-joycon-vr", stringResource(R.string.ctrl_joycon_vr), null, controller.joyConVr) { ControllerPrefs.setJoyConVr(context, it); onChanged() }
ActionRow(stringResource(R.string.input_remap_buttons), null, stringResource(R.string.ctrl_edit), { go(InputPage.REMAP) },
modifier = Modifier.testTag("input-remap"))
}
val games = remember(revision) { ControlsChoice.games(context) }
if (games.isNotEmpty()) SettingsGroup(stringResource(R.string.osc_games_own)) {
for (game in games) ActionRow(game.name, game.layout, stringResource(R.string.osc_use_default), {
ControlsChoice.useDefault(context, game.id); changed()
}, modifier = Modifier.testTag("osc-use-default-${game.id}"))
ToggleRow(host, "controller-joycon-vr", stringResource(R.string.ctrl_joycon_vr), stringResource(R.string.ctrl_joycon_vr_hint), controller.joyConVr) { ControllerPrefs.setJoyConVr(context, it); onChanged() }
}
SettingsGroup(stringResource(R.string.shortcuts_title)) { PhysicalShortcutRows() }
SettingsGroup(stringResource(R.string.input_latency)) {
@@ -155,70 +244,189 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
} }, confirmButton = { PadTextButton(onClick = { reading = false }) { Text(stringResource(R.string.common_close)) } })
}
}
InputPage.REMAP -> {
SettingsGroup(stringResource(R.string.input_physical)) {
Box(Modifier.padding(horizontal = 12.dp, vertical = 12.dp)) {
SheetChips(listOf(stringResource(R.string.input_buttons), stringResource(R.string.input_axes), stringResource(R.string.input_extra_keys)), bindingsTab) { bindingsTab = it }
InputPage.PROFILE -> {
SettingsGroup(stringResource(R.string.input_profile_controls)) {
for (r in InputRole.entries) InputNavigationRow(roleLabel(r),
if (r == InputRole.PHYSICAL) stringResource(R.string.input_physical_hint) else library.layout(profileId, r)?.name,
Modifier.testTag("input-part-${r.name.lowercase()}"), leading = {
library.layout(profileId, r)?.let { InputLayoutThumbnail(it, r) }
}) { editPart(r) }
}
Spacer(Modifier.height(16.dp))
Actions {
SecondaryButton(stringResource(R.string.input_rename)) { rename(R.string.input_rename, profile.name) { name -> update { it.withProfile(profile.copy(name = name)) } } }
SecondaryButton(stringResource(R.string.input_copy_profile)) { newProfile(true) }
SecondaryButton(stringResource(R.string.input_reset_actions)) {
confirmation = InputConfirmation(context.getString(R.string.input_reset_actions), context.getString(R.string.input_reset_profile_detail, profile.name)) { update { it.resetProfile(profileId) } }
}
if (bindingsTab != 2) InputControlGrid(preset, InputControl.padControls.asList(), bindingsTab == 1) { edit = InputBindingEdit(preset.id, it) }
else {
for (b in preset.keys) {
InputNavigationRow(b.key.label, actionLabel(b.action)) { edit = InputBindingEdit(preset.id, InputControl.A, key = b.key) }
PadTextButton(onClick = { update { it.withPreset(preset.copy(keys = preset.keys - b)) } }) { Text(stringResource(R.string.input_remove_binding)) }
if (profileId !in listOf(InputProfile.GAME, InputProfile.DESKTOP)) SecondaryButton(stringResource(R.string.input_delete)) {
confirmation = InputConfirmation(context.getString(R.string.input_delete), context.getString(R.string.input_delete_profile_detail, profile.name)) {
if (update { it.removeProfile(profileId) }) { profileId = InputProfile.GAME; go(InputPage.HOME) }
}
InputNavigationRow(stringResource(R.string.input_capture), null) { capture = true }
}
val defaults = InputProfile.defaults(profile.base).bindings[InputRole.PHYSICAL].orEmpty()
if (preset.controls != defaults || preset.keys.isNotEmpty()) ActionRow(stringResource(R.string.input_reset_actions), null,
stringResource(R.string.hud_reset_button), { update { it.withPreset(preset.copy(controls = defaults, keys = emptyList())) } },
modifier = Modifier.testTag("input-remap-reset"))
}
}
InputPage.SOURCE -> {
if (role == InputRole.PRIMARY) SettingsGroup(stringResource(R.string.input_screen_visibility)) {
ChoiceRow(host, "controller-osc", stringResource(R.string.mode_osc), stringResource(R.string.input_visibility_shared),
listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
oscMode) { SessionPrefs.setOscMode(context, it); oscMode = it; onChanged() }
}
if (layout != null) SettingsGroup(stringResource(R.string.ctrl_layout)) {
if (layout.editable) InputNavigationRow(stringResource(R.string.input_edit_layout), layout.name, Modifier.testTag("input-surface-${role.name.lowercase()}")) { surface = true }
else InputHint(layout.name)
InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) }
if (layout.editable) {
InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } }
SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1,
format = { "$it%" }) { opacity -> update { it.withLayout(layout.copy(style = layout.style.copy(opacity = opacity))) } }
for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null,
button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } }
}
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
}
SettingsGroup(stringResource(R.string.input_assign_actions)) {
val users = library.usersOfBindings(preset.id)
if (users.size > 1) InputHint(stringResource(R.string.input_shared_with, users.filterNot { it.id == profileId }.joinToString { it.name }))
val elements = layout?.takeIf { it.editable }?.elements
if (elements != null) {
if (elements.isEmpty()) InputHint(stringResource(R.string.input_empty_elements))
for (e in elements) {
InputNavigationRow(e.name, actionLabel(preset.action(e)), Modifier.testTag("input-element-${e.id}")) { edit = InputBindingEdit(preset.id, e.control, e) }
if (e.hasClick) InputNavigationRow(stringResource(R.string.input_click_name, e.name), actionLabel(preset.clickAction(e)), Modifier.testTag("input-click-${e.id}")) { edit = InputBindingEdit(preset.id, InputControl.A, e, click = true) }
}
} else {
Box(Modifier.padding(horizontal = 12.dp, vertical = 12.dp)) {
SheetChips(listOf(stringResource(R.string.input_buttons), stringResource(R.string.input_axes)) +
if (preset.physical) listOf(stringResource(R.string.input_extra_keys)) else emptyList(), bindingsTab) { bindingsTab = it }
}
val controls = InputControl.padControls.asList()
if (bindingsTab != 2) InputControlGrid(preset, controls, bindingsTab == 1) { edit = InputBindingEdit(preset.id, it) }
else {
for (b in preset.keys) {
InputNavigationRow(b.key.label, actionLabel(b.action)) { edit = InputBindingEdit(preset.id, InputControl.A, key = b.key) }
PadTextButton(onClick = { update { it.withPreset(preset.copy(keys = preset.keys - b)) } }) { Text(stringResource(R.string.input_remove_binding)) }
}
InputNavigationRow(stringResource(R.string.input_capture), stringResource(R.string.input_capture_hint)) { capture = true }
}
}
}
SettingsGroup(stringResource(R.string.input_reuse)) {
InputNavigationRow(stringResource(R.string.input_use_settings_from), stringResource(R.string.input_reuse_hint)) { go(InputPage.REUSE) }
if (library.usersOfBindings(preset.id).size > 1 || layout?.let { it.editable && library.usersOfLayout(it.id).size > 1 } == true)
InputNavigationRow(stringResource(R.string.input_make_independent), stringResource(R.string.input_independent_hint), Modifier.testTag("input-make-independent")) {
update { it.usePart(profileId, role, profileId, shared = false) }
}
}
}
InputPage.LAYOUTS -> {
InputHint(stringResource(R.string.input_layout_geometry_hint))
SettingsGroup(stringResource(R.string.input_saved_layouts)) {
var showOther by remember { mutableStateOf(false) }
val available = library.layouts.filter { it.supports(role) }
val other = available.filter { saved -> !saved.id.startsWith("builtin.") && saved.id != layout?.id &&
library.usersOfLayout(saved.id).isEmpty() && library.bindings.none { it.layoutId == saved.id && library.selectedBindings(it.id) } }
for (saved in available.filter { showOther || it !in other }) {
InputLayoutRow(saved, role, if (saved.id == layout?.id) stringResource(R.string.input_current_layout) else null,
onManage = { managingLayout = saved }) {
reuse = InputReuseRequest(saved.name, layoutOnly = true) { shared -> if (update { it.useLayout(profileId, role, saved.id, shared) }) go(InputPage.SOURCE) }
}
}
if (other.isNotEmpty()) PadTextButton(onClick = { showOther = !showOther }, modifier = Modifier.padding(8.dp)) {
Text(stringResource(if (showOther) R.string.input_hide_other_layouts else R.string.input_other_layouts, other.size))
}
Row {
PadTextButton(onClick = { naming = InputNameRequest(R.string.input_new_layout, "") { name, _, _ ->
val created = SavedInputLayout(newInputId(), name, screen = if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY)
if (update { it.withLayout(created).useLayout(profileId, role, created.id, shared = true) }) { go(InputPage.SOURCE); surface = true }
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_layout)) }
PadTextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "application/octet-stream", "*/*")) },
modifier = Modifier.padding(8.dp).testTag("input-layout-import")) { Text(stringResource(R.string.boot_movie_import)) }
}
}
}
InputPage.REUSE -> {
InputHint(stringResource(R.string.input_reuse_explanation, roleLabel(role)))
SettingsGroup(stringResource(R.string.input_profiles)) {
for (p in library.profiles.filterNot { it.id == profileId }) InputNavigationRow(p.name, library.layout(p.id, role)?.name) {
reuse = InputReuseRequest(p.name, layoutOnly = false) { shared -> if (update { it.usePart(profileId, role, p.id, shared) }) go(InputPage.SOURCE) }
}
}
}
}
}
}
}
managingLayout?.let { saved -> AlertDialog(onDismissRequest = { managingLayout = null }, title = { Text(saved.name) },
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Text(stringResource(R.string.input_layout_count, saved.elements.size))
SecondaryButton(stringResource(R.string.input_rename)) {
managingLayout = null
rename(R.string.input_rename_layout, saved.name) { name -> update { it.withLayout(saved.copy(name = name)) } }
}
val exported = remember(saved, library) {
val metrics = inputDisplayMetrics(context, if (saved.screen == InputLayoutScreen.SECONDARY) InputRole.SECONDARY else InputRole.PRIMARY)
InputLayoutFile.export(saved, library.bindings.firstOrNull { it.id == preset.id && it.layoutId == saved.id }
?: library.bindings.firstOrNull { it.layoutId == saved.id }, metrics.widthPixels, metrics.heightPixels)
}
if (exported != null) SecondaryButton(stringResource(R.string.screen_key_layout_export)) {
managingLayout = null
exporting = exported
exporter.launch(InputLayoutFile.fileName(saved))
}
val used = library.usersOfLayout(saved.id).isNotEmpty() || library.bindings.any { it.layoutId == saved.id && library.selectedBindings(it.id) }
if (!used && saved.editable) SecondaryButton(stringResource(R.string.input_delete)) {
managingLayout = null
confirmation = InputConfirmation(context.getString(R.string.input_delete), context.getString(R.string.input_delete_layout_detail, saved.name)) { update { it.removeLayout(saved.id) } }
}
} }, confirmButton = { PadTextButton(onClick = { managingLayout = null }) { Text(stringResource(R.string.common_close)) } }) }
if (capture) InputCaptureDialog(onDismiss = { capture = false }) { capture = false; edit = InputBindingEdit(preset.id, InputControl.A, key = it) }
surface?.let { (profileId, layoutId, bindingsId) ->
val name = library.layouts.firstOrNull { it.id == layoutId }?.name.orEmpty()
InputSurfaceDialog(profileId, onDismiss = { surface = null; changed() }, onChanged = ::changed, role = InputRole.PRIMARY,
layoutId = layoutId, bindingsId = bindingsId, scope = stringResource(R.string.osc_scope_default, name))
}
if (surface) InputSurfaceDialog(profileId, onDismiss = { surface = false; library = InputLibraries.read(context) }, onChanged = {
library = InputLibraries.read(context); onChanged()
}, role = role, layoutId = layout?.id, bindingsId = preset.id)
naming?.let { request -> key(request) { InputNameDialog(request) { naming = null } } }
reuse?.let { request -> key(request) { InputReuseDialog(request) { reuse = null } } }
confirmation?.let { request -> AlertDialog(onDismissRequest = { confirmation = null }, title = { Text(request.title) },
text = { Text(request.detail) }, confirmButton = { PadTextButton(onClick = { confirmation = null; request.action() }) { Text(stringResource(R.string.common_ok)) } },
dismissButton = { PadTextButton(onClick = { confirmation = null }) { Text(stringResource(R.string.common_cancel)) } }) }
error?.let { message -> AlertDialog(onDismissRequest = { error = null }, title = { Text(stringResource(R.string.input_save_failed)) },
text = { Text(message) }, confirmButton = { PadTextButton(onClick = { error = null }) { Text(stringResource(R.string.common_ok)) } }) }
}
/** The in-game "On-screen controls" group, for games without a layout of their own. */
@Composable
private fun DefaultControlsGroup(host: MenuHost, revision: Int, onEdit: (Triple<String, String, String>) -> Unit, onChanged: () -> Unit,
onFailure: (Throwable) -> Unit) {
val context = LocalContext.current
val options = remember(revision) { ControlsChoice.options(context, null, steamMode = true) }
val choice = remember(revision) { ControlsChoice.current(context, null, steamMode = true) }
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
var touch by remember { mutableStateOf(SessionPrefs.touchMode(context)) }
var below by remember { mutableStateOf(SessionPrefs.unfoldedControls(context)) }
SettingsGroup(stringResource(R.string.osc_group_for, stringResource(R.string.osc_default))) {
LayoutChoiceRow(host, "osc-layout", options, choice, onPick = { id ->
runCatching { ControlsChoice.choose(context, null, id, desktop = false) }.onSuccess { onChanged() }.onFailure(onFailure)
}, onDelete = { id -> runCatching { ControlsChoice.delete(context, id) }.onSuccess { onChanged() }.onFailure(onFailure) })
if (choice != GameControls.STEAM) ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), {
host.open = null
ControlsChoice.editTarget(context, null, desktop = false)?.let(onEdit)
}, modifier = Modifier.testTag("osc-edit"))
ControlsVisibilityRow(host, oscMode, steam = true) {
SessionPrefs.setOscMode(context, it)
oscMode = it
onChanged()
private fun InputNameDialog(request: InputNameRequest, onDismiss: () -> Unit) {
var name by remember { mutableStateOf(request.initial) }
var source by remember { mutableStateOf(request.source) }
var shared by remember { mutableStateOf(false) }
val host = rememberMenuHost()
AlertDialog(onDismissRequest = onDismiss, title = { Text(stringResource(request.title)) }, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
OutlinedTextField(name, { name = it.take(80) }, label = { Text(stringResource(R.string.input_name)) }, singleLine = true, modifier = Modifier.testTag("input-name"))
if (request.sources.isNotEmpty()) ChoiceRow(host, "input-copy-source", stringResource(R.string.input_start_from), null, request.sources, source) { source = it }
if (request.offerSharing) {
Row(Modifier.fillMaxWidth().focusRow(role = Role.Checkbox, checked = shared) { shared = !shared }.testTag("input-share-physical"), verticalAlignment = Alignment.CenterVertically) {
Checkbox(shared, null)
Text(stringResource(R.string.input_share_physical))
}
Text(stringResource(R.string.input_new_independent_hint), style = MaterialTheme.typography.bodySmall)
}
ChoiceRow(host, "touch", stringResource(R.string.input_touches), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_mouse),
SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures),
SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), touch) { SessionPrefs.setTouchMode(context, it); touch = it; onChanged() }
ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls), null, below) {
SessionPrefs.setUnfoldedControls(context, it); below = it; onChanged()
} }, confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { request.save(name.trim(), source, shared); onDismiss() }) { Text(stringResource(R.string.gesture_save_changes)) } },
dismissButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } })
}
@Composable
private fun InputReuseDialog(request: InputReuseRequest, onDismiss: () -> Unit) {
var shared by remember { mutableStateOf(false) }
AlertDialog(onDismissRequest = onDismiss, title = { Text(request.name) }, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
Text(stringResource(if (request.layoutOnly) R.string.input_reuse_layout_detail else R.string.input_reuse_part_detail))
for (link in listOf(false, true)) Row(Modifier.fillMaxWidth().focusRow(role = Role.RadioButton, checked = shared == link) { shared = link }, verticalAlignment = Alignment.CenterVertically) {
RadioButton(shared == link, null)
Text(stringResource(if (link) R.string.input_keep_shared else R.string.input_independent_copy))
}
}
} }, confirmButton = { PadTextButton(onClick = { request.apply(shared); onDismiss() }) { Text(stringResource(R.string.common_ok)) } },
dismissButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } })
}
@Composable
@@ -241,22 +449,10 @@ private fun InputControlGrid(preset: SavedInputBindings, available: List<InputCo
}
@Composable
internal fun ControlsVisibilityRow(host: MenuHost, mode: String, steam: Boolean, modifier: Modifier = Modifier, onPick: (String) -> Unit) {
ChoiceRow(host, "osc-show", stringResource(R.string.osc_show), null, controlsVisibilityOptions(steam), mode, chipModifier = modifier, onPick = onPick)
}
@Composable
internal fun controlsVisibilityOptions(steam: Boolean): List<Pair<String, String>> = buildList {
add(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto))
add(SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always))
if (steam) add(SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.osc_steam_shortcuts_only))
add(SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
}
@Composable
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, onClick: () -> Unit) {
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
Row(modifier.fillMaxWidth().focusRow(RoundedCornerShape(0.dp), onClick = onClick).heightIn(min = 64.dp).padding(14.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
leading?.invoke()
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.titleMedium)
if (detail != null) Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -265,6 +461,43 @@ private fun InputNavigationRow(title: String, detail: String?, modifier: Modifie
}
}
internal fun quickButtonLabel(button: InputCommand) = when (button) {
InputCommand.STEAM -> R.string.ctrl_steam_button
InputCommand.QUICK_ACCESS -> R.string.ctrl_qam_button
else -> R.string.ctrl_keyboard_button
}
@Suppress("DEPRECATION")
internal fun inputDisplayMetrics(context: Context, role: InputRole): DisplayMetrics = DisplayMetrics().also { metrics ->
(context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputEditorDisplay(role)?.getRealMetrics(metrics)
?: metrics.setTo(context.resources.displayMetrics)
}
private fun readLayoutFile(context: Context, uri: Uri): String? = runCatching {
context.contentResolver.openInputStream(uri)?.use { input ->
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
if (out.size() > 1_000_000) return@use null
}
out.toString(Charsets.UTF_8.name())
}
}.getOrNull()
private fun layoutFileName(context: Context, uri: Uri): String? = runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0)?.substringBeforeLast('.')?.trim()?.takeIf { it.isNotEmpty() } else null
}
}.getOrNull()
@Composable
internal fun roleLabel(role: InputRole) = stringResource(when (role) {
InputRole.PHYSICAL -> R.string.input_physical; InputRole.PRIMARY -> R.string.input_primary; InputRole.SECONDARY -> R.string.input_secondary
})
@Composable
private fun InputHint(text: String) {
Text(text, Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
@@ -63,24 +63,40 @@ import com.droiddeck.launcher.session.SessionState
private data class SurfaceSnapshot(val elements: List<InputSurfaceElement>, val actions: Map<String, InputAction>,
val clicks: Map<String, InputAction>, val scale: Float, val aspect: Float)
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) {
private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale)
val ids = generator(1f).elements().map { it.id }.toSet()
fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) = generator(to).rescale(stored, generator(from))
fun reset(stored: List<InputSurfaceElement>) = generator(1f).regenerate(stored).associateBy { it.id }.let { placed -> stored.map { placed[it.id] ?: it } }
}
private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputBindings, val defaults: List<InputSurfaceElement>? = null,
private val defaultsFrame: Float = 0f, snap: Boolean = true) {
private val defaultsFrame: Float = 0f, private var gamepad: GamepadScaler? = null, snap: Boolean = true) {
val hasGamepad get() = gamepad != null
var elements by mutableStateOf(layout.elements)
var actions by mutableStateOf(preset.elements)
var clicks by mutableStateOf(preset.clicks)
var selected by mutableStateOf<String?>(null)
var toolsExpanded by mutableStateOf(false)
var toolsX by mutableFloatStateOf(.02f)
var toolsY by mutableFloatStateOf(.02f)
var snap by mutableStateOf(snap)
var popover by mutableStateOf<EditorPopover?>(null)
var confirmDiscard by mutableStateOf(false)
var adding by mutableStateOf(false)
var properties by mutableStateOf(false)
var clickProperties by mutableStateOf(false)
var history by mutableStateOf<List<SurfaceSnapshot>>(emptyList())
var layoutScale by mutableFloatStateOf(layout.scale)
var aspect by mutableFloatStateOf(layout.aspect)
private var scaleBase by mutableStateOf<Pair<List<InputSurfaceElement>, List<InputSurfaceElement>>?>(null)
private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
private var scaleValue by mutableIntStateOf(100)
val scale get() = if (scaleBase?.second == elements) scaleValue else 100
val positioned get() = defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) }?.takeIf { it != elements }
private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true
val scale get() = when {
scaleBase?.second == elements -> scaleValue
rescales -> (layoutScale * 100).roundToInt()
else -> 100
}
val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) })
?.takeIf { it != elements || rescales && layoutScale != 1f }
private fun refit(placed: List<InputSurfaceElement>, from: Float): List<InputSurfaceElement> {
if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed
@@ -90,71 +106,50 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } }
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float) {
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float, scaler: GamepadScaler? = gamepad) {
checkpoint()
elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed)
this.aspect = aspect
scaler?.let { gamepad = it }
}
fun scaleAll(percent: Int) {
val base = scaleBase?.takeIf { it.second == elements } ?: (elements to elements).also { checkpoint() }
elements = base.first.scaled(percent / 100f)
scaleValue = percent; scaleBase = base.first to elements
}
fun resetPositions() { positioned?.let { checkpoint(); elements = it } }
private val restored get() = defaults?.let { refit(it, defaultsFrame) }
private fun matches(defaults: List<InputSurfaceElement>, placed: List<InputSurfaceElement>) = defaults.size == placed.size && defaults.all { a ->
placed.any { e -> e.copy(x = a.x, y = a.y, width = a.width, height = a.height) == a &&
abs(e.x - a.x) < .002f && abs(e.y - a.y) < .002f && abs(e.width - a.width) < .002f && abs(e.height - a.height) < .002f }
}
val atDefaults get() = restored?.let { matches(it, elements) } == true
/** The kit's own controls are where the kit puts them, so only the added ones need saving. */
val kitAtDefaults get() = restored?.let { matches(it, elements.filter { e -> KitLayout.isKit(e.id) }) } == true
fun reset() {
val d = restored?.takeIf { !atDefaults } ?: return
checkpoint(); elements = d; selected = null
actions = actions.filterKeys { id -> KitLayout.bindsTo(id, d) }; clicks = clicks.filterKeys { id -> d.any { it.id == id } }
}
fun hiddenDefaults(): List<InputSurfaceElement> = defaults?.let { refit(it, defaultsFrame) }?.filter { d -> elements.none { it.id == d.id } }.orEmpty()
fun add(element: InputSurfaceElement) { checkpoint(); elements = elements + element; selected = element.id; popover = null }
fun remove(id: String) {
checkpoint(); elements = elements.filterNot { it.id == id }; selected = null
if (!KitLayout.isKit(id)) { actions = actions - id; clicks = clicks - id }
}
fun resizeSelected(factor: Float) {
val e = element ?: return
checkpoint()
val w = (e.width * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f); val h = (e.height * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val cx = e.x + e.width / 2; val cy = e.y + e.height / 2
elements = elements.map { if (it.id == e.id) e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded() else it }
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() }
val factor = percent / 100f
val pad = gamepad
elements = if (base.third > 0f && pad != null) {
layoutScale = factor
val others = base.first.filterNot { it.id in pad.ids }.scaled(factor / base.third).associateBy { it.id }
pad.rescale(base.first, base.third, factor).map { others[it.id] ?: it }
} else base.first.scaled(factor)
scaleValue = percent; scaleBase = Triple(base.first, elements, base.third)
}
fun resetPositions() { positioned?.let { checkpoint(); elements = it; if (rescales) layoutScale = 1f } }
fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e)
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
}
/** Offered when the layout being edited is shared: [create] makes the copy that Done then saves into, and [scope] describes it. */
/** Turns an edit of a shared layout into a copy for one game: [copy] adds it to the library being saved, [use] picks it once that save succeeded. */
class InputEditorSplit(val label: String, val scope: String, val copy: (InputLibrary, String, String) -> InputLibrary, val use: (String) -> Unit)
@Composable
fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null, scope: String? = null,
split: InputEditorSplit? = null) {
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) {
val context = LocalContext.current
val host = LocalInputActivity.current ?: context.findActivity() as? ComponentActivity
val library = remember { InputLibraries.read(context) }
val savedLayout = remember { library.layouts.first { it.id == (layoutId ?: library.profile(profile).parts.getValue(role).layout) } }
val savedBindings = remember { library.preset(bindingsId ?: library.profile(profile).binding(role)) }
val layoutUsers = library.usersOfLayout(savedLayout.id).size
var splitting by remember { mutableStateOf(false) }
val bindingUsers = library.usersOfBindings(savedBindings.id).size
val draft = remember {
val (display, metrics) = InputLibraries.primaryDisplay(context)
val gamepad = savedLayout.elements.takeIf { e -> e.any { it.id.startsWith("legacy:") } }?.let {
val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels)
GamepadScaler(display, w, h)
}
val defaults = InputLibraries.defaultPositions(context, library, savedLayout)
val start = if (OnScreenLayout.generated(savedLayout) && defaults != null) savedLayout.copy(elements = defaults.first +
OnScreenLayout.fit(savedLayout.elements, savedLayout.aspect.takeIf { it > 0f } ?: defaults.second, 1f, (defaults.second * 1000).roundToInt(), 1000, Rect()),
aspect = defaults.second) else savedLayout
SurfaceDraft(start, savedBindings, defaults?.first, defaults?.second ?: 0f, ControllerPrefs.snap(context))
SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context))
}
val manager = remember { context.getSystemService(DisplayManager::class.java) }
var revision by remember { mutableIntStateOf(0) }
var discard by remember { mutableStateOf(false) }
var failure by remember { mutableStateOf<String?>(null) }
val target = remember(revision, role) {
if (host is SessionActivity) host.inputEditorDisplay(role)
@@ -165,23 +160,15 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
}
}
val remote = target != null && target.displayId != host?.window?.decorView?.display?.displayId
fun leave() { if (draft.dirty) draft.confirmDiscard = true else onDismiss() }
fun leave() { if (draft.dirty) discard = true else onDismiss() }
fun save() {
runCatching {
val copy = split?.takeIf { splitting }
val (layoutTarget, bindingsTarget) = if (copy != null) newInputId() to newInputId() else savedLayout.id to savedBindings.id
InputLibraries.update(context) { saved ->
val latest = copy?.copy?.invoke(saved, layoutTarget, bindingsTarget) ?: saved
val l = latest.layouts.first { it.id == layoutTarget }
val p = latest.preset(bindingsTarget)
val generated = draft.kitAtDefaults && OnScreenLayout.generated(l.copy(elements = emptyList(), kitless = false))
val extras = draft.elements.filterNot { KitLayout.isKit(it.id) }
val edited = if (generated) l.copy(elements = extras, aspect = if (extras.isEmpty()) 0f else draft.aspect, scale = draft.layoutScale, kitless = false)
else l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale, kitless = draft.elements.none { KitLayout.isKit(it.id) })
latest.withLayout(edited).withPreset(p.copy(elements = draft.actions.filterKeys { id -> edited.element(id) != null },
clicks = draft.clicks.filterKeys { id -> edited.element(id)?.hasClick == true }))
InputLibraries.update(context) { latest ->
val l = latest.layouts.first { it.id == savedLayout.id }
val p = latest.preset(savedBindings.id)
latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } }))
}
copy?.use?.invoke(bindingsTarget)
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
}
DisposableEffect(manager) {
@@ -222,53 +209,56 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
androidx.compose.ui.graphics.Color.Transparent else MaterialTheme.colorScheme.surface) {
val element = draft.element
BackHandler { if (draft.properties) draft.properties = false else leave() }
val editorScope = split?.scope?.takeIf { splitting } ?: scope ?: if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name
val splitLabel = split?.label?.takeIf { !splitting }
val propertiesEditor: @Composable (InputSurfaceElement) -> Unit = { element ->
var properties by remember(element.id) { mutableStateOf(element) }
InputActionEditor(if (draft.clickProperties) InputControl.A else element.control,
if (draft.clickProperties) draft.clickAction(element) else draft.action(element),
if (draft.clickProperties) stringResource(R.string.input_click_name, element.name) else element.name,
onBack = { draft.properties = false }, element = element, click = draft.clickProperties,
properties = { action ->
if (!draft.clickProperties) InputElementProperties(properties, action) { properties = it }
}, detail = editorScope, onSave = { action ->
draft.checkpoint()
if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action)
draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it }
draft.properties = false
})
}
when {
(remote || target == null) && draft.properties && element != null -> propertiesEditor(element)
draft.properties && element != null -> {
var properties by remember(element.id) { mutableStateOf(element) }
InputActionEditor(if (draft.clickProperties) InputControl.A else element.control,
if (draft.clickProperties) draft.clickAction(element) else draft.action(element),
if (draft.clickProperties) stringResource(R.string.input_click_name, element.name) else element.name,
onBack = { draft.properties = false }, element = element, click = draft.clickProperties,
properties = { action ->
if (!draft.clickProperties) InputElementProperties(properties, action) { properties = it }
if (layoutUsers > 1) Text(stringResource(R.string.input_editor_shared, layoutUsers),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(bottom = 12.dp))
}, detail = if (bindingUsers > 1) stringResource(R.string.input_shared_detail, savedBindings.name, bindingUsers)
else "${library.profile(profile).name} · ${roleLabel(role)}", onSave = { action ->
draft.checkpoint()
if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action)
draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it }
draft.properties = false
})
}
target == null -> SettingsPage(rememberMenuHost(), savedLayout.name, ::leave) {
Text(stringResource(R.string.input_display_unavailable))
failure?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) }
if (draft.confirmDiscard) {
Text(stringResource(R.string.input_editor_discard), style = MaterialTheme.typography.titleSmall)
SecondaryButton(stringResource(R.string.input_keep_editing)) { draft.confirmDiscard = false }
SecondaryButton(stringResource(R.string.input_discard), onClick = onDismiss)
}
PrimaryButton(stringResource(R.string.input_editor_done)) { save() }
}
remote -> SettingsPage(rememberMenuHost(), stringResource(R.string.input_editor_remote), ::leave, lede = editorScope) {
splitLabel?.let { SecondaryButton(it, compact = true, modifier = Modifier.padding(horizontal = 8.dp).testTag("input-editor-split")) { splitting = true } }
SurfaceToolbar(draft, ::save, ::leave, onDismiss)
failure?.let { Text(it, Modifier.padding(horizontal = 8.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) }
remote -> SettingsPage(rememberMenuHost(), stringResource(R.string.input_editor_remote), ::leave,
lede = if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name) {
SurfaceToolbar(draft, ::save, ::leave)
SurfaceSelection(draft)
when (draft.popover) { EditorPopover.ADD -> AddRows(draft); EditorPopover.HIDDEN -> HiddenRows(draft); null -> Unit }
}
else -> Box(Modifier.fillMaxSize()) {
SurfaceCanvas(draft, transparent = host is SessionActivity && role == InputRole.PRIMARY)
EditorChrome(draft, editorScope, splitLabel, { splitting = true }, failure, ::save, ::leave, onDismiss)
if (draft.properties && element != null) Surface(Modifier.align(Alignment.CenterEnd).fillMaxHeight().fillMaxWidth(.44f),
color = MaterialTheme.colorScheme.surface, shadowElevation = 12.dp) {
propertiesEditor(element)
}
FloatingSurfaceTools(draft, ::save, ::leave)
}
}
}
}
if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column {
for (kind in InputElementKind.entries) PadTextButton(onClick = { draft.checkpoint()
val w = if (kind.control.dimensions == 2) .4f else .2f
val h = .3f
val name = context.getString(kind.label()) + " " + (draft.elements.count { it.kind == kind } + 1)
val element = InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name)
draft.elements = draft.elements + element; draft.selected = element.id
draft.adding = false; draft.toolsExpanded = false }) { Text(stringResource(kind.label())) }
} })
if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text(stringResource(R.string.input_editor_discard)) },
confirmButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_ok)) } },
dismissButton = { PadTextButton(onClick = { discard = false }) { Text(stringResource(R.string.common_cancel)) } })
failure?.let { AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) }, text = { Text(it) },
confirmButton = { PadTextButton(onClick = { failure = null }) { Text(stringResource(R.string.common_ok)) } }) }
}
@Composable
@@ -277,158 +267,70 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
update = { view ->
view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13))
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.isEnabled = !draft.properties && draft.popover == null && !draft.confirmDiscard
view.isEnabled = !draft.properties && !draft.adding
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h) }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) }
view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } }
})
}
private enum class EditorPopover { ADD, HIDDEN }
@Composable
private fun EditorBar(modifier: Modifier = Modifier, content: @Composable RowScope.() -> Unit) {
Surface(modifier, shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = .96f),
contentColor = MaterialTheme.colorScheme.onSurface, shadowElevation = 8.dp) {
Row(Modifier.horizontalScroll(rememberScrollState()).padding(6.dp), horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalAlignment = Alignment.CenterVertically, content = content)
}
}
/** The editor's tools over the canvas: one toolbar, a bar on the selected control, and the Add and Hidden lists. */
@Composable
private fun EditorChrome(draft: SurfaceDraft, scope: String, splitLabel: String?, onSplit: () -> Unit, failure: String?,
onSave: () -> Unit, onLeave: () -> Unit, onDiscard: () -> Unit) {
val context = LocalContext.current
private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) {
BoxWithConstraints(Modifier.fillMaxSize()) {
Column(Modifier.align(Alignment.TopCenter).padding(top = 10.dp).widthIn(max = maxWidth - 16.dp),
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) {
EditorBar(Modifier.testTag("input-editor-tools")) {
if (draft.confirmDiscard) {
Text(stringResource(R.string.input_editor_discard), Modifier.padding(horizontal = 8.dp), style = MaterialTheme.typography.titleSmall)
SecondaryButton(stringResource(R.string.input_keep_editing), compact = true) { draft.confirmDiscard = false }
PrimaryButton(stringResource(R.string.input_discard), compact = true, onClick = onDiscard)
} else {
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave)
SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() }
SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) {
draft.popover = if (draft.popover == EditorPopover.ADD) null else EditorPopover.ADD
val density = LocalDensity.current
val screenWidth = with(density) { maxWidth.toPx() }
val screenHeight = with(density) { maxHeight.toPx() }
val margin = with(density) { 8.dp.toPx() }
var panelSize by remember { mutableStateOf(IntSize.Zero) }
val x = (draft.toolsX * screenWidth).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin))
val y = (draft.toolsY * screenHeight).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin))
val position by rememberUpdatedState(Offset(x, y))
val expandedWidth = minOf(420.dp, maxWidth - 16.dp)
val panelWidth by animateDpAsState(if (draft.toolsExpanded) expandedWidth else 152.dp, label = "input-tools-width")
Surface(Modifier.offset { IntOffset(x.roundToInt(), y.roundToInt()) }
.width(panelWidth).clipToBounds()
.heightIn(max = maxHeight - 16.dp).onSizeChanged { panelSize = it },
shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surface,
tonalElevation = 6.dp, shadowElevation = 10.dp) {
Column {
Row(Modifier.fillMaxWidth().heightIn(min = 52.dp).testTag("input-editor-tools")
.pointerInput(screenWidth, screenHeight, panelSize) {
var dragPosition = Offset.Zero
detectDragGestures(onDragStart = { dragPosition = position }) { change, delta ->
change.consume()
dragPosition = Offset((dragPosition.x + delta.x).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin)),
(dragPosition.y + delta.y).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin)))
draft.toolsX = dragPosition.x / screenWidth
draft.toolsY = dragPosition.y / screenHeight
}
}
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_hidden_count, draft.hiddenDefaults().size), compact = true) {
draft.popover = if (draft.popover == EditorPopover.HIDDEN) null else EditorPopover.HIDDEN
.clickable { draft.toolsExpanded = !draft.toolsExpanded }.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Text("⠿", color = MaterialTheme.colorScheme.primary)
Text(stringResource(if (draft.toolsExpanded) R.string.input_hide_tools else R.string.input_tools), style = MaterialTheme.typography.titleSmall, maxLines = 1)
}
AnimatedVisibility(draft.toolsExpanded, enter = expandVertically(expandFrom = Alignment.Top) + fadeIn(),
exit = shrinkVertically(shrinkTowards = Alignment.Top) + fadeOut()) {
Column(Modifier.requiredWidth(expandedWidth).verticalScroll(rememberScrollState())) {
HorizontalDivider()
SurfaceToolbar(draft, onSave, onLeave)
HorizontalDivider()
SurfaceSelection(draft)
}
if (draft.defaults != null) SecondaryButton(stringResource(R.string.hud_reset_button), enabled = !draft.atDefaults, compact = true) { draft.reset() }
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(draft.snap, { draft.snap = it; ControllerPrefs.setSnap(context, it) })
Text(stringResource(R.string.ctrl_editor_snap))
}
if (draft.elements.isNotEmpty()) {
SecondaryButton("−", enabled = draft.scale > 80, compact = true) { draft.scaleAll((draft.scale - 5).coerceAtLeast(80)) }
Text("${draft.scale}%", Modifier.widthIn(min = 44.dp).testTag("input-editor-scale"), style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
SecondaryButton("+", enabled = draft.scale < 150, compact = true) { draft.scaleAll((draft.scale + 5).coerceAtMost(150)) }
}
PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave)
}
}
Row(Modifier.background(MaterialTheme.colorScheme.background.copy(alpha = .7f), RoundedCornerShape(50)).padding(horizontal = 12.dp, vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(scope, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
splitLabel?.let { SecondaryButton(it, compact = true, modifier = Modifier.testTag("input-editor-split"), onClick = onSplit) }
}
failure?.let { Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error) }
when (draft.popover) {
EditorPopover.ADD -> EditorList { AddRows(draft) }
EditorPopover.HIDDEN -> EditorList { HiddenRows(draft) }
null -> Unit
}
}
val e = draft.element
if (e != null && !draft.properties && draft.popover == null && !draft.confirmDiscard) {
val density = LocalDensity.current
var size by remember { mutableStateOf(IntSize.Zero) }
val w = with(density) { maxWidth.toPx() }
val h = with(density) { maxHeight.toPx() }
val gap = with(density) { 12.dp.toPx() }
val margin = with(density) { 8.dp.toPx() }
val top = h * e.y - gap - size.height
val above = top > with(density) { 110.dp.toPx() }
val x = (w * (e.x + e.width / 2) - size.width / 2).coerceIn(margin, (w - size.width - margin).coerceAtLeast(margin))
val y = if (above) top else (h * (e.y + e.height) + gap).coerceAtMost(h - size.height - margin)
EditorBar(Modifier.offset { IntOffset(x.roundToInt(), y.roundToInt()) }.onSizeChanged { size = it }.testTag("input-editor-selection")) {
SecondaryButton("−", compact = true) { draft.resizeSelected(1f / 1.1f) }
SecondaryButton("+", compact = true) { draft.resizeSelected(1.1f) }
PrimaryButton(stringResource(R.string.input_options), compact = true) { draft.clickProperties = false; draft.properties = true }
if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_short), compact = true) { draft.clickProperties = true; draft.properties = true }
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) }
}
}
}
}
@Composable
private fun EditorList(content: @Composable ColumnScope.() -> Unit) {
Surface(Modifier.widthIn(min = 260.dp, max = 360.dp), shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = .97f),
contentColor = MaterialTheme.colorScheme.onSurface, shadowElevation = 8.dp) {
Column(Modifier.padding(6.dp).heightIn(max = 320.dp).verticalScroll(rememberScrollState()), content = content)
}
}
@Composable
private fun EditorRow(title: String, action: String, onClick: () -> Unit) {
Row(Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
Text(title, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)
SecondaryButton(action, compact = true, onClick = onClick)
}
}
@Composable
private fun CloseRow(draft: SurfaceDraft) {
Row(Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp), horizontalArrangement = Arrangement.End) {
SecondaryButton(stringResource(R.string.common_close), compact = true) { draft.popover = null }
}
}
@Composable
private fun AddRows(draft: SurfaceDraft) {
val context = LocalContext.current
CloseRow(draft)
for (control in listOf(InputControl.L3, InputControl.R3).filter { c -> draft.elements.none { it.id == "legacy:${c.id}" } })
EditorRow(control.label, stringResource(R.string.input_editor_add)) { draft.add(InputSurfaceElement(control, .47f, .45f, .06f, .1f, buttonShape = InputButtonShape.CIRCLE)) }
for (kind in InputElementKind.entries) EditorRow(stringResource(kind.label()), stringResource(R.string.input_editor_add)) {
val w = if (kind.control.dimensions == 2) .2f else .1f
val h = if (kind.control.dimensions == 2) .35f else .16f
val name = context.getString(kind.label()) + " " + (draft.elements.count { it.kind == kind } + 1)
draft.add(InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name))
}
}
@Composable
private fun HiddenRows(draft: SurfaceDraft) {
val hidden = draft.hiddenDefaults()
CloseRow(draft)
if (hidden.isEmpty()) Text(stringResource(R.string.input_nothing_hidden), Modifier.padding(12.dp), style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant)
for (e in hidden) EditorRow(e.name, stringResource(R.string.input_restore)) { draft.add(e) }
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit, onDiscard: () -> Unit) {
private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) {
val context = LocalContext.current
if (draft.confirmDiscard) {
FlowRow(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(R.string.input_editor_discard), style = MaterialTheme.typography.titleSmall)
SecondaryButton(stringResource(R.string.input_keep_editing), compact = true) { draft.confirmDiscard = false }
PrimaryButton(stringResource(R.string.input_discard), compact = true, onClick = onDiscard)
}
return
}
FlowRow(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave)
SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.popover = EditorPopover.ADD }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_hidden_count, draft.hiddenDefaults().size), compact = true) { draft.popover = EditorPopover.HIDDEN }
SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true }
SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions() }
Row(verticalAlignment = Alignment.CenterVertically) {
@@ -450,7 +352,9 @@ private fun SurfaceSelection(draft: SurfaceDraft) {
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
PrimaryButton(stringResource(R.string.input_properties), compact = true) { draft.clickProperties = false; draft.properties = true }
if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_properties), compact = true) { draft.clickProperties = true; draft.properties = true }
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) }
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) {
draft.checkpoint(); draft.elements = draft.elements.filterNot { it.id == e.id }; draft.actions = draft.actions - e.id; draft.clicks = draft.clicks - e.id; draft.selected = null
}
}
} ?: Text(stringResource(R.string.input_editor_hint))
}
@@ -1,12 +1,17 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.R
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RadialGradient
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import android.graphics.drawable.GradientDrawable
import android.view.Gravity
@@ -31,11 +36,7 @@ import com.droiddeck.launcher.input.InputAction
import com.droiddeck.launcher.input.InputButtonIcons
import com.droiddeck.launcher.input.InputButtonShape
import com.droiddeck.launcher.input.InputButtonImages
import com.droiddeck.launcher.input.KitLayout
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.SavedInputLayout
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.pcKeyLabel
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.atan2
@@ -50,11 +51,7 @@ class InputSurfaceView(
val inputRole: InputRole = InputRole.SECONDARY,
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
private val haptics: Boolean = inputRole != InputRole.PRIMARY,
kit: PadKit = PadKit.current(context),
) : FrameLayout(context) {
var kit: PadKit = kit
set(value) { if (field != value) { field = value; customCanvas?.let { c -> for (i in 0 until c.childCount) c.getChildAt(i).invalidate() } } }
private val art = PadArt(context)
private val content = FrameLayout(context)
private val elementSources = ArrayList<InputSurfaceSource>()
private var customCanvas: ViewGroup? = null
@@ -147,25 +144,10 @@ class InputSurfaceView(
private fun styleElement(view: View) {
view.alpha = surfaceStyle.opacity / 100f * ((view.tag as? InputSurfaceElement)?.opacity ?: 1f)
(view as? Surface)?.tint = surfaceStyle.tint
view.invalidate()
}
private var generated: SavedInputLayout? = null
/** Shows [layout]; a layout that has no elements of its own gets the virtual controller's defaults at this view's size. */
fun showLayout(layout: SavedInputLayout?) {
generated = layout?.takeIf(OnScreenLayout::generated)
kit = PadKit.current(context)
updateStyle(layout?.style ?: InputSurfaceStyle())
updateCustomLayout(generated?.let { OnScreenLayout.elements(context, it, width, height, android.graphics.Rect(), null) } ?: layout?.elements.orEmpty())
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
val layout = generated ?: return
post { if (generated === layout) updateCustomLayout(OnScreenLayout.elements(context, layout, width, height, android.graphics.Rect(), null)) }
}
fun updateCustomLayout(requested: List<InputSurfaceElement>) {
requestedLayout = requested
val layout = surfaceStyle.shown(requested)
@@ -206,20 +188,16 @@ class InputSurfaceView(
val e = layout[i]
val child = getChildAt(i)
val x = (width * e.x).toInt(); val y = (height * e.y).toInt()
// A dialog resized after its first pass can lay this out at a size it was never measured at.
val w = (width * e.width).toInt(); val h = (height * e.height).toInt()
if (child.measuredWidth != w || child.measuredHeight != h)
child.measure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY))
child.layout(x, y, x + w, y + h)
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
}
}
}
canvas.clipChildren = customLayout.none(::adaptive)
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) }
for (element in customLayout) {
val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } }
canvas.addView(when (element.kind) {
InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null)
InputElementKind.TRACKPAD -> TrackpadView(context, source)
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, source = source)
InputElementKind.DPAD -> DirectionPad(context, element, source)
else -> HoldButton(context, element, source)
}.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } })
@@ -289,12 +267,64 @@ class InputSurfaceView(
private fun feedback(view: View, type: Int) { if (haptics) view.performHapticFeedback(type) }
private abstract class Surface(context: Context) : View(context) {
var tint: Int? = null
protected val density = resources.displayMetrics.density
protected val rect = RectF()
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
protected val labelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
color = TEXT
}
protected val captionPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
color = TEXT_DIM
}
protected fun drawSurface(canvas: Canvas, lit: Boolean, shape: InputButtonShape = InputButtonShape.ROUNDED, classic: Boolean = false) {
val inset = if (classic && tint != null) 0.75f * density else density
rect.set(inset, inset, width - inset, height - inset)
val radius = when (shape) { InputButtonShape.CIRCLE, InputButtonShape.PILL -> min(width, height) / 2f; InputButtonShape.RECTANGLE -> 2 * density; else -> CORNER * density }
val color = tint
if (classic && color != null) {
val corner = if (shape == InputButtonShape.PILL) radius * 0.55f else radius
fill.color = if (lit) shade(color, 160, 1f) else shade(color, 80, 0.12f)
canvas.drawRoundRect(rect, corner, corner, fill)
stroke.color = if (lit) light(color, 230, 0.7f) else light(color, 150, 0.25f)
stroke.strokeWidth = 1.5f * density
canvas.drawRoundRect(rect, corner, corner, stroke)
return
}
fill.color = tint?.let { color -> (color and 0x00ffffff) or ((if (lit) 140 else 48) shl 24) } ?: if (lit) ACCENT_WASH else SURFACE
canvas.drawRoundRect(rect, radius, radius, fill)
stroke.color = tint?.let { color -> (color and 0x00ffffff) or ((if (lit) 255 else 160) shl 24) } ?: if (lit) ACCENT else LINE
stroke.strokeWidth = (if (lit) 2f else 1f) * density
canvas.drawRoundRect(rect, radius, radius, stroke)
}
protected fun drawCircle(canvas: Canvas, x: Float, y: Float, radius: Float, fillColor: Int, strokeColor: Int) {
fill.color = fillColor
canvas.drawCircle(x, y, radius, fill)
stroke.color = strokeColor
stroke.strokeWidth = 1.5f * density
canvas.drawCircle(x, y, radius, stroke)
}
protected fun drawKeyboard(canvas: Canvas, x: Float, y: Float, lit: Boolean) {
val color = tint ?: return
stroke.color = if (lit) light(color, 230, 0.7f) else light(color, 150, 0.25f)
stroke.strokeWidth = 1.5f * density
rect.set(x - 10 * density, y - 7 * density, x + 10 * density, y + 7 * density)
canvas.drawRoundRect(rect, 2 * density, 2 * density, stroke)
for (row in 0..1) for (col in 0..2) {
val kx = x + (-6f + col * 5f) * density
val ky = y + (-3f + row * 4f) * density
canvas.drawLine(kx, ky, kx + 2 * density, ky, stroke)
}
canvas.drawLine(x - 5 * density, y + 4 * density, x + 5 * density, y + 4 * density, stroke)
}
protected fun textColor(lit: Boolean) = if (lit) Color.WHITE else tint?.let { light(it, 210, 0.75f) } ?: TEXT
}
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
@@ -316,61 +346,38 @@ class InputSurfaceView(
override fun onDraw(canvas: Canvas) {
val lit = if (element.toggle) source?.latched == true else down
val w = width.toFloat(); val h = height.toFloat()
val c = element.control
val native = element.id == "legacy:${c.id}" && element.showLabel && element.icon == 0 && bitmap == null &&
(element.name == c.label || element.name == kit.name(c)) && (c !in FACE || element.buttonShape == InputButtonShape.CIRCLE)
when {
element.id == KitLayout.KEYBOARD_ID && element.icon == InputButtonIcons.KEYBOARD -> art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, lit)
element.id == OnScreenLayout.STEAM_SHORTCUT_ID -> art.system(canvas, w, h, PadArt.Shape.PILL, PadArt.Icon.STEAM, lit)
element.id == OnScreenLayout.QAM_SHORTCUT_ID -> art.system(canvas, w, h, PadArt.Shape.PILL, PadArt.Icon.QAM, lit)
native && c in FACE -> art.face(canvas, w / 2f, h / 2f, min(w, h) / 2f - art.dp(2f), c, kit, lit)
native && c in SHOULDERS -> art.shoulder(canvas, w, h, c, kit, lit)
native && c in GRIPS -> art.grip(canvas, w, h, c.label, lit)
native && (c == InputControl.L3 || c == InputControl.R3) -> art.small(canvas, w, h, c.label, lit)
native && c in SYSTEM -> systemLook(c).let { (shape, icon) -> art.system(canvas, w, h, shape, icon, lit) }
else -> custom(canvas, w, h, lit)
}
}
private fun systemLook(c: InputControl): Pair<PadArt.Shape, PadArt.Icon> = when {
kit.steam -> when (c) {
InputControl.SELECT -> PadArt.Shape.CHIP to PadArt.Icon.VIEW
InputControl.START -> PadArt.Shape.CHIP to PadArt.Icon.MENU
InputControl.GUIDE -> PadArt.Shape.PILL to PadArt.Icon.STEAM
else -> PadArt.Shape.PILL to PadArt.Icon.QAM
}
kit.playStation -> when (c) {
InputControl.SELECT -> PadArt.Shape.PILL to if (kit == PadKit.DUALSHOCK) PadArt.Icon.SHARE else PadArt.Icon.CREATE
InputControl.START -> PadArt.Shape.PILL to if (kit == PadKit.DUALSHOCK) PadArt.Icon.OPTIONS else PadArt.Icon.MENU
InputControl.GUIDE -> PadArt.Shape.ROUND to PadArt.Icon.HOME
else -> PadArt.Shape.ROUND to PadArt.Icon.QAM
}
else -> PadArt.Shape.ROUND to when (c) {
InputControl.SELECT -> PadArt.Icon.BACK
InputControl.START -> PadArt.Icon.START
InputControl.GUIDE -> PadArt.Icon.HOME
else -> PadArt.Icon.QAM
}
}
private fun custom(canvas: Canvas, w: Float, h: Float, lit: Boolean) {
val inset = art.dp(2f)
art.glass(canvas, when (element.buttonShape) {
InputButtonShape.CIRCLE -> art.circle(w / 2f, h / 2f, min(w, h) / 2f - inset)
InputButtonShape.PILL -> art.roundRect(inset, inset, w - inset, h - inset, min(w, h) / 2f)
InputButtonShape.RECTANGLE -> art.roundRect(inset, inset, w - inset, h - inset, art.dp(4f))
InputButtonShape.ROUNDED -> art.roundRect(inset, inset, w - inset, h - inset, min(w, h) * .22f)
}, lit)
labelPaint.color = if (lit) PadArt.ON_ACCENT else PadArt.INK
val classic = classic(element)
drawSurface(canvas, lit, element.buttonShape, classic)
val cx = width / 2f
labelPaint.color = if (classic && tint != null) textColor(lit) else if (lit) ACCENT else TEXT
bitmap?.let {
val scale = min(w * .84f / it.width, h * .84f / it.height)
imageRect.set(w / 2f - it.width * scale / 2, (h - it.height * scale) / 2, w / 2f + it.width * scale / 2, (h + it.height * scale) / 2)
val scale = min(width * .84f / it.width, height * .84f / it.height)
imageRect.set(cx - it.width * scale / 2, (height - it.height * scale) / 2,
cx + it.width * scale / 2, (height + it.height * scale) / 2)
canvas.drawBitmap(it, null, imageRect, labelPaint)
return
}
if (element.icon != 0 && InputButtonIcons.draw(canvas, element.icon, w / 2f, h / 2f, min(w, h) * .6f, labelPaint, symbol)) return
if (element.showLabel) art.text(canvas, element.name, w / 2f, h / 2f, min(h * .34f, 26 * density), labelPaint.color, w * .82f)
if (classic && element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) { drawKeyboard(canvas, cx, height / 2f, lit); return }
if (element.icon != 0 && InputButtonIcons.draw(canvas, element.icon, cx, height / 2f, min(width, height) * .68f, labelPaint, symbol)) return
if (!element.showLabel) return
labelPaint.style = Paint.Style.FILL
if (classic && element.name == element.control.label) {
val radius = min(width, height) / 2f
val direction = DIRECTIONS.indexOf(element.control)
if (direction >= 0) { drawArrow(canvas, cx, height / 2f, radius * 0.34f, direction, labelPaint); return }
val glyph = glyph(element.control)
labelPaint.textSize = when {
element.buttonShape == InputButtonShape.PILL -> height / 2f * 0.8f
glyph.length > 2 -> 11 * density
else -> radius * if (glyph.length == 2) 0.62f else 0.85f
}
canvas.drawText(glyph, cx, height / 2f + labelPaint.textSize * .35f, labelPaint)
return
}
labelPaint.textSize = min(height * .3f, 30 * density)
val labelWidth = labelPaint.measureText(element.name)
if (labelWidth > width * .84f) labelPaint.textSize *= width * .84f / labelWidth
canvas.drawText(element.name, cx, height / 2f + labelPaint.textSize * .35f, labelPaint)
}
fun press(pointer: Int, pressed: Boolean, cancelled: Boolean = false) {
@@ -391,7 +398,8 @@ class InputSurfaceView(
}
}
private inner class TrackpadView(context: Context, private val source: InputSurfaceSource? = null) : Surface(context) {
private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true,
private val source: InputSurfaceSource? = null) : Surface(context) {
private var gestureX = 0f
private var gestureY = 0f
private val mouse = TouchpadGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), object : PointerGestures.Listener {
@@ -408,9 +416,29 @@ class InputSurfaceView(
private var clicked = false
private var fingerX = 0f
private var fingerY = 0f
private val guide = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; color = GUIDE }
private val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = ACCENT }
private val glow = Paint(Paint.ANTI_ALIAS_FLAG)
override fun onDraw(canvas: Canvas) {
art.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY)
drawSurface(canvas, clicked)
val cx = width / 2f
val cy = height / 2f
guide.strokeWidth = density
val reach = min(width, height) / 2f - 24 * density
canvas.drawCircle(cx, cy, reach, guide)
canvas.drawCircle(cx, cy, reach / 2f, guide)
canvas.drawLine(cx - reach, cy, cx + reach, cy, guide)
canvas.drawLine(cx, cy - reach, cx, cy + reach, guide)
captionPaint.textSize = 12 * density
captionPaint.color = if (touching) ACCENT else TEXT_DIM
if (captioned) canvas.drawText((contentDescription?.toString() ?: if (right) context.getString(R.string.deck_right_trackpad) else context.getString(R.string.deck_left_trackpad)).uppercase(), cx, 28 * density, captionPaint)
if (touching) {
val radius = 56 * density
glow.shader = RadialGradient(fingerX, fingerY, radius, ACCENT_GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(fingerX, fingerY, radius, glow)
canvas.drawCircle(fingerX, fingerY, (if (clicked) 16 else 12) * density, dot)
}
}
@SuppressLint("ClickableViewAccessibility")
@@ -482,31 +510,55 @@ class InputSurfaceView(
private var originY = 0f
private var knobX = 0f
private var knobY = 0f
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
val adaptive get() = adaptive(element)
private fun radius() = (min(width, height) / 2f - 3 * density).coerceAtLeast(1f)
fun reach() = radius() * STICK_REACH
fun reach() = min(width, height) * if (classic(element)) CLASSIC_REACH else PANEL_REACH
fun captures(x: Float, y: Float): Boolean {
val cx = centreX()
val dx = when (element.control) { InputControl.LS -> maxOf(0f, x - cx); InputControl.RS -> minOf(0f, x - cx); else -> x - cx }
val limit = radius() * ADAPTIVE_REACH
val dx = if (element.control == InputControl.LS) maxOf(0f, x - cx) else x - cx
val limit = reach() * ADAPTIVE_REACH
return dx * dx + (y - height / 2f) * (y - height / 2f) <= limit * limit
}
fun centreX() = width / 2f
fun centreX() = when {
!classic(element) || width <= height -> width / 2f
element.control == InputControl.LS -> width - height / 2f
else -> height / 2f
}
override fun onDraw(canvas: Canvas) {
if (hideWhenIdle && !touching) return
val cx = if (touching) inParent(originX, left, (parent as? View)?.width ?: width) else centreX()
val cy = if (touching) inParent(originY, top, (parent as? View)?.height ?: height) else height / 2f
val r = radius()
val travel = r * KNOB_TRAVEL / reach().coerceAtLeast(1f)
art.stick(canvas, cx, cy, r, kit, knobX * travel, knobY * travel, touching || clicking)
val cx = if (touching) originX else centreX()
val cy = if (touching) originY else height / 2f
val color = tint
if (classic(element) && color != null) {
val radius = min(width, height) / 2f - 0.75f * density
drawCircle(canvas, cx, cy, radius,
if (touching) shade(color, 160, 1f) else shade(color, 60, 0.12f), if (touching) light(color, 230, 0.7f) else light(color, 150, 0.25f))
val knobRadius = radius * 0.46f
drawCircle(canvas, cx + knobX, cy + knobY, knobRadius,
if (touching || clicking) shade(color, 160, 1f) else shade(color, 120, 0.35f), if (touching) light(color, 230, 0.7f) else light(color, 150, 0.25f))
if (!element.showLabel) return
labelPaint.color = textColor(touching)
if (drawDirectionLabels(canvas, source, false, cx, cy, radius * 0.66f, radius * 0.34f, labelPaint)) return
labelPaint.textSize = knobRadius * 0.8f
val label = if (element.name == element.control.label) glyph(element.control) else element.name
canvas.drawText(label, cx + knobX, cy + knobY + labelPaint.textSize * 0.35f, labelPaint)
return
}
drawSurface(canvas, clicking)
ring.strokeWidth = 2 * density
ring.color = if (touching) ACCENT else LINE
canvas.drawCircle(cx, cy, reach(), ring)
knob.color = if (touching) ACCENT else KNOB
canvas.drawCircle(cx + knobX, cy + knobY, reach() * 0.45f, knob)
if (!element.showLabel) return
labelPaint.color = PadArt.INK
drawDirectionLabels(canvas, source, false, cx, cy, r * .66f, r * .34f, labelPaint)
labelPaint.color = if (touching) ACCENT else TEXT
drawDirectionLabels(canvas, source, false, cx, cy, reach() * 1.32f, reach() * 0.68f, labelPaint)
}
@SuppressLint("ClickableViewAccessibility")
@@ -538,13 +590,6 @@ class InputSurfaceView(
return true
}
/** Where the base is drawn for a stick centred at [at], so it stays whole inside the overlay; input still centres on the touch. */
private fun inParent(at: Float, offset: Int, span: Int): Float {
val r = radius()
val low = r - offset; val high = span - offset - r
return if (low > high) at else at.coerceIn(low, high)
}
private fun follow(x: Float, y: Float, r: Float, force: Boolean = false) {
travel = maxOf(travel, hypot(x - downX, y - downY))
var dx = x - originX
@@ -576,20 +621,34 @@ class InputSurfaceView(
}
private inner class DirectionPad(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource? = null) : View(context) {
private val density = resources.displayMetrics.density
private var held = 0
private val arm = Paint(Paint.ANTI_ALIAS_FLAG)
private val label = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD); color = TEXT }
private val rect = RectF()
override fun onDraw(canvas: Canvas) {
val labels = element.showLabel && directionLabels(context, source?.directions, true).isNotEmpty()
art.dpad(canvas, width.toFloat(), height.toFloat(), kit, held, chevrons = !labels)
if (!labels) return
val half = min(width, height) / 2f
drawDirectionLabels(canvas, source, true, width / 2f, height / 2f, half * .68f, half * .32f, label)
val size = min(width, height) * 0.86f
val cx = width / 2f
val cy = height / 2f
val half = size / 2f
val thick = size / 3f / 2f
fun armRect(bit: Int, l: Float, t: Float, r: Float, b: Float) {
arm.color = if (held and bit != 0) ACCENT else KNOB
rect.set(l, t, r, b)
canvas.drawRoundRect(rect, 8 * density, 8 * density, arm)
}
armRect(1, cx - thick, cy - half, cx + thick, cy - thick)
armRect(4, cx - thick, cy + thick, cx + thick, cy + half)
armRect(8, cx - half, cy - thick, cx - thick, cy + thick)
armRect(2, cx + thick, cy - thick, cx + half, cy + thick)
arm.color = KNOB
canvas.drawRect(cx - thick, cy - thick, cx + thick, cy + thick, arm)
if (element.showLabel) drawDirectionLabels(canvas, source, true, cx, cy, (half + thick) / 2f, thick * 1.7f, label)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_CANCEL) { source?.cancel(); held = 0; invalidate(); return true }
val bits = when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
val dx = event.getX(0) - width / 2f
@@ -624,21 +683,48 @@ class InputSurfaceView(
companion object {
private const val CLICK_MS = 300L
private const val STICK_TAP_MS = 200L
private const val STICK_REACH = .62f
private const val KNOB_TRAVEL = .54f
private const val CLASSIC_REACH = 0.5f
private const val PANEL_REACH = 0.30f
private const val HIT_SLACK = 0.25f
private const val ADAPTIVE_CLEARANCE_PX = 5f
private const val ADAPTIVE_REACH = 1.71f
private val ADAPTIVE_REACH = 1.4f * kotlin.math.sqrt(1.5f)
private const val CORNER = 20f
private const val CORNER_PILL = 22f
private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF)
private val ACCENT_WASH = Color.argb(0x2E, 0x1A, 0x9F, 0xFF)
private val ACCENT_GLOW = Color.argb(0x66, 0x1A, 0x9F, 0xFF)
private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F)
internal val SURFACE = Color.rgb(0x0A, 0x0B, 0x0D)
internal val LINE = Color.rgb(0x26, 0x29, 0x2E)
private val GUIDE = Color.rgb(0x16, 0x18, 0x1B)
internal val TEXT = Color.rgb(0xF2, 0xF4, 0xF7)
private val FACE = setOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y)
private val SHOULDERS = setOf(InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT)
private val GRIPS = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
private val SYSTEM = setOf(InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM)
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
private fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating
private fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating && element.hideWhenIdle
private fun classic(element: InputSurfaceElement) = (element.id == "legacy:${element.control.id}" || element.id == "builtin:keyboard") &&
(element.buttonShape == InputButtonShape.CIRCLE || element.buttonShape == InputButtonShape.PILL)
private val DIRECTIONS = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
internal fun shade(tint: Int, alpha: Int, f: Float) =
Color.argb(alpha, (Color.red(tint) * f).toInt(), (Color.green(tint) * f).toInt(), (Color.blue(tint) * f).toInt())
internal fun light(tint: Int, alpha: Int, f: Float) = Color.argb(alpha, (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())
private fun glyph(control: InputControl) = when (control) {
InputControl.LS -> "L"
InputControl.RS -> "R"
InputControl.SELECT -> "⧉"
InputControl.START -> "☰"
InputControl.GUIDE -> "◉"
InputControl.QAM -> "⋯"
else -> control.id.uppercase()
}
private val CARDINAL = listOf(0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f)
private val DIAGONAL = listOf(.7071f to -.7071f, .7071f to .7071f, -.7071f to .7071f, -.7071f to -.7071f)
@@ -663,6 +749,16 @@ class InputSurfaceView(
return labels.isNotEmpty()
}
private fun drawArrow(canvas: Canvas, x: Float, y: Float, size: Float, direction: Int, paint: Paint) {
val (fx, fy) = when (direction) { 0 -> 0f to -1f; 1 -> 1f to 0f; 2 -> 0f to 1f; else -> -1f to 0f }
val path = Path()
path.moveTo(x + fx * size, y + fy * size)
path.lineTo(x - fx * size * 0.7f - fy * size, y - fy * size * 0.7f + fx * size)
path.lineTo(x - fx * size * 0.7f + fy * size, y - fy * size * 0.7f - fx * size)
path.close()
canvas.drawPath(path, paint)
}
internal fun dp(context: Context, value: Int): Int = (value * context.resources.displayMetrics.density + 0.5f).toInt()
internal fun outline(context: Context, radius: Float, fill: Int) = GradientDrawable().apply {
@@ -1,87 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.ControlsChoice
/** The on-screen controls layout menu: each option with what it is, and a delete button on saved layouts nothing uses. */
@Composable
fun LayoutChoiceRow(
host: MenuHost, key: String, options: List<ControlsChoice.Option>, selected: String, hint: String? = null,
chipModifier: Modifier = Modifier, onPick: (String) -> Unit, onDelete: (String) -> Unit,
) {
val label = stringResource(R.string.osc_layout)
val open = host.open == key
var deleting by remember { mutableStateOf<ControlsChoice.Option?>(null) }
SettingsRow(label, hint, highlighted = open) {
Box {
ValueChip(options.firstOrNull { it.id == selected }?.name ?: "-", open,
modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label) { firstItemFocus ->
options.forEachIndexed { index, option ->
MenuItem(option.name, checked = option.id == selected, detail = option.detail,
focusRequester = if (index == 0) firstItemFocus else null,
trailing = if (option.deletable) ({ DeleteButton(option.id, option.name) { host.open = null; deleting = option } }) else null) {
onPick(option.id)
host.open = null
}
}
}
}
}
deleting?.let { option ->
AlertDialog(onDismissRequest = { deleting = null },
title = { Text(stringResource(R.string.osc_delete_layout)) },
text = { Text(stringResource(R.string.input_delete_layout_detail, option.name)) },
confirmButton = { PadTextButton(onClick = { deleting = null; onDelete(option.id) }, modifier = Modifier.testTag("osc-delete-confirm")) {
Text(stringResource(R.string.common_delete))
} },
dismissButton = { PadTextButton(onClick = { deleting = null }) { Text(stringResource(R.string.common_cancel)) } })
}
}
@Composable
private fun DeleteButton(id: String, name: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(36.dp).clip(RoundedCornerShape(8.dp))
.background(if (hot) colors.error.copy(alpha = 0.16f) else Color.Transparent)
.glideBorder(hot, RoundedCornerShape(8.dp), colors.error)
.hoverable(source).clickable(role = Role.Button, interactionSource = source, indication = null, onClick = onClick)
.controllerConfirm(onClick = onClick)
.testTag("osc-delete-$id"),
) {
Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name),
tint = if (hot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp))
}
}
@@ -286,9 +286,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
extras.drivers(s.gpuDrivers)
}
if (tab == SheetTab.CONTROLS) {
SettingsGroup(stringResource(R.string.drawer_page_controller)) {
ActionRow(stringResource(R.string.input_remap_buttons), null, stringResource(R.string.ctrl_edit), a.onInputSettings)
}
InputQuickSettings(host, desktop = s.mode == SessionService.MODE_DESKTOP, onEdit = a.onInputSettings)
SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) {
ChoiceRow(
host, "touch", stringResource(R.string.mode_touch), null,
@@ -298,7 +296,13 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
)
if (steam && s.oscMode != null) ChoiceRow(
host, "osc", stringResource(R.string.mode_osc), null,
controlsVisibilityOptions(steam = true), s.oscMode,
listOf(
SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto),
SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always),
SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch),
SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam),
SessionPrefs.OSC_NEVER to stringResource(R.string.common_never),
), s.oscMode,
note = stringResource(R.string.mode_osc_note), onPick = a.onOsc,
)
if (steam && s.steamController != null) ChoiceRow(
@@ -1,359 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RadialGradient
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import androidx.core.graphics.PathParser
import com.droiddeck.launcher.input.DpadStyle
import com.droiddeck.launcher.input.FaceGlyphs
import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.StickCap
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
/** The on-screen controls' shared drawing: one glass material, shaped per virtual controller. */
internal class PadArt(context: Context) {
val density = context.resources.displayMetrics.density
private val body = Paint(Paint.ANTI_ALIAS_FLAG)
private val shine = Paint(Paint.ANTI_ALIAS_FLAG)
private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) }
private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val path = Path()
private val arm = Path()
private val bar = Path()
private val rect = RectF()
private var shineTop = Float.NaN
private var shineHeight = Float.NaN
fun dp(value: Float) = value * density
fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) {
shape.computeBounds(rect, false)
body.color = if (pressed) PRESSED else tint
body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawPath(shape, body)
body.clearShadowLayer()
if (!pressed) {
if (rect.top != shineTop || rect.height() != shineHeight) {
shineTop = rect.top; shineHeight = rect.height()
shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP)
}
canvas.drawPath(shape, shine)
}
edge.color = if (pressed) EDGE_PRESSED else EDGE
edge.strokeWidth = dp(1.25f)
canvas.drawPath(shape, edge)
}
fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) }
fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW)
}
private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW)
}
fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) {
ink.textSize = size
val measured = ink.measureText(value)
if (measured > maxWidth) ink.textSize = size * maxWidth / measured
ink.color = color
canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink)
}
fun face(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, kit: PadKit, pressed: Boolean) {
glass(canvas, circle(cx, cy, r), pressed)
when (kit.face) {
FaceGlyphs.COLOR_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else SYMBOL_COLORS[control] ?: INK)
FaceGlyphs.MONO_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else INK_SOFT)
FaceGlyphs.COLOR_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else LETTER_COLORS[control] ?: INK)
FaceGlyphs.MONO_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else INK)
}
}
private fun symbol(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, color: Int) {
val s = r * .4f
line.color = color; line.strokeWidth = r * .12f
when (control) {
InputControl.A -> { canvas.drawLine(cx - s, cy - s, cx + s, cy + s, line); canvas.drawLine(cx + s, cy - s, cx - s, cy + s, line) }
InputControl.B -> canvas.drawCircle(cx, cy, s * 1.05f, line)
InputControl.X -> canvas.drawRoundRect(RectF(cx - s * .95f, cy - s * .95f, cx + s * .95f, cy + s * .95f), s * .18f, s * .18f, line)
else -> canvas.drawPath(path.apply { reset(); moveTo(cx, cy - s * 1.1f); lineTo(cx + s * 1.1f, cy + s * .85f); lineTo(cx - s * 1.1f, cy + s * .85f); close() }, line)
}
}
fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, kit: PadKit, pressed: Boolean) {
val inset = dp(2f)
val l = inset; val t = inset; val r = w - inset; val b = h - inset
val trigger = control == InputControl.LT || control == InputControl.RT
val big = (b - t) * if (trigger) .9f else .62f
val small = dp(5f)
val left = control == InputControl.LT || control == InputControl.LB
glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed)
text(canvas, kit.label(control), w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f)
}
/** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */
fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val inset = dp(3f)
val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f)
val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f)
val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long
val cx = w / 2f; val cy = h / 2f
glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed)
text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT)
}
fun small(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val r = min(w, h) / 2f * VISUAL
glass(canvas, circle(w / 2f, h / 2f, r), pressed)
text(canvas, label, w / 2f, h / 2f, r * .62f, if (pressed) ON_ACCENT else INK)
}
enum class Shape { ROUND, PILL, CHIP }
enum class Icon { VIEW, MENU, QAM, KEYBOARD, BACK, START, CREATE, HOME, STEAM, SHARE, OPTIONS, MARK }
fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) {
val cx = w / 2f; val cy = h / 2f
val size = when (shape) {
Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f }
Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f }
Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f }
}
icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink)
}
fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) {
val u = size / 28f
line.color = color; line.strokeWidth = 3.2f * u
fill.color = color; fill.shader = null
when (icon) {
Icon.VIEW -> {
canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line)
fill.color = Color.argb(230, 14, 16, 20)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line)
}
Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line)
Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill)
Icon.KEYBOARD -> {
canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line)
for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill)
line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line)
}
Icon.BACK, Icon.START -> {
val f = if (icon == Icon.START) 1f else -1f
line.strokeWidth = 2.6f * u
canvas.drawPath(path.apply { reset(); moveTo(cx - 6 * f * u, cy - 8 * u); lineTo(cx + 7 * f * u, cy); lineTo(cx - 6 * f * u, cy + 8 * u); close() }, line)
}
Icon.CREATE -> {
line.strokeWidth = 2.8f * u
canvas.drawLine(cx - 8 * u, cy + 8 * u, cx - 2 * u, cy - 8 * u, line)
canvas.drawLine(cx + u, cy + 8 * u, cx + 4 * u, cy - 2 * u, line)
canvas.drawLine(cx + 8 * u, cy + 8 * u, cx + 9 * u, cy + 3 * u, line)
}
Icon.HOME -> canvas.drawPath(path.apply {
reset(); moveTo(cx - 13 * u, cy - u); lineTo(cx, cy - 13 * u); lineTo(cx + 13 * u, cy - u)
moveTo(cx - 9 * u, cy - 4 * u); lineTo(cx - 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy - 4 * u)
}, line)
Icon.STEAM, Icon.SHARE, Icon.OPTIONS -> {
ink.letterSpacing = .12f
text(canvas, when (icon) { Icon.STEAM -> "STEAM"; Icon.SHARE -> "SHARE"; else -> "OPTIONS" }, cx, cy, 14 * u, color, size * 1.9f)
ink.letterSpacing = 0f
}
Icon.MARK -> mark(canvas, cx, cy, size * .5f, color, if (color == ON_ACCENT) ON_ACCENT else ACCENT)
}
}
fun mark(canvas: Canvas, cx: Float, cy: Float, radius: Float, ink: Int, orb: Int) {
val k = radius / 111.86f
canvas.save()
canvas.translate(cx - 71.98f * k, cy - 111.86f * k)
canvas.scale(k, k)
fill.shader = null; fill.color = ink
canvas.drawPath(MARK, fill)
fill.color = orb
canvas.drawCircle(63.98f, 111.86f, 55.98f, fill)
canvas.restore()
}
private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) {
val px = -dy; val py = dx
line.color = color; line.strokeWidth = width
canvas.drawPath(path.apply {
reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f)
lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k)
}, line)
}
private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply {
reset()
addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW)
bar.reset()
bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW)
op(bar, Path.Op.UNION)
}
/** [held] bits: up 1, right 2, down 4, left 8. */
fun dpad(canvas: Canvas, w: Float, h: Float, kit: PadKit, held: Int, chevrons: Boolean = true, ink: Int = INK) {
val cx = w / 2f; val cy = h / 2f
val s = min(w, h) / 2f - dp(3f)
val dirs = arrayOf(floatArrayOf(0f, -1f), floatArrayOf(1f, 0f), floatArrayOf(0f, 1f), floatArrayOf(-1f, 0f))
when (kit.dpad) {
DpadStyle.CROSS, DpadStyle.DISC -> {
val disc = kit.dpad == DpadStyle.DISC
val arms = if (disc) s * .78f else s
val half = if (disc) s * .25f else s * .37f
if (disc) {
glass(canvas, circle(cx, cy, s), false)
fill.shader = null; fill.color = Color.argb(18, 255, 255, 255)
canvas.drawPath(cross(arm, cx, cy, arms, half, half * .5f), fill)
edge.color = Color.argb(56, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawPath(arm, edge)
} else glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false)
for (i in 0..3) {
val dx = dirs[i][0]; val dy = dirs[i][1]
val on = held and (1 shl i) != 0
if (on) {
fill.shader = null; fill.color = PRESSED
val near = half + dp(1f); val far = arms - dp(2f); val side = half - dp(2f)
rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far, if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far,
if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near, if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near)
canvas.drawRoundRect(rect, half * .4f, half * .4f, fill)
}
val m = (arms + half) / 2f
if (chevrons) chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else ink, half * .17f)
}
if (!disc) { fill.shader = null; fill.color = Color.argb(18, 255, 255, 255); canvas.drawCircle(cx, cy, half * .36f, fill) }
}
DpadStyle.ARROWS -> {
fill.shader = null; fill.color = Color.argb(56, 0, 0, 0)
canvas.drawCircle(cx, cy, s, fill)
edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawCircle(cx, cy, s, edge)
val bw = s * .5f; val tip = s * .14f; val base = s * .38f; val top = s * .9f; val rc = s * .11f
for (i in 0..3) {
canvas.save()
canvas.rotate(i * 90f, cx, cy)
arm.reset()
arm.moveTo(cx, cy - tip); arm.lineTo(cx - bw / 2, cy - base); arm.lineTo(cx - bw / 2, cy - top + rc)
arm.quadTo(cx - bw / 2, cy - top, cx - bw / 2 + rc, cy - top); arm.lineTo(cx + bw / 2 - rc, cy - top)
arm.quadTo(cx + bw / 2, cy - top, cx + bw / 2, cy - top + rc); arm.lineTo(cx + bw / 2, cy - base); arm.close()
val on = held and (1 shl i) != 0
glass(canvas, arm, on)
val ty = cy - (base + top) / 2f; val ts = s * .07f
fill.shader = null; fill.color = if (on) ON_ACCENT else INK_SOFT
if (chevrons) canvas.drawPath(path.apply { reset(); moveTo(cx, ty - ts); lineTo(cx + ts, ty + ts * .7f); lineTo(cx - ts, ty + ts * .7f); close() }, fill)
canvas.restore()
}
}
}
}
fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kit: PadKit, kx: Float, ky: Float, active: Boolean) {
fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP)
fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawCircle(cx, cy, radius, fill)
fill.clearShadowLayer(); fill.shader = null
edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f)
canvas.drawCircle(cx, cy, radius, edge)
line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f)
for (i in 0 until 8) {
val a = i * Math.PI / 4
val c = cos(a).toFloat(); val n = sin(a).toFloat()
canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line)
}
if (active && (kx != 0f || ky != 0f)) {
val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat()
line.color = ACCENT; line.strokeWidth = dp(3f)
val r = radius - dp(2f)
canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line)
}
val k = radius * .46f
val x = cx + kx; val y = cy + ky
if (kit.stick == StickCap.RINGED) {
line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240); line.strokeWidth = dp(2.8f)
canvas.drawCircle(x, y, k * 1.14f, line)
}
glass(canvas, circle(x, y, k), false)
when (kit.stick) {
StickCap.DISHED -> {
fill.shader = RadialGradient(x, y - k * .1f, k * .74f, Color.argb(107, 0, 0, 0), Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(x, y, k * .74f, fill); fill.shader = null
edge.color = if (active) ACCENT else Color.argb(51, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawCircle(x, y, k * .74f, edge)
}
StickCap.KNURLED -> {
line.color = if (active) ACCENT else Color.argb(66, 255, 255, 255); line.strokeWidth = dp(2.3f)
line.pathEffect = DashPathEffect(floatArrayOf(dp(1.2f), dp(1.9f)), 0f)
canvas.drawCircle(x, y, k * .9f, line); line.pathEffect = null
fill.color = Color.argb(56, 0, 0, 0); canvas.drawCircle(x, y, k * .6f, fill)
}
StickCap.RINGED -> { edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f); canvas.drawCircle(x, y, k * .66f, edge) }
}
}
fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) {
val inset = dp(1.5f)
val radius = min(w, h) * .14f
fill.shader = null; fill.color = Color.argb(51, 14, 16, 20)
rect.set(inset, inset, w - inset, h - inset)
canvas.drawRoundRect(rect, radius, radius, fill)
edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255)
edge.strokeWidth = dp(if (touching) 1.5f else 1f)
canvas.drawRoundRect(rect, radius, radius, edge)
if (!touching) return
val glow = min(w, h) * .3f
fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(fx, fy, glow, fill); fill.shader = null
fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill)
}
fun label(canvas: Canvas, w: Float, h: Float, round: Boolean, value: String, pressed: Boolean) {
val inset = dp(2f)
glass(canvas, if (round) circle(w / 2f, h / 2f, min(w, h) / 2f - inset) else roundRect(inset, inset, w - inset, h - inset, min(w, h) * .25f), pressed)
text(canvas, value, w / 2f, h / 2f, min(h * .38f, dp(18f)), if (pressed) ON_ACCENT else INK, w * .82f)
}
companion object {
const val VISUAL = .72f
val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF)
val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F)
val INK = Color.rgb(0xF4, 0xF7, 0xFB)
val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB)
private val BODY = Color.argb(133, 14, 16, 20)
private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF)
private val SHINE = Color.argb(43, 255, 255, 255)
private val EDGE = Color.argb(77, 255, 255, 255)
private val EDGE_PRESSED = Color.argb(140, 255, 255, 255)
private val SHADOW = Color.argb(97, 0, 0, 0)
private val WELL_IN = Color.argb(140, 5, 7, 10)
private val WELL_OUT = Color.argb(71, 14, 16, 20)
private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF)
private val LETTER_COLORS = mapOf(InputControl.A to Color.rgb(0x5C, 0xCB, 0x5F), InputControl.B to Color.rgb(0xF0, 0x50, 0x4A),
InputControl.X to Color.rgb(0x4C, 0x9B, 0xF0), InputControl.Y to Color.rgb(0xF5, 0xC0, 0x2E))
private val SYMBOL_COLORS = mapOf(InputControl.A to Color.rgb(0x8D, 0xB4, 0xF2), InputControl.B to Color.rgb(0xF2, 0x61, 0x6B),
InputControl.X to Color.rgb(0xEE, 0x93, 0xD6), InputControl.Y to Color.rgb(0x45, 0xCB, 0xAA))
private const val MARK_DATA = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z" +
"M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"
val MARK: Path by lazy { PathParser.createPathFromPathData(MARK_DATA) }
}
}
@@ -245,7 +245,8 @@ class SecondScreenPresentation(
if (!created || !currentMode.controls) return
val controls = controlsView ?: return
val layout = panelLayout(currentMode)
controls.showLayout(layout)
controls.updateCustomLayout(layout?.elements.orEmpty())
controls.updateStyle(layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
}
fun showKeyboard(): Boolean {
@@ -292,7 +293,8 @@ class SecondScreenPresentation(
if (mode == SecondScreenMode.DECK_CONTROLS) deckPanel.value = SessionPrefs.deckPanel(context)
bar(mode)
val layout = panelLayout(mode)
val controls = InputSurfaceView(context, pad).also { it.showLayout(layout) }
val controls = InputSurfaceView(context, pad, layout?.elements.orEmpty(),
surfaceStyle = layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
controlsView = controls
root.addView(controls, weightParams())
attachKeyboard()
@@ -1,7 +1,7 @@
package com.droiddeck.launcher.ui
internal enum class SessionDrawerPage(val firstControl: String) {
CONTROLLER("touch"),
CONTROLLER("input-profile"),
GLASSES("glasses-game"),
DISPLAY("fg"),
HUD("hud"),
@@ -50,6 +50,8 @@ import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.SportsEsports
import androidx.compose.material3.Icon
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.ui.semantics.Role
@@ -290,17 +292,7 @@ class DrawerActions(
val onAchievements: (() -> Unit)? = null,
val achievementsProgress: Pair<Int, Int>? = null,
val onOsc: (String) -> Unit,
val layoutGame: String? = null,
val layoutOptions: List<com.droiddeck.launcher.input.ControlsChoice.Option> = emptyList(),
val layoutChoice: String = "",
val layoutHint: String? = null,
val onLayout: (String) -> Unit = {},
val onDeleteLayout: (String) -> Unit = {},
val onEditLayout: (() -> Unit)? = null,
val oscRearButtons: Boolean? = null,
val oscTrackpads: Boolean = false,
val onOscRearButtons: (Boolean) -> Unit = {},
val onOscTrackpads: (Boolean) -> Unit = {},
val onEditSteamTouch: (() -> Unit)? = null,
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val onRumble: (Boolean) -> Unit = {},
val onSuspendPolicy: (String) -> Unit,
@@ -346,6 +338,10 @@ class DrawerActions(
val onPause: () -> Unit = {},
val onPipAutoEnter: (Boolean) -> Unit = {},
val unfoldedControls: Boolean? = null,
val adaptiveSticks: Boolean? = null,
val onAdaptiveSticks: (Boolean) -> Unit = {},
val quickButtons: Map<com.droiddeck.launcher.input.InputCommand, Boolean> = emptyMap(),
val onQuickButton: (com.droiddeck.launcher.input.InputCommand, Boolean) -> Unit = { _, _ -> },
val onUnfoldedControls: (Boolean) -> Unit = {},
val unfoldedControlsWithController: Boolean = false,
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
@@ -670,54 +666,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (!a.glassesOutput) CardboardGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.CONTROLLER -> {
SettingsGroup(a.layoutGame?.let { stringResource(R.string.osc_group_for, it) } ?: stringResource(R.string.mode_osc)) {
if (a.layoutOptions.isNotEmpty()) LayoutChoiceRow(host, "osc-layout", a.layoutOptions, a.layoutChoice, a.layoutHint,
chipModifier = focus.track(page, "osc-layout"), onPick = a.onLayout, onDelete = a.onDeleteLayout)
a.onEditLayout?.let { edit ->
ActionRow(stringResource(R.string.osc_edit_layout), null, stringResource(R.string.ctrl_edit), { host.open = null; edit() },
modifier = focus.track(page, "osc-edit"))
}
ControlsVisibilityRow(host, a.oscMode, a.steam, focus.track(page, "osc-show"), a.onOsc)
a.oscRearButtons?.let { rearButtons ->
ToggleRow(host, "osc-rear-buttons", stringResource(R.string.osc_rear_buttons), null, rearButtons,
chipModifier = focus.track(page, "osc-rear-buttons"), onChange = a.onOscRearButtons)
ToggleRow(host, "osc-trackpads", stringResource(R.string.osc_trackpads), null, a.oscTrackpads,
chipModifier = focus.track(page, "osc-trackpads"), onChange = a.onOscTrackpads)
}
ChoiceRow(host, "touch", stringResource(R.string.input_touches), null,
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_mouse),
SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures),
SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
if (a.touchActive == SessionPrefs.TOUCH_PAD)
RelativeMouseRow(host, a, focus.track(page, "relative-mouse"))
if (a.touchActive == SessionPrefs.TOUCH_DIRECT)
ToggleRow(host, "direct-cursor", stringResource(R.string.input_touch_cursor),
null, a.directCursor,
chipModifier = focus.track(page, "direct-cursor"), onChange = a.onDirectCursor)
when (a.touchActive) {
SessionPrefs.TOUCH_GESTURES -> ActionRow(stringResource(R.string.gesture_settings), null,
stringResource(R.string.ctrl_edit), a.onGestureSettings,
modifier = focus.track(page, "gesture-settings"))
SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.input_touch_hold), null,
listOf(MOUSE_BEHAVIOR_NONE to stringResource(R.string.gesture_hold_left),
MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_right_click),
MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_right)),
a.directHoldBehavior, chipModifier = focus.track(page, "long-press"),
onPick = a.onDirectHoldBehavior)
}
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
null, a.unfoldedControls,
chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls)
if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller",
stringResource(R.string.unfolded_controls_with_controller),
null, a.unfoldedControlsWithController,
chipModifier = focus.track(page, "unfolded-controls-with-controller"),
onChange = a.onUnfoldedControlsWithController)
}
SettingsGroup(stringResource(R.string.drawer_page_controller)) {
InputQuickSettings(host, desktop = a.desktop, onChanged = a.onInputSelection, onEdit = a.onInputSettings) { key -> focus.track(page, key) }
}
SettingsGroup(stringResource(R.string.input_device_settings)) {
a.padType?.let { type ->
ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), null,
ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), stringResource(R.string.input_virtual_controller_hint),
listOf(SessionPrefs.CONTROLLER_DECK to stringResource(R.string.mode_controller_deck),
SessionPrefs.CONTROLLER_STEAM to stringResource(R.string.mode_controller_steam),
SessionPrefs.CONTROLLER_DS4 to stringResource(R.string.mode_controller_ds4),
@@ -728,9 +682,83 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
a.controller?.let { c ->
ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble,
chipModifier = focus.track(page, "rumble"), onChange = a.onRumble)
}
ActionRow(stringResource(R.string.input_remap_buttons), null, stringResource(R.string.ctrl_edit),
a.onInputSettings, modifier = focus.track(page, "remap"))
}
SettingsGroup(stringResource(R.string.input_touchscreen)) {
ChoiceRow(host, "touch", stringResource(R.string.input_touchscreen), stringResource(R.string.input_touchscreen_hint),
listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)),
a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch)
if (a.touchActive == SessionPrefs.TOUCH_PAD)
RelativeMouseRow(host, a, focus.track(page, "relative-mouse"))
if (a.touchActive == SessionPrefs.TOUCH_DIRECT)
ToggleRow(host, "direct-cursor", stringResource(R.string.input_touch_cursor),
stringResource(R.string.input_touch_cursor_hint), a.directCursor,
chipModifier = focus.track(page, "direct-cursor"), onChange = a.onDirectCursor)
when (a.touchActive) {
SessionPrefs.TOUCH_GESTURES -> ActionRow(stringResource(R.string.gesture_settings), null,
stringResource(R.string.ctrl_edit), a.onGestureSettings,
modifier = focus.track(page, "gesture-settings"))
SessionPrefs.TOUCH_DIRECT -> ChoiceRow(host, "long-press", stringResource(R.string.input_touch_hold), stringResource(R.string.input_touch_hold_hint),
listOf(MOUSE_BEHAVIOR_NONE to stringResource(R.string.gesture_hold_left),
MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_right_click),
MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_right)),
a.directHoldBehavior, chipModifier = focus.track(page, "long-press"),
onPick = a.onDirectHoldBehavior)
}
}
a.pen?.let { PenSettingsGroup(host, it, track = { key -> focus.track(page, key) }, onPick = a.onPen) }
SettingsGroup(stringResource(R.string.input_screen_visibility)) {
ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null,
if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)),
if (!a.steam && a.oscMode == SessionPrefs.OSC_STEAM_TOUCH) SessionPrefs.OSC_AUTO else a.oscMode,
chipModifier = focus.track(page, "osc"), onPick = a.onOsc)
a.adaptiveSticks?.let { on ->
ToggleRow(host, "adaptive-sticks", stringResource(R.string.ctrl_adaptive), null, on,
chipModifier = focus.track(page, "adaptive-sticks"), onChange = a.onAdaptiveSticks)
}
for ((button, shown) in a.quickButtons) {
val key = "quick-${button.name.lowercase()}"
ToggleRow(host, key, stringResource(quickButtonLabel(button)), null, shown,
chipModifier = focus.track(page, key)) { a.onQuickButton(button, it) }
}
a.onEditSteamTouch?.let { edit ->
ActionRow(stringResource(R.string.osc_steam_layout), stringResource(R.string.osc_steam_layout_hint), stringResource(R.string.ctrl_edit), edit)
}
if (a.steam && a.unfoldedControls != null) ToggleRow(host, "unfolded-controls", stringResource(R.string.unfolded_controls),
stringResource(R.string.unfolded_controls_hint), a.unfoldedControls,
chipModifier = focus.track(page, "unfolded-controls"), onChange = a.onUnfoldedControls)
if (a.steam && a.unfoldedControls == true) ToggleRow(host, "unfolded-controls-with-controller",
stringResource(R.string.unfolded_controls_with_controller),
stringResource(R.string.unfolded_controls_with_controller_hint), a.unfoldedControlsWithController,
chipModifier = focus.track(page, "unfolded-controls-with-controller"),
onChange = a.onUnfoldedControlsWithController)
}
SettingsGroup(stringResource(R.string.shortcuts_title)) {
if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold),
stringResource(R.string.back_hold_hint), a.backHold,
chipModifier = focus.track(page, "back-hold"), onChange = a.onBackHold)
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.input_back_taps), stringResource(R.string.input_back_taps_hint),
listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)),
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null,
SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) },
a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs)
PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") })
ToggleRow(host, "corner-tap", stringResource(R.string.drawer_corner_tap),
stringResource(R.string.drawer_corner_tap_hint), a.cornerTap,
chipModifier = focus.track(page, "corner-tap"), onChange = a.onCornerTap)
}
SettingsGroup(stringResource(R.string.drawer_latency)) {
ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency),
stringResource(R.string.drawer_low_latency_hint), a.lowLatency,
chipModifier = focus.track(page, "low-latency"), onChange = a.onLowLatency)
ToggleRow(host, "evdev-mouse", stringResource(R.string.drawer_evdev_mouse),
null, a.evdevMouse,
chipModifier = focus.track(page, "evdev-mouse"), onChange = a.onEvdevMouse)
if (a.touchActive != SessionPrefs.TOUCH_PAD)
RelativeMouseRow(host, a, focus.track(page, "relative-mouse"))
}
SettingsGroup(stringResource(R.string.drawer_keyboard)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
@@ -750,57 +778,28 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
),
a.wowChat, chipModifier = focus.track(page, "wow-chat"), onPick = a.onWowChat,
)
}
a.pen?.let { PenSettingsGroup(host, it, track = { key -> focus.track(page, key) }, onPick = a.onPen) }
var moreControls by rememberSaveable { mutableStateOf(false) }
SettingsGroup(stringResource(R.string.osc_more)) {
ActionRow(stringResource(R.string.osc_more_detail), null, stringResource(if (moreControls) R.string.common_hide else R.string.common_show),
{ moreControls = !moreControls }, modifier = focus.track(page, "more-controls"))
if (moreControls) {
if (a.steam) ToggleRow(host, "back-hold", stringResource(R.string.back_hold),
null, a.backHold,
chipModifier = focus.track(page, "back-hold"), onChange = a.onBackHold)
if (a.steam) ChoiceRow(host, "back-actions", stringResource(R.string.input_back_taps), null,
listOf(false to stringResource(SessionPrefs.BACK_MENU_THEN_QAM), true to stringResource(SessionPrefs.BACK_QAM_THEN_MENU)),
a.backActionsInverted, chipModifier = focus.track(page, "back-actions"), onPick = a.onBackActionsInverted)
if (a.steam) ChoiceRow(host, "back-double-tap", stringResource(R.string.back_double_tap_window), null,
SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) },
a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs)
PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") })
ToggleRow(host, "corner-tap", stringResource(R.string.drawer_corner_tap),
stringResource(R.string.drawer_corner_tap_hint), a.cornerTap,
chipModifier = focus.track(page, "corner-tap"), onChange = a.onCornerTap)
ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency),
null, a.lowLatency,
chipModifier = focus.track(page, "low-latency"), onChange = a.onLowLatency)
ToggleRow(host, "evdev-mouse", stringResource(R.string.drawer_evdev_mouse),
null, a.evdevMouse,
chipModifier = focus.track(page, "evdev-mouse"), onChange = a.onEvdevMouse)
if (a.touchActive != SessionPrefs.TOUCH_PAD)
RelativeMouseRow(host, a, focus.track(page, "relative-mouse"))
val keyboardContext = LocalContext.current
remember { PcKeyboardPrefs.load(keyboardContext) }
SliderRow(
stringResource(R.string.pckb_size), null,
PcKeyboardPrefs.size, SessionPrefs.PC_KEYBOARD_SIZE_RANGE, step = 1,
format = { "$it%" }, modifier = focus.track(page, "pckb-size"),
onChange = { PcKeyboardPrefs.setSize(keyboardContext, it) })
SliderRow(
stringResource(R.string.pckb_opacity), null,
PcKeyboardPrefs.opacity, SessionPrefs.PC_KEYBOARD_OPACITY_RANGE, step = 5,
format = { "$it%" }, modifier = focus.track(page, "pckb-opacity"),
onChange = { PcKeyboardPrefs.setOpacity(keyboardContext, it) })
MultiRow(
host, "pckb-hidden", stringResource(R.string.pckb_hidden_keys),
null,
listOf(
0 to stringResource(R.string.pckb_group_function),
1 to stringResource(R.string.pckb_group_nav),
2 to stringResource(R.string.pckb_group_arrows),
),
PC_KEY_GROUP_IDS.filterValues { it in PcKeyboardPrefs.hiddenKeys }.keys,
onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) })
}
val keyboardContext = LocalContext.current
remember { PcKeyboardPrefs.load(keyboardContext) }
SliderRow(
stringResource(R.string.pckb_size), stringResource(R.string.pckb_size_hint),
PcKeyboardPrefs.size, SessionPrefs.PC_KEYBOARD_SIZE_RANGE, step = 1,
format = { "$it%" }, modifier = focus.track(page, "pckb-size"),
onChange = { PcKeyboardPrefs.setSize(keyboardContext, it) })
SliderRow(
stringResource(R.string.pckb_opacity), stringResource(R.string.pckb_opacity_hint),
PcKeyboardPrefs.opacity, SessionPrefs.PC_KEYBOARD_OPACITY_RANGE, step = 5,
format = { "$it%" }, modifier = focus.track(page, "pckb-opacity"),
onChange = { PcKeyboardPrefs.setOpacity(keyboardContext, it) })
MultiRow(
host, "pckb-hidden", stringResource(R.string.pckb_hidden_keys),
stringResource(R.string.pckb_hidden_keys_hint),
listOf(
0 to stringResource(R.string.pckb_group_function),
1 to stringResource(R.string.pckb_group_nav),
2 to stringResource(R.string.pckb_group_arrows),
),
PC_KEY_GROUP_IDS.filterValues { it in PcKeyboardPrefs.hiddenKeys }.keys,
onToggle = { id, on -> PcKeyboardPrefs.toggleHiddenKey(keyboardContext, PC_KEY_GROUP_IDS.getValue(id), on) })
}
}
SessionDrawerPage.GLASSES -> if (glassesTab == GlassesTab.CONTROLLERS) {
@@ -840,7 +839,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SessionDrawerPage.AGENT -> Unit
SessionDrawerPage.SESSION -> {
SettingsGroup(stringResource(R.string.drawer_support)) {
SettingsRow(stringResource(R.string.report_problem), null) {
SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) {
DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs"),
progress = com.droiddeck.launcher.session.SessionLogShare.progress) {
host.open = null
@@ -878,7 +877,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
SettingsGroup(stringResource(R.string.drawer_session_behavior)) {
if (a.micAvailable) ToggleRow(host, "microphone", stringResource(R.string.mode_mic),
null, a.micEnabled,
stringResource(R.string.drawer_mic_hint), a.micEnabled,
chipModifier = focus.track(page, "microphone"), onChange = a.onMicEnabled)
ChoiceRow(
host, "suspend", stringResource(R.string.mode_suspend),
@@ -897,7 +896,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
)
if (a.steam && a.suspendPolicy != SessionPrefs.SUSPEND_NEVER) ToggleRow(
host, "background-downloads", stringResource(R.string.mode_background_downloads),
null,
stringResource(R.string.mode_background_downloads_hint),
a.steamDownloadsInBackground,
onChange = a.onSteamDownloadsInBackground,
)
@@ -1114,20 +1113,20 @@ private fun ScreenEffectsGroup(
SettingsGroup(stringResource(R.string.drawer_effects)) {
ChoiceRow(
host, "effects-profile", stringResource(R.string.screen_effects_target),
null, a.screenEffectsTargets,
stringResource(R.string.screen_effects_target_hint), a.screenEffectsTargets,
a.screenEffectsTarget, chipModifier = track("effects-profile"),
onPick = a.onScreenEffectsTarget,
)
ActionRow(
stringResource(R.string.screen_effects_reset),
null,
stringResource(R.string.screen_effects_reset_hint),
stringResource(R.string.hud_reset_button),
a.onScreenEffectsReset,
modifier = track("effects-reset"),
)
if (a.screenEffectsCanDelete) ActionRow(
stringResource(R.string.screen_effects_delete),
null,
stringResource(R.string.screen_effects_delete_hint),
stringResource(R.string.common_delete),
a.onScreenEffectsDelete,
modifier = track("effects-delete"),
@@ -1210,7 +1209,7 @@ private fun ScreenEffectsGroup(
private fun CardboardGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val c = a.cardboard
SettingsGroup(stringResource(R.string.cardboard_title)) {
ToggleRow(host, "cardboard", stringResource(R.string.cardboard_mode), null,
ToggleRow(host, "cardboard", stringResource(R.string.cardboard_mode), stringResource(R.string.cardboard_mode_hint),
c.enabled, chipModifier = track("cardboard")) { a.onCardboard(c.copy(enabled = it)) }
if (!c.enabled) return@SettingsGroup
ChoiceRow(host, "cardboard-source", stringResource(R.string.cardboard_source), null,
@@ -1684,6 +1683,8 @@ internal fun ComponentDownloadsDrawerGroup(
val installed = packages.map { it.file }.toSet()
val nightlyPicked = remember { mutableStateMapOf<String, Boolean>() }
SettingsGroup(stringResource(R.string.drawer_component_downloads)) {
Text(stringResource(R.string.drawer_component_downloads_hint), fontSize = 12.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
SettingsRow(stringResource(R.string.comp_nightlies_checked,
if (catalogAt > 0) java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT)
.format(java.util.Date(catalogAt * 1000)) else stringResource(R.string.comp_never)), null, stacked = true) {