feat(input): draw on-screen controls per virtual controller with a corner button and a simpler controller page

This commit is contained in:
Kurt Himebauch committed 2026-11-18 18:08:30 -05:00
1 parent 6ed281f78d
commit 0fba656ee2
20 files changed
+1295 -1146

No files matched your search

@@ -170,8 +170,6 @@ 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)
@@ -646,6 +644,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var steamDownloadsInBackground by mutableStateOf(false)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var onScreenButtonsVisible by mutableStateOf(false)
private var layoutOptions by mutableStateOf<List<Pair<String, String>>>(emptyList())
private var layoutChoice by mutableStateOf("")
private var layoutEditor by mutableStateOf<Triple<String, String, String>?>(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)
@@ -876,8 +880,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionState.deckPadListener = deckPadListener
openDeckRing("activity created")
bridge.setOnPlayerInput(::onPadInput)
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())
@@ -957,7 +964,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
hud = DroidDeckHudHost(this)
hud.onConfigChanged = { hudConfig = DroidDeckHudConfig.load(this) }
hud.passesTouchAt = ::controlTakesTouchAt
hud.attach(root, root.childCount)
hud.attach(root, onScreenControls?.let(root::indexOfChild)?.takeIf { it >= 0 } ?: root.childCount)
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
hud.onPresentingWindowChanged = {
CompositorHost.rearmFrameGen { applyFrameGen(force = true) }
@@ -1247,7 +1254,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
if (inputSettingsOpen) com.droiddeck.launcher.ui.InputSettingsDialog(
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 = primaryInputLayout?.name?.let { name -> controlsGameName()?.let { getString(R.string.osc_scope_game, name, it) } ?: getString(R.string.osc_scope_default, name) })
}
if (inputSettingsOpen && layoutEditor == null) com.droiddeck.launcher.ui.InputSettingsDialog(
onBack = { inputSettingsOpen = false; secondScreenPresentation?.refreshControls() },
onChanged = {
controllerSettings = ControllerPrefs.read(this@SessionActivity)
@@ -1431,16 +1445,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
frameGen = frameGen,
frameGenTargetGameId = frameGenTargetGameId()?.toString(),
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
},
frameGenTargetGameName = frameGenTargetGameName(),
hasGameOverride = frameGenHasGameOverride,
lossless = lossless,
oscMode = oscMode, suspendPolicy = suspendPolicy,
@@ -1708,15 +1713,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
},
onOsc = { v ->
SessionPrefs.setOscMode(this@SessionActivity, v)
controlsHiddenByTap = false
readPrefs()
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()
},
onEditSteamTouch = if (steamTouchAvailable && oscMode == SessionPrefs.OSC_STEAM_TOUCH && onScreenButtonsVisible) ({
drawerOpen = false
steamTouchControls?.startEditing()
}) else null,
layoutGame = controlsGameName(),
layoutOptions = layoutOptions,
layoutChoice = layoutChoice,
layoutHint = getString(if (controlsGameId() != null) R.string.osc_layout_this_game else R.string.osc_layout_default),
onLayout = ::chooseLayout,
onEditLayout = when {
layoutChoice == com.droiddeck.launcher.input.GameControls.STEAM -> if (steamTouchAvailable && onScreenButtonsVisible) ({
drawerOpen = false
steamTouchControls?.startEditing()
}) else null
primaryInputLayout?.editable == true -> ({ openLayoutEditor() })
else -> null
},
onSuspendPolicy = { policy ->
SessionPrefs.setSuspendPolicy(this@SessionActivity, SessionState.mode, policy)
suspendPolicy = policy
@@ -1779,21 +1792,6 @@ 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) },
@@ -2013,6 +2011,17 @@ 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
@@ -2030,6 +2039,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun loadFrameGenFor(appId: Long?) {
if (appId != controlsGame) { controlsGame = appId; uiHandler.post { refreshInputProfile(); updateOnScreenControls() } }
val profileId = appId?.toString()
frameGen = FrameGen.mode(this, profileId)
frameGenHasGameOverride = appId?.let {
@@ -3620,6 +3630,7 @@ 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)
}
@@ -3991,6 +4002,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
private fun onPadInput() {
noteControllerUse()
if (inputUsesPointer && !pointerLocked) return
lastPadInputMs = android.os.SystemClock.uptimeMillis()
uiHandler.removeCallbacks(cursorHide)
@@ -4355,14 +4367,70 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (started && displayId !in inputWindowDisplays && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
}
private fun refreshInputProfile() {
private fun controlsGameId(): Long? = frameGenTargetGameId()
private fun controlsGameName(): String? = controlsGameId()?.let { frameGenTargetGameName() }
/** The input library with the current game's main-screen layout selected, without saving it. */
private fun gameLibrary(): com.droiddeck.launcher.input.InputLibrary {
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val chosen = com.droiddeck.launcher.input.GameControls.bindings(this, controlsGameId())
?.takeIf { id -> library.bindings.any { it.id == id && !it.physical && it.layoutId?.let { l -> library.layouts.any { x -> x.id == l && x.supports(InputRole.PRIMARY) } } == true } }
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
}
private fun refreshLayoutOptions(library: com.droiddeck.launcher.input.InputLibrary) {
val steam = SessionState.mode == SessionService.MODE_STEAM
layoutOptions = listOf(com.droiddeck.launcher.input.InputLibraries.OVERLAY to getString(R.string.osc_layout_gamepad)) +
(if (steam) listOf(com.droiddeck.launcher.input.GameControls.STEAM to getString(R.string.osc_layout_steam)) else emptyList()) +
library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != com.droiddeck.launcher.input.InputLibraries.OVERLAY }.map { it.id to it.name }
layoutChoice = if (steam && com.droiddeck.launcher.input.GameControls.steamLayout(this, controlsGameId())) com.droiddeck.launcher.input.GameControls.STEAM
else primaryInputLayout?.id ?: com.droiddeck.launcher.input.InputLibraries.OVERLAY
}
private fun chooseLayout(id: String) {
val game = controlsGameId()
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val steam = id == com.droiddeck.launcher.input.GameControls.STEAM
runCatching {
val bindings = if (steam) null else {
var library = com.droiddeck.launcher.input.InputLibraries.read(this)
val layout = library.layouts.first { it.id == id }
library.bindings.firstOrNull { !it.physical && it.compatible(layout) }?.id ?: com.droiddeck.launcher.input.newInputId().also { newId ->
library = com.droiddeck.launcher.input.InputLibraries.update(this) {
it.withPreset(com.droiddeck.launcher.input.SavedInputBindings(newId, layout.name, false, layout.id))
}
}
}
if (game != null) com.droiddeck.launcher.input.GameControls.choose(this, game, bindings, steam)
else {
SessionPrefs.setSteamTouchLayout(this, steam)
if (bindings != null) com.droiddeck.launcher.input.InputLibraries.update(this) { it.selectPart(desktop, InputRole.PRIMARY, bindings) }
}
}.onFailure { Log.w(TAG, "could not choose layout $id", it) }
releasePads()
refreshInputProfile()
updateOnScreenControls()
}
private fun openLayoutEditor() {
val library = gameLibrary()
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val layout = primaryInputLayout ?: return
releasePads()
drawerOpen = false
layoutEditor = Triple(library.activeId(desktop), layout.id, library.activePart(desktop, InputRole.PRIMARY).bindings)
inputSettingsOpen = true
}
private fun refreshInputProfile() {
val library = gameLibrary()
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)
adaptiveSticks = primaryInputLayout?.adaptiveSticks
quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty()
refreshLayoutOptions(library)
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 }
@@ -5300,99 +5368,116 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
updateOnScreenPad()
val c = onScreenControls
glassesSlot = when {
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
c == null || c.visibility != View.VISIBLE || c.hidden != null -> 0
c.inputSurface.shownElements.any { it.id == com.droiddeck.launcher.input.KitLayout.KEYBOARD_ID } -> 2
else -> 1
}
}
private fun controlsPlan(): com.droiddeck.launcher.input.ControlsPresenter.Plan {
val steam = SessionState.mode == SessionService.MODE_STEAM
return com.droiddeck.launcher.input.ControlsPresenter.plan(com.droiddeck.launcher.input.ControlsPresenter.State(
mode = SessionPrefs.oscMode(this),
desktop = SessionState.mode == SessionService.MODE_DESKTOP,
virtualPad = !steam || SessionPrefs.builtinPad(this),
covered = pipUi || unfoldedPanel != null || pcKeyboardOpen || inputSettingsOpen || keyboardCoversPad(),
controllerInUse = controllerInUse && (PadBridge.anyControllerConnected() || SteamControllerBle.connected),
hiddenByTap = controlsHiddenByTap,
steamLayout = steam && com.droiddeck.launcher.input.GameControls.steamLayout(this, controlsGameId()),
bottomScreen = bottomGame?.surfaceView?.parent is android.view.ViewGroup,
))
}
private fun updateOnScreenPad() {
fun hideBottomControls() { bottomInputControls?.takeIf { it.visibility == View.VISIBLE }?.let { it.releaseAll(); it.visibility = View.GONE } }
val forced = File(Environment.getExternalStorageDirectory(), "Download/droiddeck-osc")
.takeIf { it.isFile }
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this)
val controls = onScreenControls ?: return
fun showPinned() {
controls.setPinnedOnly(true)
val pinned = controls.hasPinned && !pipUi && !inputSettingsOpen
if (!pinned) controls.releaseAll()
controls.visibility = if (pinned) View.VISIBLE else View.GONE
}
if (pipUi || unfoldedPanel != null || pcKeyboardOpen || inputSettingsOpen ||
(SessionState.mode == SessionService.MODE_STEAM && !SessionPrefs.builtinPad(this))) {
onScreenButtonsVisible = false
hideBottomControls()
showPinned()
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 }
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
applyTouchRouting()
return
}
val buttonsOnly = forced == SessionPrefs.OSC_STEAM_QAM
val wantsSteam = forced == SessionPrefs.OSC_STEAM_TOUCH && SessionState.mode == SessionService.MODE_STEAM
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
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))
}
bottomInputControls = bottom
}
bottom.updateLayout(primaryInputLayout)
bottom.setButtonsOnly(buttonsOnly)
bottom.setPinnedOnly(!drawn)
bottom.visibility = View.VISIBLE
if (!plan.shown) { steam.cancelEditing(); steam.releaseAll() }
steam.visibility = if (plan.shown) View.VISIBLE else View.GONE
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = plan.shown
applyTouchRouting()
return
}
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"
})
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
}
bottom.updateLayout(primaryInputLayout)
bottom.setHidden(plan.hidden)
bottom.visibility = View.VISIBLE
}
com.droiddeck.launcher.input.ControlsPresenter.Place.MAIN -> {
hideBottomControls()
controls.setHidden(plan.hidden)
controls.visibility = View.VISIBLE
}
else -> {
hideBottomControls()
controls.releaseAll()
controls.visibility = View.GONE
}
}
}
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 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()
}
private fun desktopTextInput() =
@@ -0,0 +1,40 @@
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 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.steamLayout -> Place.STEAM
state.bottomScreen -> Place.BOTTOM
else -> Place.MAIN
},
when {
state.hiddenByTap -> OnScreenControls.Hidden.BY_TAP
state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse -> OnScreenControls.Hidden.BY_CONTROLLER
else -> null
},
)
}
}
@@ -0,0 +1,24 @@
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 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) {
prefs(context).edit().apply { if (bindings == null) remove("$game.bindings") else putString("$game.bindings", bindings) }
.putBoolean("$game.steam", steam).apply()
}
}
@@ -10,7 +10,7 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 14
private const val VERSION = 15
private const val KEY = "library"
private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay"
@@ -29,10 +29,10 @@ object InputLibraries {
val version = raw?.let { JSONObject(it).getInt("version") } ?: 0
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(library)
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) {
@@ -141,11 +141,11 @@ object InputLibraries {
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 || origin.startsWith("migrated.layout.")) {
if (origin == OVERLAY) {
val (surfaceContext, metrics) = primaryDisplay(context)
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] }
val w = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val h = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
return KitLayout.elements(surfaceContext, PadKit.current(context), w, h) to w.toFloat() / h
}
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect }
}
@@ -157,29 +157,13 @@ 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 elements = LegacyGamepadLayout(surfaceContext, metrics.widthPixels.coerceAtLeast(1), metrics.heightPixels.coerceAtLeast(1)).elements()
val style = InputSurfaceStyle(settings.tint, settings.opacity)
val elements = emptyList<InputSurfaceElement>()
val style = InputSurfaceStyle(opacity = settings.opacity)
val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old ->
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style,
aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f))
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style)
}
var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
val migrated = mutableMapOf<Pair<String, String>, String>()
@@ -201,15 +185,6 @@ 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()
}
@@ -275,6 +250,17 @@ object InputLibraries {
return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate()
}
/** Gamepads saved by the old editor follow the virtual controller's kit again; their positions don't map onto the new controls. */
private fun kitGamepads(library: InputLibrary): InputLibrary {
var result = library
for (layout in library.layouts) {
val origin = layout.origin ?: layout.id
if (origin != OVERLAY && !origin.startsWith("migrated.layout.")) continue
result = result.withLayout(layout.copy(elements = emptyList(), origin = if (layout.id == OVERLAY) null else OVERLAY, aspect = 0f, scale = 1f))
}
return result.validate()
}
private fun migrationBindingId(library: InputLibrary, binding: String, layout: String): String {
val seed = JSONArray(listOf(binding, layout)).toString().toByteArray(Charsets.UTF_8)
val base = "migrated.bindings." + UUID.nameUUIDFromBytes(seed)
@@ -49,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 InputAction.Disabled
else defaultElementAction(element.id)
fun clickAction(element: InputSurfaceElement) = clicks[element.id]
?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() }
@@ -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 InputAction.Disabled
elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else defaultElementAction(id)
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
@@ -115,3 +115,10 @@ 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)
else -> InputAction.Disabled
}
@@ -0,0 +1,115 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
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.
*/
object KitLayout {
const val DPAD_ID = "kit:dpad"
const val KEYBOARD_ID = "builtin:keyboard"
private const val REF_W = 1600f
private const val REF_H = 900f
private const val MAX_HEIGHT_MM = 80f
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)
private fun shoulders() = listOf(
Spec(InputControl.LT, 140f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.LB, 140f, 148f, 88f, 28f, shape = InputButtonShape.PILL),
Spec(InputControl.RT, 1460f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.RB, 1460f, 148f, 88f, 28f, shape = InputButtonShape.PILL))
private fun face(cx: Float, cy: Float, r: Float, off: Float) = listOf(
Spec(InputControl.Y, cx, cy - off, r), Spec(InputControl.X, cx - off, cy, r), Spec(InputControl.B, cx + off, cy, r), Spec(InputControl.A, cx, cy + off, r))
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, 62f, shape = InputButtonShape.ROUNDED), Spec(InputControl.L5, 30f, 590f, 30f, 62f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.R4, 1570f, 470f, 30f, 62f, shape = InputButtonShape.ROUNDED), Spec(InputControl.R5, 1570f, 590f, 30f, 62f, shape = InputButtonShape.ROUNDED),
dpad(215f, 330f, 100f)) + face(1385f, 330f, 50f, 82f) + listOf(
Spec(InputControl.LS, 290f, 610f, 96f), Spec(InputControl.RS, 1310f, 610f, 96f),
Spec(InputControl.LEFT_PAD, 480f, 345f, 95f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1120f, 345f, 95f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.SELECT, 660f, 150f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 150f, 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, 56f, 92f) + listOf(
Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f),
Spec(InputControl.L3, 420f, 790f, 42f), Spec(InputControl.R3, 1180f, 790f, 42f),
Spec(InputControl.SELECT, 640f, 150f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 150f, 50f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 800f, 250f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 690f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf(
Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f), Spec(InputControl.R3, 1290f, 790f, 42f),
Spec(InputControl.SELECT, 690f, 162f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 162f, 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, safe: Rect = Rect(), scale: Float = 1f): List<InputSurfaceElement> {
if (width <= 0 || height <= 0) return emptyList()
val w = width.toFloat(); val h = height.toFloat()
val unit = min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale
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
}
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
}
return specs(kit).map { s ->
val cx = x(s.cx); val cy = y(s.cy); 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, s.name,
floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded()
}
}
/** 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): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val boxes = GamepadGeometry.layout(w, h, context.resources.displayMetrics.density, portrait)
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 = control.label) {
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) }
put(left, 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(right, 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))
}
}
@@ -1,362 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.*
internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int, private val 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
var cx = 0f
var cy = 0f
val halfW get() = if (id in shoulderIds) radius * SHOULDER_WIDTH else radius
val halfH get() = if (id in shoulderIds) radius * SHOULDER_HEIGHT else radius
}
private val controls = listOf(
Control("up", "dpad", -1, 30f, 0f, -50f),
Control("right", "dpad", -1, 30f, 50f, 0f),
Control("down", "dpad", -1, 30f, 0f, 50f),
Control("left", "dpad", -1, 30f, -50f, 0f),
Control("ls", "ls", 0, 48f, 0f, 0f),
Control("rs", "rs", 1, 48f, 0f, 0f),
Control("a", "face", -1, 30f, 0f, 50f),
Control("b", "face", -1, 30f, 50f, 0f),
Control("x", "face", -1, 30f, -50f, 0f),
Control("y", "face", -1, 30f, 0f, -50f),
Control("lb", "lb", -1, 24f, 0f, 0f),
Control("rb", "rb", -1, 24f, 0f, 0f),
Control("lt", "lt", -1, 24f, 0f, 0f),
Control("rt", "rt", -1, 24f, 0f, 0f),
Control("select", "select", -1, 20f, 0f, 0f),
Control("start", "start", -1, 20f, 0f, 0f),
Control("guide", "guide", -1, 22f, 0f, 0f),
Control("qam", "qam", -1, 22f, 0f, 0f),
)
private val groups = controls.map { it.group }.distinct()
private fun dp(value: Float) = value * resources.displayMetrics.density
private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit
private fun fitScale(): Float {
val metrics = resources.displayMetrics
val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
}
private fun pxPerMm(dpi: Float): Float {
val nominal = resources.displayMetrics.densityDpi.toFloat()
return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
}
private fun placeAuto(w: Float, h: Float) {
val metrics = resources.displayMetrics
val mmX = pxPerMm(metrics.xdpi)
val mmY = pxPerMm(metrics.ydpi)
val usableW = w - safe.left - safe.right
val usableH = h - safe.top - safe.bottom
val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
val gap = dp(12f)
val floor = BOTTOM_MARGIN_MM * mmY
val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
put("ls", safe.left + inboard, restY)
put("face", w - safe.right - inboard, restY)
besideBelow("dpad", "ls", 1f, gap, floor)
besideBelow("rs", "face", -1f, gap, floor)
val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
val shoulderY = if (phone) safe.top + floor + halfH("lb")
else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
shoulders("face", "rb", "rt", -1f, gap, shoulderY)
val bottom = h - safe.bottom - floor - extent("guide")
val spread = extent("guide") + gap / 2f
put("guide", w / 2f - spread, bottom)
put("qam", w / 2f + spread, bottom)
val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
put("select", inner, restY)
put("start", w - inner, restY)
if (phone) {
val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
put("select", top, shoulderY)
put("start", w - top, shoulderY)
}
if (crowded("select", gap) || crowded("start", gap)) {
above("select", "dpad", gap)
val (sx, sy) = centre("select")
put("start", w - sx, sy)
if (crowded("start", gap)) above("start", "rs", gap)
}
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
val row = centre("select").second
put("guide", w / 2f - spread, row)
put("qam", w / 2f + spread, row)
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
val top = safe.top + dp(8f) + extent("guide")
put("guide", w / 2f - spread, top)
put("qam", w / 2f + spread, top)
}
}
}
private fun drop(group: String, anchor: String, gap: Float): Float =
(extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
val (ax, ay) = centre(anchor)
val reach = extent(anchor) + extent(group) + gap
val floor = height - safe.bottom - margin - extent(group)
val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
val dx = sqrt(max(0f, reach * reach - dy * dy))
put(group, ax + inward * dx, ay + dy)
}
private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
val (ax, _) = centre(anchor)
val spread = extent(bumper) + gap / 2f
put(bumper, ax + inward * spread, y)
put(trigger, ax - inward * spread, y)
}
private fun above(group: String, anchor: String, gap: Float) {
val (ax, ay) = centre(anchor)
put(group, ax, ay - extent(anchor) - gap - extent(group))
}
private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
val (x, y) = centre(group)
return groups.any { other ->
if (other == group || other == except) return@any false
val (ox, oy) = centre(other)
val dx = x - ox
val dy = y - oy
sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
}
}
private fun members(group: String) = controls.filter { it.group == group }
private fun centre(group: String): Pair<Float, Float> {
val first = members(group).first()
return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
}
private fun extent(group: String): Float = members(group).maxOf { control ->
sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
}
private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
private fun put(group: String, x: Float, y: Float) {
for (control in members(group)) {
control.cx = x + scaled(control.offsetXDp)
control.cy = y + scaled(control.offsetYDp)
}
}
private fun clamp(group: String) {
val list = members(group)
val margin = dp(4f)
val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
if (dx == 0f && dy == 0f) return
for (control in list) { control.cx += dx; control.cy += dy }
}
fun elements(previousStickGeometry: Boolean = false): List<InputSurfaceElement> {
fit = fitScale()
controls.forEach { it.radius = scaled(it.radiusDp) }
placeAuto(width.toFloat(), height.toFloat())
for ((group, position) in ControllerPrefs.layout(context, width, height)) {
if (group in groups && position.first.isFinite() && position.second.isFinite()) put(group, position.first * width, position.second * height)
}
groups.forEach(::clamp)
val result = controls.filter {
settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton)
}.map { c ->
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded()
}.toMutableList()
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,
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 {
val extra = e.width * (STICK_REACH - 1f)
return when (e.control) {
InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) }
InputControl.RS -> e.copy(width = (e.width + extra).coerceAtMost(1f - e.x))
else -> e
}
}
private fun widenStick(e: InputSurfaceElement): InputSurfaceElement {
val extra = e.width * (STICK_REACH - 1f)
val width = e.width + extra
return when (e.control) {
InputControl.LS -> e.copy(x = (e.x - extra).coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width)
InputControl.RS -> e.copy(x = e.x.coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width)
else -> e
}
}
private companion object {
const val MIN_FACE_MM = 9.5f
const val FULL_SIZE_HEIGHT_MM = 85f
const val BOTTOM_MARGIN_MM = 5f
const val DROP_DEGREES = 35.0
const val PHONE_MAX_HEIGHT_MM = 90f
const val SHOULDER_WIDTH = 1.45f
const val SHOULDER_HEIGHT = 0.8f
val shoulderIds = setOf("lb", "rb", "lt", "rt")
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,103 +3,77 @@ 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.Typeface
import android.graphics.RectF
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.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 viewWidth = 0
private var viewHeight = 0
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 val corner = CornerButton(context)
var hidden: Hidden? = null
private set
var isQuickHidden = false
private set
var isPinnedOnly = false
private set
val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true
val inputSurface: com.droiddeck.launcher.ui.InputSurfaceView get() = surface
/** 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 onTouchMiss: ((MotionEvent) -> Unit)?
get() = surface.onTouchMiss
set(value) { surface.onTouchMiss = value }
init {
addView(surface, LayoutParams(-1, -1))
val size = (QUICK_HIT_DP * 2 * resources.displayMetrics.density).toInt()
addView(quickToggle, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
val size = (CORNER_HIT_DP * resources.displayMetrics.density).toInt()
addView(corner, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
}
fun updateLayout(value: SavedInputLayout?) {
if (layout == value) return
val kit = PadKit.current(context)
if (layout == value && surface.kit == kit) return
releaseAll()
layout = value
surface.kit = kit
render()
}
fun setButtonsOnly(enabled: Boolean) {
if (isButtonsOnly == enabled) return
fun setHidden(value: Hidden?) {
if (hidden == value) return
releaseAll()
isButtonsOnly = enabled
isQuickHidden = false
hidden = value
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 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()
surface.updateStyle(style)
quickToggle.tint = style.tint
quickToggle.alpha = style.opacity / 100f
quickToggle.visibility = if (isButtonsOnly || isPinnedOnly || layout == null || dock != null) GONE else VISIBLE
quickToggle.invalidate()
surface.updateCustomLayout(if (hidden != null) emptyList() else OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock))
surface.updateStyle(layout?.style ?: InputSurfaceStyle())
corner.visibility = if (layout == null || dock != null) GONE else VISIBLE
corner.alpha = (layout?.style?.opacity ?: 100) / 100f
corner.invalidate()
}
fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y) ||
quickToggle.visibility == VISIBLE && x >= quickToggle.left && x < quickToggle.right && y >= quickToggle.top && y < quickToggle.bottom
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
fun releaseAll() = surface.releaseInputs()
fun reload() { releaseAll(); placements.clear(); render() }
fun reload() { releaseAll(); surface.kit = PadKit.current(context); render() }
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val w = MeasureSpec.getSize(widthMeasureSpec)
@@ -116,14 +90,14 @@ 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
val margin = (CORNER_MARGIN_DP * resources.displayMetrics.density).toInt()
val params = corner.layoutParams as LayoutParams
val left = (cutout?.safeInsetLeft ?: 0) + margin
val bottom = (cutout?.safeInsetBottom ?: 0) + margin
if (params.leftMargin != left || params.bottomMargin != bottom) {
params.leftMargin = left
params.bottomMargin = bottom
quickToggle.layoutParams = params
corner.layoutParams = params
}
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
if (fresh != safe) {
@@ -133,42 +107,45 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
return super.onApplyWindowInsets(insets)
}
private inner class QuickToggle(context: Context) : View(context) {
var tint: Int? = ControllerPrefs.STEAM_BLUE
private val density = resources.displayMetrics.density
private inner class CornerButton(context: Context) : View(context) {
private val art = PadArt(context)
private val badge = Paint(Paint.ANTI_ALIAS_FLAG)
private var armed = false
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
}
private var held = false
private val hold = Runnable { if (armed) { held = true; performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } }
override fun onDraw(canvas: Canvas) {
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)
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)
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> armed = true
MotionEvent.ACTION_CANCEL -> armed = false
MotionEvent.ACTION_DOWN -> { armed = true; held = false; postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()); invalidate() }
MotionEvent.ACTION_CANCEL -> { armed = false; removeCallbacks(hold); invalidate() }
MotionEvent.ACTION_UP -> {
if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
removeCallbacks(hold)
if (armed && held) post { onCornerHold?.invoke() }
else if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
setQuickHidden(!isQuickHidden)
val next = if (hidden == null) Hidden.BY_TAP else null
setHidden(next)
onCornerTap?.invoke(next)
}
armed = false
invalidate()
}
}
return true
@@ -176,9 +153,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
}
private companion object {
const val QUICK_CENTER_DP = 34f
const val QUICK_HIT_DP = 26f
const val QUICK_RADIUS_DP = 18f
const val PLACEMENT_CACHE = 4
const val CORNER_HIT_DP = 48f
const val CORNER_MARGIN_DP = 4f
}
}
@@ -2,10 +2,8 @@ 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) {
@@ -21,25 +19,18 @@ object OnScreenLayout {
}
}
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
/** The built-in gamepad keeps no positions until it is edited; until then it follows the virtual controller's kit. */
fun generated(layout: SavedInputLayout) = layout.elements.isEmpty() && (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY)
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)
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null): List<InputSurfaceElement> {
layout ?: return emptyList()
if (width <= 0 || height <= 0) return layout.elements
if (generated(layout)) {
val kit = PadKit.current(context)
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)
}
val byId = (placed + others).associateBy { it.id }
return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
return fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
@@ -73,35 +64,8 @@ object OnScreenLayout {
}
}
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
}
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)
}
}
@@ -0,0 +1,39 @@
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
}
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))
}
}
@@ -119,6 +119,7 @@ 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 }
@@ -281,56 +282,54 @@ 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)
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
if (alpha < 255) canvas.saveLayerAlpha(x - r * 1.5f, y - r * 1.5f, x + r * 1.5f, y + r * 1.5f, alpha)
when (e.type) {
SteamTouchConfig.DPAD -> drawDpad(canvas, e, x, y, r)
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)
canvas.restore()
}
SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> {
canvas.drawCircle(x, y, r, stroke)
val f = fingers.values.firstOrNull { it.element?.type == e.type }
if (f != null && !editing) {
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
var kx = 0f; var ky = 0f
if (f != null) {
val d = hypot(f.x - x, f.y - y)
val k = if (d > r) r / d else 1f
val kx = x + (f.x - x) * k
val ky = y + (f.y - y) * k
canvas.drawCircle(kx, ky, r * 0.42f, fill)
kx = (f.x - x) * k * .54f; ky = (f.y - y) * k * .54f
}
art.stick(canvas, x, y, r, PadKit.STEAM_DECK, kx, ky, f != null)
}
SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> {
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)
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
canvas.save(); canvas.translate(x - r * 1.3f, y - r * .85f)
art.trackpad(canvas, r * 2.6f, r * 1.7f, f != null, (f?.x ?: x) - x + r * 1.3f, (f?.y ?: y) - y + r * .85f)
canvas.restore()
if (editing) art.text(canvas, context.getString(R.string.deck_surface_trackpad), x, y, r * .3f, Color.argb(128, 255, 255, 255))
}
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, 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 })
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)
}
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, alpha, pressed)
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)
}
}
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)
canvas.restore()
}
private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT,
@@ -350,53 +349,29 @@ class SteamTouchControls(
canvas.restore()
}
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)
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)
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 com.droiddeck.launcher.ui.PadArt.INK
if (icon != null) {
val s = r * 0.62f
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)
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) })
return
}
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 {
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 {
shown.length <= 1 -> r * 0.9f
shown.length <= 2 -> r * 0.66f
shown.length <= 5 -> r * 0.4f
else -> r * 0.3f
}
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)
art.text(canvas, if (shown.length > 10) shown.take(9) + "…" else shown, x, y, size, ink, r * 1.8f)
}
private fun drawDots(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
@@ -639,12 +639,25 @@ object SessionPrefs {
prefs(context).getString("shape", null)
?: if (context.packageManager.hasSystemFeature("android.hardware.sensor.hinge_angle")) SHAPE_WIDE else SHAPE_AUTO
fun oscMode(context: Context): String = prefs(context).getString("osc", OSC_AUTO) ?: OSC_AUTO
/** Auto, Always or Never. Older builds also stored the Steam layout and a buttons-only mode here. */
fun oscMode(context: Context): String = when (val mode = prefs(context).getString("osc", OSC_AUTO)) {
OSC_ALWAYS, OSC_NEVER -> mode
OSC_STEAM_QAM -> OSC_ALWAYS
else -> OSC_AUTO
}
fun setOscMode(context: Context, mode: String) {
prefs(context).edit().putString("osc", mode).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()
}
fun linuxDriver(context: Context): String =
prefs(context).getString("linuxDriver", null)
?: prefs(context).getString("linuxDriver.steam", null)
@@ -270,7 +270,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
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)),
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)) {
@@ -63,40 +63,24 @@ 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, private var gamepad: GamepadScaler? = null, snap: Boolean = true) {
val hasGamepad get() = gamepad != null
private val defaultsFrame: Float = 0f, snap: Boolean = true) {
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 adding by mutableStateOf(false)
var popover by mutableStateOf<EditorPopover?>(null)
var confirmDiscard 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<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
private var scaleBase by mutableStateOf<Pair<List<InputSurfaceElement>, List<InputSurfaceElement>>?>(null)
private var scaleValue by mutableIntStateOf(100)
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 }
val scale get() = if (scaleBase?.second == elements) scaleValue else 100
val positioned get() = defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) }?.takeIf { it != elements }
private fun refit(placed: List<InputSurfaceElement>, from: Float): List<InputSurfaceElement> {
if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed
@@ -106,31 +90,34 @@ 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, scaler: GamepadScaler? = gamepad) {
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float) {
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 } ?: 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)
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 } }
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 }; actions = actions - id; clicks = clicks - id; selected = null }
fun resizeSelected(factor: Float) {
val e = element ?: return
checkpoint()
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
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 }
}
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)
}
@Composable
fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) {
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null, scope: String? = null) {
val context = LocalContext.current
val host = LocalInputActivity.current ?: context.findActivity() as? ComponentActivity
val library = remember { InputLibraries.read(context) }
@@ -139,17 +126,12 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val layoutUsers = library.usersOfLayout(savedLayout.id).size
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)
SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context))
val start = if (OnScreenLayout.generated(savedLayout) && defaults != null) savedLayout.copy(elements = defaults.first, aspect = defaults.second) else savedLayout
SurfaceDraft(start, savedBindings, defaults?.first, defaults?.second ?: 0f, 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)
@@ -160,7 +142,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
}
}
val remote = target != null && target.displayId != host?.window?.decorView?.display?.displayId
fun leave() { if (draft.dirty) discard = true else onDismiss() }
fun leave() { if (draft.dirty) draft.confirmDiscard = true else onDismiss() }
fun save() {
runCatching {
InputLibraries.update(context) { latest ->
@@ -209,8 +191,23 @@ 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 = scope ?: if (layoutUsers > 1) stringResource(R.string.input_editor_shared, layoutUsers) else savedLayout.name
when {
draft.properties && element != null -> {
target == null -> SettingsPage(rememberMenuHost(), savedLayout.name, ::leave) {
Text(stringResource(R.string.input_display_unavailable))
PrimaryButton(stringResource(R.string.input_editor_done)) { save() }
}
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, onDismiss)
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, failure, ::save, ::leave, onDismiss)
if (draft.properties && element != null) Surface(Modifier.align(Alignment.CenterEnd).fillMaxHeight().fillMaxWidth(.44f),
color = MaterialTheme.colorScheme.surface, shadowElevation = 12.dp) {
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),
@@ -228,37 +225,11 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
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))
PrimaryButton(stringResource(R.string.input_editor_done)) { save() }
}
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)
}
else -> Box(Modifier.fillMaxSize()) {
SurfaceCanvas(draft, transparent = host is SessionActivity && role == InputRole.PRIMARY)
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
@@ -267,70 +238,145 @@ 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.adding
view.isEnabled = !draft.properties && draft.popover == null && !draft.confirmDiscard
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h) }
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 FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit) {
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, failure: String?, onSave: () -> Unit, onLeave: () -> Unit, onDiscard: () -> Unit) {
val context = LocalContext.current
BoxWithConstraints(Modifier.fillMaxSize()) {
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
}
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
}
.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.input_hidden_count, draft.hiddenDefaults().size), compact = true) {
draft.popover = if (draft.popover == EditorPopover.HIDDEN) null else EditorPopover.HIDDEN
}
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions() }
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)
}
}
Text(scope, Modifier.background(MaterialTheme.colorScheme.background.copy(alpha = .7f), RoundedCornerShape(50)).padding(horizontal = 12.dp, vertical = 4.dp),
style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
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 AddRows(draft: SurfaceDraft) {
val context = LocalContext.current
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()
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) {
private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: () -> Unit, onDiscard: () -> 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.adding = true }
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_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) {
@@ -352,9 +398,7 @@ 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.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
}
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) }
}
} ?: Text(stringResource(R.string.input_editor_hint))
}
@@ -1,17 +1,12 @@
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
@@ -36,7 +31,9 @@ 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.PadBridge
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.pcKeyLabel
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.atan2
@@ -51,7 +48,11 @@ 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
@@ -144,7 +145,6 @@ 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()
}
@@ -192,12 +192,12 @@ class InputSurfaceView(
}
}
}
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) }
canvas.clipChildren = customLayout.none(::adaptive)
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, element.control == InputControl.RIGHT_PAD, source = source)
InputElementKind.TRACKPAD -> TrackpadView(context, source)
InputElementKind.DPAD -> DirectionPad(context, element, source)
else -> HoldButton(context, element, source)
}.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } })
@@ -267,64 +267,12 @@ 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) {
@@ -346,38 +294,58 @@ class InputSurfaceView(
override fun onDraw(canvas: Canvas) {
val lit = if (element.toggle) source?.latched == true else down
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
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
when {
element.id == KitLayout.KEYBOARD_ID && element.icon == InputButtonIcons.KEYBOARD -> art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, 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
bitmap?.let {
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)
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)
canvas.drawBitmap(it, null, imageRect, labelPaint)
return
}
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)
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)
}
fun press(pointer: Int, pressed: Boolean, cancelled: Boolean = false) {
@@ -398,8 +366,7 @@ class InputSurfaceView(
}
}
private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true,
private val source: InputSurfaceSource? = null) : Surface(context) {
private inner class TrackpadView(context: Context, 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 {
@@ -416,29 +383,9 @@ 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) {
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)
}
art.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY)
}
@SuppressLint("ClickableViewAccessibility")
@@ -510,55 +457,31 @@ 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)
fun reach() = min(width, height) * if (classic(element)) CLASSIC_REACH else PANEL_REACH
private fun radius() = min(width, height) / 2f - 3 * density
fun reach() = radius() * STICK_REACH
fun captures(x: Float, y: Float): Boolean {
val cx = centreX()
val dx = if (element.control == InputControl.LS) maxOf(0f, x - cx) else x - cx
val limit = reach() * ADAPTIVE_REACH
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
return dx * dx + (y - height / 2f) * (y - height / 2f) <= limit * limit
}
fun centreX() = when {
!classic(element) || width <= height -> width / 2f
element.control == InputControl.LS -> width - height / 2f
else -> height / 2f
}
fun centreX() = width / 2f
override fun onDraw(canvas: Canvas) {
if (hideWhenIdle && !touching) return
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)
val r = radius()
val travel = r * KNOB_TRAVEL / reach().coerceAtLeast(1f)
art.stick(canvas, cx, cy, r, kit, knobX * travel, knobY * travel, touching || clicking)
if (!element.showLabel) return
labelPaint.color = if (touching) ACCENT else TEXT
drawDirectionLabels(canvas, source, false, cx, cy, reach() * 1.32f, reach() * 0.68f, labelPaint)
labelPaint.color = PadArt.INK
drawDirectionLabels(canvas, source, false, cx, cy, r * .66f, r * .34f, labelPaint)
}
@SuppressLint("ClickableViewAccessibility")
@@ -621,30 +544,15 @@ 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 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)
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)
}
@SuppressLint("ClickableViewAccessibility")
@@ -683,48 +591,21 @@ class InputSurfaceView(
companion object {
private const val CLICK_MS = 300L
private const val STICK_TAP_MS = 200L
private const val CLASSIC_REACH = 0.5f
private const val PANEL_REACH = 0.30f
private const val STICK_REACH = .62f
private const val KNOB_TRAVEL = .54f
private const val HIT_SLACK = 0.25f
private const val ADAPTIVE_CLEARANCE_PX = 5f
private val ADAPTIVE_REACH = 1.4f * kotlin.math.sqrt(1.5f)
private const val CORNER = 20f
private const val ADAPTIVE_REACH = 1.71f
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 TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
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 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 fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating
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)
@@ -749,16 +630,6 @@ 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 {
@@ -299,8 +299,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
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,
@@ -0,0 +1,354 @@
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.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)
}
fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val vw = min(w * .8f, h * .4f); val vh = vw * 2.5f
val cx = w / 2f; val cy = h / 2f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vw / 2), pressed)
text(canvas, label, cx, cy, vw * .4f, 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) {
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) {
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) }
}
}
@@ -293,7 +293,12 @@ class DrawerActions(
val onAchievements: (() -> Unit)? = null,
val achievementsProgress: Pair<Int, Int>? = null,
val onOsc: (String) -> Unit,
val onEditSteamTouch: (() -> Unit)? = null,
val layoutGame: String? = null,
val layoutOptions: List<Pair<String, String>> = emptyList(),
val layoutChoice: String = "",
val layoutHint: String? = null,
val onLayout: (String) -> Unit = {},
val onEditLayout: (() -> Unit)? = null,
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
val onRumble: (Boolean) -> Unit = {},
val onSuspendPolicy: (String) -> Unit,
@@ -339,10 +344,6 @@ 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 = {},
@@ -658,28 +659,22 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
if (!a.glassesOutput) CardboardGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.CONTROLLER -> {
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), 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),
SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)),
type, chipModifier = focus.track(page, "pad-type"), onPick = a.onPadType)
SettingsGroup(a.layoutGame?.let { stringResource(R.string.osc_group_for, it) } ?: stringResource(R.string.mode_osc)) {
if (a.layoutOptions.isNotEmpty()) ChoiceRow(host, "osc-layout", stringResource(R.string.osc_layout), a.layoutHint,
a.layoutOptions, a.layoutChoice, chipModifier = focus.track(page, "osc-layout"), onPick = a.onLayout)
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"))
}
a.controller?.let { c ->
ToggleRow(host, "rumble", stringResource(R.string.ctrl_rumble), null, c.rumble,
chipModifier = focus.track(page, "rumble"), onChange = a.onRumble)
SettingsRow(stringResource(R.string.osc_show), stringResource(R.string.osc_show_hint), stacked = true) {
SegmentedTabs(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)), a.oscMode,
tabModifier = { focus.track(page, "osc-$it") }, onPick = a.onOsc)
}
}
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)),
ChoiceRow(host, "touch", stringResource(R.string.input_touches), stringResource(R.string.input_touches_hint),
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"))
@@ -698,26 +693,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
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)
@@ -727,30 +702,22 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
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_page_controller)) {
a.padType?.let { type ->
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),
SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)),
type, chipModifier = focus.track(page, "pad-type"), onPick = a.onPadType)
}
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), stringResource(R.string.input_physical_hint), stringResource(R.string.ctrl_edit),
a.onInputSettings, modifier = focus.track(page, "remap"))
}
SettingsGroup(stringResource(R.string.drawer_keyboard)) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(8.dp)) {
@@ -770,28 +737,57 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
),
a.wowChat, chipModifier = focus.track(page, "wow-chat"), onPick = a.onWowChat,
)
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) })
}
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),
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)
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"))
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.SECOND_SCREEN -> {