fix(input): restore the controls, panels and settings #1439 removed (#2238)

* fix(input): restore on-screen touch behaviour: slide between buttons, mouse pass-through, keyboard on release, overlay haptics, stick reach and hit areas

* fix(dual-screen): restore second-screen bars, swapped Terminal and Deck panel tabs

* fix(input): fit on-screen layouts to the real view size, cutout, Steam + QAM mode and unfolded strip

* fix(input): unfolded strip keeps press haptics

* fix(input): restore layout import/export, element editor rows and layout tools

Bring back .icp layout import and export on the saved layouts page, the
per-element image, opacity and label controls, a uniform size slider and
reset positions in the layout editor, and non-destructive Steam, QAM and
keyboard button toggles stored on the layout style. Remove strings left
unused by the input profile unification.

* fix(input): keep hit slack to gamepad-shaped buttons and fit touch tests to saved layout geometry

* fix(input): button size regenerates the gamepad and scales spacing

A generated gamepad now stores its button size and is regenerated at that
size, so spacing follows the radius and the layout keeps regenerating on
rotation. Edited layouts scale positions from their anchor edge or centre
so gaps grow and shrink with the controls.

* fix(input): button size rescales moved gamepads around the generator

Gamepad layouts that no longer match the generated positions exactly were
scaled element by element from screen thirds, which split the face buttons
and D-pad across anchors. Gamepad controls now take the generator's
positions at the new size plus each control's own offset from the
generated position, so groups keep their shape and spacing.
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-07 16:36:23 -05:00
1 parent a33954b8bd
commit 8fa30b99f9
70 files changed
+2383 -1789

No files matched your search

@@ -79,6 +79,7 @@ import com.droiddeck.launcher.input.OnScreenControls
import com.droiddeck.launcher.input.InputRouter
import com.droiddeck.launcher.input.InputOutput
import com.droiddeck.launcher.input.InputCommand
import com.droiddeck.launcher.input.quickButton
import com.droiddeck.launcher.input.InputProfiles
import com.droiddeck.launcher.input.InputProfile
import com.droiddeck.launcher.input.InputAction
@@ -160,6 +161,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
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 fun applyGameAlignment() {
@@ -173,7 +175,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, alignment)
}
private var unfoldedPanel by mutableStateOf<com.droiddeck.launcher.ui.InputSurfaceView?>(null)
private var unfoldedPanel by mutableStateOf<OnScreenControls?>(null)
private var unfoldedColumn: android.widget.LinearLayout? = null
private lateinit var sessionRoot: FrameLayout
private var inputRouter: InputRouter? = null
private var physicalInputBindings: com.droiddeck.launcher.input.PhysicalInputBindings? = null
@@ -1416,6 +1419,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
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) },
@@ -2813,7 +2824,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
return onScreenControls?.let { takes(it, it::takesTouchAt) } == true ||
steamTouchControls?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true
unfoldedPanel?.let { takes(it, it::takesTouchAt) } == true ||
unfoldedColumn?.getChildAt(0)?.let { takes(it) { _, _ -> true } } == true
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
@@ -3401,6 +3413,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
DroidDeckTheme { SessionMenu(docked = true) }
},
onSwap = if (bottomSwapAvailable && com.droiddeck.launcher.input.DualScreen.builtIn(target)) ({ putGameOnBottom(true) }) else null,
onDeckPanel = ::selectDeckPanel,
dashboard = if (bottomPages().isEmpty()) null else ({
DroidDeckTheme {
BottomDashboard(
@@ -3511,10 +3524,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun refreshInputProfile() {
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
val desktop = loadingMode() == SessionService.MODE_DESKTOP
inputProfile = library.compileActive(desktop, secondScreenMode.bindings)
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this))
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
adaptiveSticks = primaryInputLayout?.adaptiveSticks
secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.bindings)
quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty()
secondaryInputLayout = library.panelLayout(desktop, secondScreenMode.panel(this))
inputUsesLocalActions = InputControl.padControls.any { inputProfile.action(InputRole.PHYSICAL, it) !is InputAction.Native }
inputUsesPointer = inputProfile.bindings.values.any { bindings ->
bindings.values.any { it is InputAction.Pointer || it is InputAction.MouseButton || it is InputAction.Scroll }
@@ -3527,8 +3541,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
DeckControls.refresh()
onScreenControls?.updateLayout(primaryInputLayout)
bottomInputControls?.updateLayout(primaryInputLayout)
unfoldedPanel?.updateCustomLayout(primaryInputLayout?.elements.orEmpty())
unfoldedPanel?.updateStyle(primaryInputLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
unfoldedPanel?.updateLayout(primaryInputLayout)
updateOnScreenPad()
secondScreenPresentation?.refreshControls()
}
@@ -3537,6 +3550,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
}
private fun selectDeckPanel(panel: com.droiddeck.launcher.input.DeckPanel) {
if (SessionPrefs.deckPanel(this) == panel) return
releasePads()
SessionPrefs.setDeckPanel(this, panel)
refreshInputProfile()
}
private fun chooseUnfoldedControls(on: Boolean) {
SessionPrefs.setUnfoldedControls(this, on)
unfoldedControls = on
@@ -3573,19 +3593,35 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, if (wanted) "unfolded controls: game ${width}x$gameHeight, controls ${width}x${height - gameHeight}"
else "unfolded controls: game full screen")
}
val dock = com.droiddeck.launcher.input.OnScreenLayout.Dock(!com.droiddeck.launcher.session.SessionDisplay.foldable(this), SessionState.deckPad)
var panel = unfoldedPanel
if (!wanted) {
if (panel != null) { sessionRoot.removeView(panel); unfoldedPanel = null; updateOnScreenControls() }
return
if (panel != null && (!wanted || panel.dock != dock)) {
sessionRoot.removeView(unfoldedColumn)
unfoldedColumn = null
unfoldedPanel = null
panel = null
if (!wanted) updateOnScreenControls()
}
if (!wanted) return
if (panel == null) {
panel = com.droiddeck.launcher.ui.InputSurfaceView(this, padBridge, primaryInputLayout?.elements.orEmpty(), InputRole.PRIMARY,
primaryInputLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
sessionRoot.addView(panel, sessionRoot.indexOfChild(surfaceView) + 1)
panel = OnScreenControls(this, padBridge, dock).also { it.updateLayout(primaryInputLayout) }
val column = android.widget.LinearLayout(this).apply {
orientation = android.widget.LinearLayout.VERTICAL
addView(unfoldedBar(), android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
(com.droiddeck.launcher.ui.BAR_HEIGHT.value * resources.displayMetrics.density + 0.5f).toInt()))
addView(panel, android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f))
}
sessionRoot.addView(column, sessionRoot.indexOfChild(surfaceView) + 1)
unfoldedColumn = column
unfoldedPanel = panel
updateOnScreenControls()
}
panel.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
unfoldedColumn?.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height - gameHeight, Gravity.BOTTOM)
}
private fun unfoldedBar(): View = com.droiddeck.launcher.ui.bottomScreenBarView(this) {
com.droiddeck.launcher.ui.sessionBarModel(getString(R.string.deck_tab_gamepad), { chooseUnfoldedControls(false) },
{ drawerOpen = true }, ::tapSteamButton, ::tapQam)
}
private fun bottomKeyboardPresentation(): SecondScreenPresentation? {
@@ -3725,7 +3761,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
private fun panelMode(mode: SecondScreenMode) {
val rebind = secondScreenMode.bindings != mode.bindings
val rebind = secondScreenMode.panel(this) != mode.panel(this)
secondScreenMode = mode
SessionState.secondScreenMode = mode
if (rebind) refreshInputProfile()
@@ -4210,7 +4246,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
glassesSlot = when {
c == null || c.visibility != View.VISIBLE -> 0
c.isButtonsOnly -> -1
controllerSettings?.keyboardButton != false -> 2
primaryInputLayout?.let { l -> l.elements.any { it.quickButton == InputCommand.KEYBOARD && !l.style.hides(it) } }
?: (controllerSettings?.keyboardButton != false) -> 2
else -> 1
}
}
@@ -4996,10 +5033,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val swapBack = { putGameOnBottom(false) }
val steam = SessionState.mode == SessionService.MODE_STEAM
val openMenu = { drawerOpen = true }
fun bar(title: String?, extras: List<com.droiddeck.launcher.ui.BarExtra> = emptyList()) = com.droiddeck.launcher.ui.BottomBarModel(
title, openMenu, openMenu, if (steam) ({ tapSteamButton() }) else null, if (steam) ({ tapQam() }) else null,
extras + com.droiddeck.launcher.ui.BarExtra(getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, onClick = swapBack),
)
fun bar(title: String?, extras: List<com.droiddeck.launcher.ui.BarExtra> = emptyList(), tabs: com.droiddeck.launcher.ui.BarTabs? = null) =
com.droiddeck.launcher.ui.BottomBarModel(
title, openMenu, openMenu, if (steam) ({ tapSteamButton() }) else null, if (steam) ({ tapQam() }) else null,
extras + com.droiddeck.launcher.ui.BarExtra(getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, onClick = swapBack),
tabs = tabs,
)
val keyboardExtra = com.droiddeck.launcher.ui.BarExtra(getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) {
keyboard?.toggle()
}
val profileLayout = secondaryInputLayout
androidx.compose.foundation.layout.Box(
Modifier.fillMaxSize().background(androidx.compose.ui.graphics.Color.Black)
@@ -5014,16 +5056,34 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
},
modifier = Modifier.fillMaxSize(),
)
secondScreenMode.controls && (secondScreenMode != SecondScreenMode.DECK_CONTROLS || SessionState.deckPad) -> {
androidx.compose.runtime.key(profileLayout) {
androidx.compose.ui.viewinterop.AndroidView(
factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(),
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) },
modifier = Modifier.fillMaxSize(),
)
secondScreenMode.controls && (secondScreenMode != SecondScreenMode.DECK_CONTROLS || SessionState.deckPad) ->
androidx.compose.foundation.layout.Column(Modifier.fillMaxSize()) {
when (secondScreenMode) {
SecondScreenMode.KEYBOARD_TRACKPAD ->
com.droiddeck.launcher.ui.BottomScreenBar(bar(getString(SecondScreenMode.KEYBOARD_TRACKPAD.label), listOf(keyboardExtra)))
SecondScreenMode.DECK_CONTROLS -> com.droiddeck.launcher.ui.BottomScreenBar(bar(getString(SecondScreenMode.DECK_CONTROLS.label),
tabs = com.droiddeck.launcher.ui.deckPanelTabs(this@SessionActivity, SessionPrefs.deckPanel(this@SessionActivity), ::selectDeckPanel)))
else -> Unit
}
androidx.compose.runtime.key(profileLayout) {
androidx.compose.ui.viewinterop.AndroidView(
factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(),
surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) },
modifier = Modifier.fillMaxWidth().weight(1f),
)
}
}
secondScreenMode == SecondScreenMode.TERMINAL -> androidx.compose.foundation.layout.Column(Modifier.fillMaxSize()) {
var terminal by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf<com.droiddeck.launcher.ui.SessionTerminalPanel?>(null) }
com.droiddeck.launcher.ui.BottomScreenBar(bar(getString(SecondScreenMode.TERMINAL.label), listOf(
com.droiddeck.launcher.ui.BarExtra(getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard) { terminal?.showKeyboard() },
)))
androidx.compose.ui.viewinterop.AndroidView(
factory = { context -> com.droiddeck.launcher.ui.SessionTerminalPanel(context).also { terminal = it } },
modifier = Modifier.fillMaxWidth().weight(1f),
)
}
pages.isEmpty() -> com.droiddeck.launcher.ui.BottomScreenBar(bar(null))
else -> BottomDashboard(
pages, com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import java.io.File
import java.util.UUID
internal object InputButtonImages {
const val DIR = "screenkeys"
private const val MAX_SIZE_DP = 140
fun file(context: Context, name: String): File? =
name.takeIf { it.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && it != "." && it != ".." }?.let { File(File(context.filesDir, DIR), it) }
fun import(context: Context, uri: Uri): String? {
val dir = File(context.filesDir, DIR).apply { mkdirs() }
val name = "key_" + UUID.randomUUID() + ".png"
val longest = (MAX_SIZE_DP * context.resources.displayMetrics.density).toInt()
return runCatching {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, bounds) }
val source = maxOf(bounds.outWidth, bounds.outHeight)
if (source <= 0) return@runCatching null
var sample = 1
while (source / (sample * 2) >= longest) sample *= 2
val bitmap = context.contentResolver.openInputStream(uri)?.use {
BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inSampleSize = sample })
} ?: return@runCatching null
val scale = longest.toFloat() / maxOf(bitmap.width, bitmap.height)
val scaled = if (scale < 1f) Bitmap.createScaledBitmap(bitmap, (bitmap.width * scale).toInt().coerceAtLeast(1),
(bitmap.height * scale).toInt().coerceAtLeast(1), true) else bitmap
try {
val saved = File(dir, name).outputStream().use { scaled.compress(Bitmap.CompressFormat.PNG, 100, it) }
if (saved) name else null
} finally {
if (scaled !== bitmap) bitmap.recycle()
scaled.recycle()
}
}.getOrNull().also { if (it == null) File(dir, name).delete() }
}
}
@@ -0,0 +1,123 @@
package com.droiddeck.launcher.input
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.roundToInt
internal object InputLayoutFile {
private val NAMES: Map<Int, String> = mapOf(
103 to "KEY_UP", 106 to "KEY_RIGHT", 108 to "KEY_DOWN", 105 to "KEY_LEFT",
28 to "KEY_ENTER", 1 to "KEY_ESC", 14 to "KEY_BKSP", 111 to "KEY_DEL", 15 to "KEY_TAB",
57 to "KEY_SPACE", 29 to "KEY_CTRL_L", 97 to "KEY_CTRL_R", 110 to "KEY_INSERT",
42 to "KEY_SHIFT_L", 54 to "KEY_SHIFT_R", 56 to "KEY_ALT_L", 100 to "KEY_ALT_R",
102 to "KEY_HOME", 107 to "KEY_END", 99 to "KEY_PRTSCN", 104 to "KEY_PG_UP", 109 to "KEY_PG_DOWN",
58 to "KEY_CAPS_LOCK", 69 to "KEY_NUM_LOCK", 41 to "KEY_GRAVE", 12 to "KEY_MINUS",
11 to "KEY_0", 2 to "KEY_1", 3 to "KEY_2", 4 to "KEY_3", 5 to "KEY_4", 6 to "KEY_5",
7 to "KEY_6", 8 to "KEY_7", 9 to "KEY_8", 10 to "KEY_9",
30 to "KEY_A", 48 to "KEY_B", 46 to "KEY_C", 32 to "KEY_D", 18 to "KEY_E", 33 to "KEY_F",
34 to "KEY_G", 35 to "KEY_H", 23 to "KEY_I", 36 to "KEY_J", 37 to "KEY_K", 38 to "KEY_L",
50 to "KEY_M", 49 to "KEY_N", 24 to "KEY_O", 25 to "KEY_P", 16 to "KEY_Q", 19 to "KEY_R",
31 to "KEY_S", 20 to "KEY_T", 22 to "KEY_U", 47 to "KEY_V", 17 to "KEY_W", 45 to "KEY_X",
21 to "KEY_Y", 44 to "KEY_Z",
26 to "KEY_BRACKET_LEFT", 27 to "KEY_BRACKET_RIGHT", 43 to "KEY_BACKSLASH", 53 to "KEY_SLASH",
39 to "KEY_SEMICOLON", 51 to "KEY_COMMA", 52 to "KEY_PERIOD", 40 to "KEY_APOSTROPHE",
59 to "KEY_F1", 60 to "KEY_F2", 61 to "KEY_F3", 62 to "KEY_F4", 63 to "KEY_F5", 64 to "KEY_F6",
65 to "KEY_F7", 66 to "KEY_F8", 67 to "KEY_F9", 68 to "KEY_F10", 87 to "KEY_F11", 88 to "KEY_F12",
79 to "KEY_KP_1", 80 to "KEY_KP_2", 81 to "KEY_KP_3", 75 to "KEY_KP_4", 76 to "KEY_KP_5",
77 to "KEY_KP_6", 71 to "KEY_KP_7", 72 to "KEY_KP_8", 73 to "KEY_KP_9", 82 to "KEY_KP_0",
)
private val CODES: Map<String, Int> = NAMES.entries.associate { (code, name) -> name to code }
fun fileName(layout: SavedInputLayout) = layout.name.replace(Regex("[^A-Za-z0-9 _.-]"), "_").trim().ifEmpty { "droiddeck-layout" } + ".icp"
fun export(layout: SavedInputLayout, bindings: SavedInputBindings?, width: Int, height: Int): String? {
val snap = width.coerceAtLeast(1) / 100f
val elements = JSONArray()
for (e in layout.elements) {
val action = bindings?.action(e) ?: InputAction.Disabled
val directional = e.kind == InputElementKind.DPAD || e.kind == InputElementKind.STICK
val codes = when {
directional && action is InputAction.Directions -> listOf(action.up, action.right, action.down, action.left)
!directional && action is InputAction.Keys -> action.codes
else -> continue
}
val binds = JSONArray()
for (code in codes) {
val name = NAMES[code]
if (name != null) binds.put(name) else if (directional) binds.put("")
}
if ((0 until binds.length()).all { binds.getString(it).isEmpty() }) continue
val shape = when {
directional -> "ROUND_RECT"
e.buttonShape == InputButtonShape.CIRCLE -> "CIRCLE"
e.buttonShape == InputButtonShape.RECTANGLE -> "RECT"
else -> "ROUND_RECT"
}
val sizePx = e.height * height
val scale = when {
directional -> sizePx * 2.3f / (14f * snap)
shape == "CIRCLE" -> sizePx / (6f * snap)
else -> sizePx / (4f * snap)
}
elements.put(JSONObject()
.put("type", when (e.kind) { InputElementKind.DPAD -> "D_PAD"; InputElementKind.STICK -> "STICK"; else -> "BUTTON" })
.put("shape", shape).put("customColor", 0).put("bindings", binds).put("scale", scale.toDouble())
.put("x", (e.x + e.width / 2).toDouble()).put("y", (e.y + e.height / 2).toDouble())
.put("toggleSwitch", e.toggle).put("swipeable", false)
.put("text", if (e.icon != 0 || e.image.isNotEmpty()) "" else e.name).put("iconId", 0)
.apply { if (e.opacity < 1f) put("opacity", e.opacity.toDouble()) })
}
if (elements.length() == 0) return null
return JSONObject().put("id", 0).put("name", layout.name).put("cursorSpeed", 1.5).put("elements", elements).toString()
}
fun parse(raw: String, width: Int, density: Float): List<LegacyScreenKey>? {
val root = runCatching { JSONObject(raw) }.getOrNull() ?: return null
val elements = root.optJSONArray("elements") ?: return null
val snap = width.coerceAtLeast(1) / 100f
val keys = mutableListOf<LegacyScreenKey>()
for (i in 0 until elements.length()) {
val element = elements.optJSONObject(i) ?: continue
val type = element.optString("type", "BUTTON")
if (type != "BUTTON" && type != "D_PAD" && type != "STICK") continue
val binds = element.optJSONArray("bindings") ?: continue
val raw = (0 until binds.length()).map { CODES[binds.optString(it)] ?: 0 }
val directional = type != "BUTTON"
val codes = when {
!directional -> raw.filter { it != 0 }.distinct().take(8)
type == "STICK" && raw.size <= 4 -> listOf(raw.getOrElse(0) { 0 }, 0, raw.getOrElse(1) { 0 }, 0, raw.getOrElse(2) { 0 }, 0, raw.getOrElse(3) { 0 }, 0)
else -> raw.take(if (type == "STICK") 8 else 4)
}
if (codes.none { it != 0 }) continue
val shape = when {
type == "D_PAD" -> 5
type == "STICK" -> 6
else -> when (element.optString("shape")) { "CIRCLE" -> 2; "RECT" -> 3; "SQUARE" -> 1; else -> 0 }
}
val scale = element.optDouble("scale", 1.0).toFloat().takeIf { it.isFinite() && it > 0f } ?: 1f
val sizePx = when {
directional -> 14f * snap * scale / 2.3f
shape == 2 -> 6f * snap * scale
else -> 4f * snap * scale
}
fun coordinate(name: String) = element.optDouble(name, .5).toFloat().takeIf { it.isFinite() }?.coerceIn(0f, 1f) ?: .5f
keys += LegacyScreenKey(codes, coordinate("x"), coordinate("y"), (sizePx / density).roundToInt().coerceIn(24, 140).toFloat(),
text = element.optString("text").trim().take(24),
opacity = element.optDouble("opacity", 1.0).toFloat().takeIf { it.isFinite() }?.coerceIn(.2f, 1f) ?: 1f,
shape = shape, toggle = element.optBoolean("toggleSwitch"))
if (keys.size == 64) break
}
return keys
}
fun import(context: Context, raw: String, fallbackName: String, screen: InputLayoutScreen, style: InputSurfaceStyle,
width: Int, height: Int, density: Float, id: String = newInputId()): Pair<SavedInputLayout, SavedInputBindings>? {
val keys = parse(raw, width, density)?.takeIf { it.isNotEmpty() } ?: return null
val converted = runCatching { LegacyScreenKeyMigration.convert(context, keys, width, height, density) }.getOrNull() ?: return null
val name = runCatching { JSONObject(raw).optString("name") }.getOrNull().orEmpty().trim().take(80).ifEmpty { fallbackName.trim().take(80) }
val layout = SavedInputLayout(id, name, converted.map { it.first }, style = style, screen = screen,
aspect = (width.coerceAtLeast(1).toFloat() / height.coerceAtLeast(1)).coerceIn(.05f, 20f))
return layout to SavedInputBindings(newInputId(), name, false, id, elements = converted.associate { it.first.id to it.second })
}
}
@@ -9,7 +9,7 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 11
private const val VERSION = 12
private const val KEY = "library"
private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay"
@@ -29,25 +29,41 @@ object InputLibraries {
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 < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) {
val upgraded = runCatching { LegacyScreenKeyMigration.migrate(context, library, legacy) }.getOrElse {
val migrated = runCatching { LegacyScreenKeyMigration.migrate(context, library, legacy) }.getOrElse {
android.util.Log.e("InputLibraries", "Could not migrate screen keys; keeping the original settings", it)
return library
}
val merged = mergeScreenKeys(migrated, legacy)
val upgraded = merged ?: migrated
val encoded = encode(upgraded)
require(encoded.length <= 2_000_000)
if (!p.edit().putString(KEY, encoded).putString(LegacyScreenKeyMigration.BACKUP, legacy).commit()) return library
val edit = p.edit().putString(KEY, encoded).putString(LegacyScreenKeyMigration.BACKUP, legacy)
if (merged != null) edit.putBoolean(LegacyScreenKeyMigration.MERGED, true)
if (!edit.commit()) return library
LegacyScreenKeyMigration.clean(context)
return upgraded
}
}
val backup = p.getString(LegacyScreenKeyMigration.BACKUP, null)
if (backup != null && !p.contains(LegacyScreenKeyMigration.MERGED)) {
val merged = mergeScreenKeys(library, backup)
if (merged != null) {
val encoded = encode(merged)
if (encoded.length <= 2_000_000 && p.edit().putString(KEY, encoded).putBoolean(LegacyScreenKeyMigration.MERGED, true).commit()) library = merged
}
}
if (raw == null || version < VERSION) write(context, library)
if (p.contains(LegacyScreenKeyMigration.BACKUP)) LegacyScreenKeyMigration.clean(context)
return library
}
private fun mergeScreenKeys(library: InputLibrary, legacy: String): InputLibrary? = runCatching { LegacyScreenKeyMigration.merge(library, legacy) }
.onFailure { android.util.Log.e("InputLibraries", "Could not show the imported screen keys with the gamepad", it) }.getOrNull()
fun hasPendingScreenKeyMigration(context: Context) = !prefs(context).contains(LegacyScreenKeyMigration.BACKUP) && LegacyScreenKeyMigration.snapshot(context) != null
fun hasLibraryRecovery(context: Context) = prefs(context).all.keys.any { it.startsWith(RECOVERY) }
@@ -115,8 +131,24 @@ object InputLibraries {
}
}.onSuccess { ControllerPrefs.setAdaptiveSticks(context, on) }.isSuccess
fun setQuickButton(context: Context, layoutId: String, button: InputCommand, shown: Boolean): Boolean = runCatching {
update(context) { library -> library.layouts.firstOrNull { it.id == layoutId && it.editable }?.let { library.withLayout(it.withQuickButton(button, shown)) } ?: library }
}.isSuccess
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): List<InputSurfaceElement>? {
val origin = layout.origin ?: layout.id
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements }
if (origin == OVERLAY || origin.startsWith("migrated.layout.")) {
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() }
}
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.elements
}
@Suppress("DEPRECATION")
private fun primaryDisplay(context: Context): Pair<Context, DisplayMetrics> {
internal fun primaryDisplay(context: Context): Pair<Context, DisplayMetrics> {
val display = context.getSystemService(DisplayManager::class.java)?.getDisplay(Display.DEFAULT_DISPLAY)
val surfaceContext = display?.let(context::createDisplayContext) ?: context
return surfaceContext to DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) }
@@ -143,7 +175,8 @@ object InputLibraries {
val elements = LegacyGamepadLayout(surfaceContext, metrics.widthPixels.coerceAtLeast(1), metrics.heightPixels.coerceAtLeast(1)).elements()
val style = InputSurfaceStyle(settings.tint, settings.opacity)
val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old ->
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style)
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style,
aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f))
}
var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
val migrated = mutableMapOf<Pair<String, String>, String>()
@@ -172,7 +205,7 @@ object InputLibraries {
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))
LegacyGamepadLayout(surfaceContext, size[0], size[1]).elements(), style = style, aspect = (size[0].toFloat() / size[1]).coerceIn(.05f, 20f)))
}
return result.validate()
}
@@ -206,11 +239,30 @@ 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() })
return addStockLayouts(result)
}
private fun addStockLayouts(library: InputLibrary): InputLibrary {
val stock = InputStockLayouts.layouts()
var result = library
for (layout in stock) if (result.layouts.none { it.id == layout.id }) result = result.withLayout(layout)
for (preset in InputStockLayouts.presets(stock)) if (result.bindings.none { it.id == preset.id }) result = result.withPreset(preset)
return result.validate()
}
private fun barStockLayouts(library: InputLibrary): InputLibrary {
var result = library
for (stock in InputStockLayouts.layouts().filter { it.id == DECK || it.id == TRACKPAD }) {
val saved = result.layouts.firstOrNull { it.id == stock.id } ?: continue
val (commands, rest) = saved.elements.partition { it.id.startsWith("command:") }
val untouched = commands.isNotEmpty() && commands.all { it.control == InputControl.A && it.kind == InputElementKind.BUTTON } &&
rest.size == stock.elements.size && rest.all { e -> stock.elements.any { s -> s.id == e.id && s.copy(y = e.y, height = e.height) == e &&
kotlin.math.abs(s.y + s.height - e.y - e.height) < 1e-3f } }
if (untouched) result = result.withLayout(saved.copy(elements = stock.elements))
}
return addStockLayouts(result)
}
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)
@@ -242,7 +294,8 @@ object InputLibraries {
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name))
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
}
val bindings = JSONArray()
for (b in library.bindings) {
@@ -283,8 +336,10 @@ object InputLibraries {
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true))
}
SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")),
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100)),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)))
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), layout.optionalString("origin"),
layout.optDouble("scale", 1.0).toFloat())
}
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
@@ -9,15 +9,25 @@ enum class InputLayoutScreen { MAIN, SECONDARY, BOTH;
if (role == InputRole.PRIMARY) this == MAIN else this == SECONDARY)
}
data class InputSurfaceStyle(val tint: Int? = ControllerPrefs.STEAM_BLUE, val opacity: Int = 100)
data class InputSurfaceStyle(val tint: Int? = ControllerPrefs.STEAM_BLUE, val opacity: Int = 100, val hidden: Set<InputCommand> = emptySet()) {
fun hides(element: InputSurfaceElement) = element.quickButton?.let { it in hidden } == true
fun shown(elements: List<InputSurfaceElement>) = if (hidden.isEmpty()) elements else elements.filterNot(::hides)
}
data class SavedInputLayout(
val id: String, val name: String, val elements: List<InputSurfaceElement> = emptyList(),
val template: InputLayoutTemplate = InputLayoutTemplate.CUSTOM,
val style: InputSurfaceStyle = InputSurfaceStyle(),
val screen: InputLayoutScreen = InputLayoutScreen.BOTH,
val aspect: Float = 0f,
val origin: String? = null,
val scale: Float = 1f,
) {
val editable get() = template == InputLayoutTemplate.CUSTOM
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
fun withQuickButton(button: InputCommand, shown: Boolean) =
copy(style = style.copy(hidden = if (shown) style.hidden - button else style.hidden + button))
fun derived(id: String, name: String) = copy(id = id, name = name, origin = origin ?: this.id)
val adaptiveSticks get() = elements.filter { it.kind == InputElementKind.STICK }.takeIf { editable && it.isNotEmpty() }?.all { it.floating && it.hideWhenIdle }
fun supports(role: InputRole) = screen.supports(role) && when (template) {
InputLayoutTemplate.OVERLAY -> role == InputRole.PRIMARY
@@ -132,7 +142,7 @@ data class InputLibrary(
if (shared) return withProfile(target.copy(parts = target.parts + (role to source)))
val sourceLayout = layout(sourceId, role)
val name = (target.name + " / " + role.name.lowercase()).take(80)
val copiedLayout = sourceLayout?.takeIf { it.editable }?.copy(id = newInputId(), name = name)
val copiedLayout = sourceLayout?.takeIf { it.editable }?.derived(newInputId(), name)
val copiedBindings = preset(source.bindings).copy(id = newInputId(), name = name,
layoutId = copiedLayout?.id ?: preset(source.bindings).layoutId)
return (if (copiedLayout == null) this else withLayout(copiedLayout)).withPreset(copiedBindings)
@@ -143,7 +153,7 @@ data class InputLibrary(
val source = layouts.first { it.id == layoutId }
require(source.supports(role))
val target = profile(profileId)
val layout = if (shared || !source.editable) source else source.copy(id = newInputId(), name = (target.name + " / " + source.name).take(80))
val layout = if (shared || !source.editable) source else source.derived(newInputId(), (target.name + " / " + source.name).take(80))
val previous = preset(target.binding(role))
val actions = if (previous.compatible(source)) previous else bindings.firstOrNull { it.compatible(source) } ?: SavedInputBindings(newInputId(), target.name, false,
controls = if (source.editable) emptyMap() else InputProfile.defaults(target.base).bindings[role].orEmpty(),
@@ -181,7 +191,7 @@ data class InputLibrary(
fun copyLayout(id: String, name: String, newId: String = newInputId()): InputLibrary {
val source = layouts.first { it.id == id }
require(source.editable)
return withLayout(source.copy(id = newId, name = inputName(name)))
return withLayout(source.derived(newId, inputName(name)))
}
fun removeProfile(id: String): InputLibrary {
@@ -227,7 +237,9 @@ data class InputLibrary(
require(selected == InputProfiles.AUTO || profiles.any { it.id == selected })
require(profiles.any { it.id == steam } && profiles.any { it.id == desktop })
for (layout in layouts) {
require(layout.style.opacity in 1..100)
require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS })
require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f)
require(layout.scale.isFinite() && layout.scale in .5f..2f)
inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id })
for (e in layout.elements) {
inputName(e.name)
@@ -234,7 +234,7 @@ class InputRouter(private val output: InputOutput) {
when (a) {
is InputAction.Keys -> if (down) a.codes.forEach { key(it, true) } else a.codes.asReversed().forEach { key(it, false) }
is InputAction.MouseButton -> button(a.code, down)
is InputAction.Command -> if (down) output.command(a.command, role)
is InputAction.Command -> if (!down) output.command(a.command, role)
else -> Unit
}
}
@@ -1,32 +1,61 @@
package com.droiddeck.launcher.input
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
enum class DeckPanel(val id: String, val layout: String, val bindings: String, @StringRes val label: Int) {
GAMEPAD("gamepad", "builtin.deck.gamepad", "preset.deck.gamepad", R.string.deck_tab_gamepad),
GRIPS("grips", "builtin.deck.grips", "preset.deck.grips", R.string.deck_tab_grips),
LEFT("left", "builtin.deck.left", "preset.deck.left", R.string.deck_tab_left),
RIGHT("right", "builtin.deck.right", "preset.deck.right", R.string.deck_tab_right),
BOTH("both", InputLibraries.DECK, InputStockLayouts.DECK, R.string.deck_tab_both);
companion object {
fun from(id: String?) = entries.firstOrNull { it.id == id } ?: BOTH
}
}
internal object InputStockLayouts {
private val NEUTRAL = InputSurfaceStyle(tint = null)
const val DECK = "preset.deck"
const val TRACKPAD = "preset.trackpad"
private fun commands(indices: List<Int>): List<InputSurfaceElement> {
val names = listOf("DroidDeck menu", "Keyboard", "Steam", "Quick access")
val icons = listOf(InputButtonIcons.MENU, InputButtonIcons.KEYBOARD, InputButtonIcons.STEAM, InputButtonIcons.QUICK_ACCESS)
val step = .98f / indices.size
return indices.mapIndexed { position, i ->
InputSurfaceElement(InputControl.A, .02f + position * step, .01f, step - .02f, .11f,
"command:$i", name = names[i], icon = icons[i])
}
}
private fun commandActions(): Map<String, InputAction> = listOf(InputCommand.MENU, InputCommand.KEYBOARD, InputCommand.STEAM, InputCommand.QUICK_ACCESS)
.mapIndexed { i, command -> "command:$i" to InputAction.Command(command) }.toMap()
private fun grips() = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4).mapIndexed { i, c ->
InputSurfaceElement(c, .02f + i * .245f, .78f, .225f, .20f)
}
private fun pads() = listOf(InputSurfaceElement(InputControl.LEFT_PAD, .02f, .14f, .47f, .62f),
InputSurfaceElement(InputControl.RIGHT_PAD, .51f, .14f, .47f, .62f))
private fun pads() = listOf(InputSurfaceElement(InputControl.LEFT_PAD, .02f, .02f, .47f, .74f),
InputSurfaceElement(InputControl.RIGHT_PAD, .51f, .02f, .47f, .74f))
private fun gripGrid() = listOf(InputControl.L4 to (.02f to .02f), InputControl.L5 to (.02f to .51f),
InputControl.R4 to (.51f to .02f), InputControl.R5 to (.51f to .51f)).map { (c, at) ->
InputSurfaceElement(c, at.first, at.second, .47f, .47f)
}
private fun pad(right: Boolean) = listOf(
InputSurfaceElement(if (right) InputControl.RIGHT_PAD else InputControl.LEFT_PAD, .02f, .02f, .96f, .74f),
InputSurfaceElement(if (right) InputControl.RIGHT_CLICK else InputControl.LEFT_CLICK, .02f, .78f, .96f, .20f),
)
private fun gamepad(): List<InputSurfaceElement> {
fun round(c: InputControl, x: Float, y: Float, size: Float) = InputSurfaceElement(c, x, y, size, size, buttonShape = InputButtonShape.CIRCLE)
fun pill(c: InputControl, x: Float) = InputSurfaceElement(c, x, .02f, .2f, .12f, buttonShape = InputButtonShape.PILL)
return listOf(pill(InputControl.LT, .02f), pill(InputControl.LB, .24f), pill(InputControl.RB, .56f), pill(InputControl.RT, .78f),
InputSurfaceElement(InputControl.LS, .02f, .17f, .4f, .4f),
InputSurfaceElement(InputControl.RIGHT_PAD, .58f, .59f, .4f, .39f),
round(InputControl.UP, .14f, .6f, .12f), round(InputControl.LEFT, .03f, .73f, .12f),
round(InputControl.RIGHT, .25f, .73f, .12f), round(InputControl.DOWN, .14f, .86f, .12f),
round(InputControl.Y, .72f, .17f, .12f), round(InputControl.X, .61f, .3f, .12f),
round(InputControl.B, .83f, .3f, .12f), round(InputControl.A, .72f, .43f, .12f),
InputSurfaceElement(InputControl.SELECT, .42f, .3f, .07f, .1f, buttonShape = InputButtonShape.PILL),
InputSurfaceElement(InputControl.START, .51f, .3f, .07f, .1f, buttonShape = InputButtonShape.PILL))
}
fun layouts() = listOf(
SavedInputLayout(InputLibraries.DECK, "Deck grips + trackpads", commands(listOf(2, 3, 0)) + pads() + grips(), style = NEUTRAL, screen = InputLayoutScreen.SECONDARY),
SavedInputLayout(InputLibraries.TRACKPAD, "Trackpad + keyboard", commands(listOf(0, 1)) +
InputSurfaceElement(InputControl.RIGHT_PAD, .02f, .14f, .96f, .84f, mouseGestures = true), style = NEUTRAL, screen = InputLayoutScreen.SECONDARY),
SavedInputLayout(InputLibraries.DECK, "Deck grips + trackpads", pads() + grips(), style = NEUTRAL, screen = InputLayoutScreen.SECONDARY),
SavedInputLayout(InputLibraries.TRACKPAD, "Trackpad + keyboard", listOf(
InputSurfaceElement(InputControl.RIGHT_PAD, .02f, .02f, .96f, .96f, mouseGestures = true)), style = NEUTRAL, screen = InputLayoutScreen.SECONDARY),
SavedInputLayout(DeckPanel.GAMEPAD.layout, "Deck gamepad", gamepad(), style = NEUTRAL, screen = InputLayoutScreen.SECONDARY),
SavedInputLayout(DeckPanel.GRIPS.layout, "Deck grips", gripGrid(), style = NEUTRAL, screen = InputLayoutScreen.SECONDARY),
SavedInputLayout(DeckPanel.LEFT.layout, "Deck left trackpad", pad(right = false), style = NEUTRAL, screen = InputLayoutScreen.SECONDARY),
SavedInputLayout(DeckPanel.RIGHT.layout, "Deck right trackpad", pad(right = true), style = NEUTRAL, screen = InputLayoutScreen.SECONDARY),
)
fun actions(layout: SavedInputLayout): Map<String, InputAction> = (commandActions() + if (layout.id == InputLibraries.TRACKPAD) mapOf(
fun actions(layout: SavedInputLayout): Map<String, InputAction> = (if (layout.id == InputLibraries.TRACKPAD) mapOf(
"legacy:right-pad" to InputAction.Pointer(), "legacy:a" to InputAction.MouseButton(272), "legacy:b" to InputAction.MouseButton(273),
) else emptyMap()).filterKeys { id -> layout.elements.any { it.id == id } }
@@ -35,7 +64,8 @@ internal object InputStockLayouts {
fun presets(layouts: List<SavedInputLayout>) = layouts.map { layout ->
val desktop = layout.id == InputLibraries.TRACKPAD
SavedInputBindings(if (desktop) TRACKPAD else DECK, layout.name, false, layout.id,
val id = if (desktop) TRACKPAD else DeckPanel.entries.first { it.layout == layout.id }.bindings
SavedInputBindings(id, layout.name, false, layout.id,
controls = InputProfile.defaults(if (desktop) InputProfile.DESKTOP else InputProfile.GAME).bindings[InputRole.SECONDARY].orEmpty(),
elements = actions(layout), clicks = clicks(layout))
}
@@ -38,7 +38,33 @@ data class InputSurfaceElement(
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
fun bounded() = copy(x = x.coerceIn(0f, 0.97f), y = y.coerceIn(0f, 0.97f),
width = width.coerceIn(0.03f, 1f - x.coerceIn(0f, 0.97f)), height = height.coerceIn(0.03f, 1f - y.coerceIn(0f, 0.97f)))
width = width.coerceIn(0.03f, (1f - x.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)), height = height.coerceIn(0.03f, (1f - y.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)))
}
internal val QUICK_BUTTONS = listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.KEYBOARD)
val InputSurfaceElement.quickButton: InputCommand? get() = when {
id == "legacy:${InputControl.GUIDE.id}" -> InputCommand.STEAM
id == "legacy:${InputControl.QAM.id}" -> InputCommand.QUICK_ACCESS
id == "builtin:keyboard" -> InputCommand.KEYBOARD
else -> null
}
internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> = map { e ->
fun anchor(centre: Float) = when { centre < 1f / 3f -> 0f; centre > 2f / 3f -> 1f; else -> .5f }
val w = (e.width * factor).coerceIn(.03f, 1f)
val h = (e.height * factor).coerceIn(.03f, 1f)
val cx = e.x + e.width / 2
val cy = e.y + e.height / 2
val ax = anchor(cx)
val ay = anchor(cy)
e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h),
width = w, height = h).bounded()
}
internal fun List<InputSurfaceElement>.withPositionsOf(defaults: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = defaults.associateBy { it.id }
return map { e -> byId[e.id]?.let { d -> e.copy(x = d.x, y = d.y, width = d.width, height = d.height).bounded() } ?: e }
}
object InputSurfaceLayout {
@@ -71,6 +71,12 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
InputTiming.end(timing)
}
fun cancel() {
if (closed) return
route?.takeIf { it.action is InputAction.Command }?.release()
update(0f)
}
fun click(down: Boolean) {
if (closed) return
val timing = InputTiming.begin()
@@ -4,10 +4,10 @@ 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) {
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 val safe = Rect()
private var fit = 1f
private class Control(val id: String, val group: String, val stick: Int, val radiusDp: Float, val offsetXDp: Float, val offsetYDp: Float) {
var radius = 0f
@@ -41,7 +41,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
private fun dp(value: Float) = value * resources.displayMetrics.density
private fun scaled(value: Float) = dp(value) * settings.size / 100f * fit
private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit
private fun fitScale(): Float {
val metrics = resources.displayMetrics
@@ -195,6 +195,76 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
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): 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(InputControl.LS, GamepadGeometry.Slot.LEFT_MAIN, InputButtonShape.CIRCLE)
cross(DPAD_ORDER, GamepadGeometry.Slot.LEFT_SECOND)
box(InputControl.RS, 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) }
return withGeometry(stored, placed) + placed.filter { p -> GRIPS.any { it.first == p.control } && 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)
@@ -268,5 +338,13 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
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)
}
}
@@ -8,6 +8,8 @@ import org.json.JSONObject
internal object LegacyScreenKeyMigration {
const val BACKUP = "legacy-screen-keys-backup"
const val MERGED = "legacy-screen-keys-merged"
private const val SHOWN = "migrated.screenkeys.0"
fun snapshot(context: Context): String? {
val values = ControllerPrefs.prefs(context).all.filterKeys { it == "screenKeys" || it == "screenKeysShown" || it.startsWith("screenLayout.") }
@@ -38,7 +40,8 @@ internal object LegacyScreenKeyMigration {
if (result.profiles.any { it.id == id }) continue
val converted = convert(context, set.second, metrics.widthPixels, metrics.heightPixels, metrics.density)
if (converted.isEmpty()) continue
val layout = SavedInputLayout("$id.layout", set.first, converted.map { it.first }, style = style, screen = InputLayoutScreen.MAIN)
val layout = SavedInputLayout("$id.layout", set.first, converted.map { it.first }, style = style, screen = InputLayoutScreen.MAIN,
aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f))
val bindings = SavedInputBindings("$id.bindings", set.first, false, layout.id, elements = converted.associate { it.first.id to it.second })
val base = library.profile(library.steam)
val profile = SavedInputProfile(id, set.first, base.base, base.parts + (InputRole.PRIMARY to InputPart(bindings.id, layout.id)))
@@ -47,30 +50,58 @@ internal object LegacyScreenKeyMigration {
return result.validate()
}
fun merge(library: InputLibrary, raw: String): InputLibrary {
val old = JSONObject(raw)
if (!old.optBoolean("screenKeysShown", true) || old.optString("screenKeys").isBlank()) return library
val keys = library.layouts.firstOrNull { it.id == "$SHOWN.layout" } ?: return library
val actions = library.bindings.firstOrNull { it.id == "$SHOWN.bindings" }?.elements.orEmpty()
var result = library
for (part in listOf(false, true).map { library.activePart(it, InputRole.PRIMARY) }.distinct()) {
val layout = result.layouts.firstOrNull { it.id == part.layout } ?: continue
val preset = result.preset(part.bindings)
if (!layout.editable || preset.layoutId != layout.id || layout.elements.any { e -> keys.elements.any { it.id == e.id } } ||
layout.elements.size + keys.elements.size > 64) continue
val added = keys.elements.mapNotNull { e -> actions[e.id]?.let { e.id to it } }.toMap()
result = result.withLayout(layout.copy(elements = layout.elements + keys.elements))
.withPreset(preset.copy(elements = added + preset.elements))
}
return result.validate()
}
internal fun convert(context: Context, raw: String, width: Int, height: Int, density: Float): List<Pair<InputSurfaceElement, InputAction>> =
raw.split(';').filter { it.isNotBlank() }.mapIndexed { index, entry ->
val parts = entry.split(':')
require(parts.size >= 2) { "Invalid legacy screen key" }
val codes = parts[0].split('+').map { it.toInt() }
convert(context, parse(raw), width, height, density)
internal fun parse(raw: String): List<LegacyScreenKey> = raw.split(';').filter { it.isNotBlank() }.map { entry ->
val parts = entry.split(':')
require(parts.size >= 2) { "Invalid legacy screen key" }
val codes = parts[0].split('+').map { it.toInt() }
val position = parts[1].split(',').map { it.toFloat() }
require(position.size == 3)
fun text(at: Int) = parts.getOrNull(at).orEmpty().replace("%2C", ",").replace("%3A", ":").replace("%3B", ";").replace("%25", "%")
LegacyScreenKey(codes, position[0], position[1], position[2], text(2), text(3), text(4),
parts.getOrNull(5)?.toFloatOrNull() ?: 1f, parts.getOrNull(6)?.toIntOrNull() ?: 0, parts.getOrNull(7) == "1", parts.getOrNull(8) != "0")
}
internal fun convert(context: Context, keys: List<LegacyScreenKey>, width: Int, height: Int, density: Float): List<Pair<InputSurfaceElement, InputAction>> =
keys.mapIndexed { index, key ->
val codes = key.codes
require(codes.all { it in 0..255 })
val position = parts[1].split(',').map { it.toFloat() }
require(position.size == 3 && position.all { it.isFinite() })
fun text(at: Int) = parts.getOrNull(at).orEmpty().replace("%2C", ",").replace("%3A", ":").replace("%3B", ";").replace("%25", "%")
val shape = parts.getOrNull(6)?.toIntOrNull() ?: 0
require(listOf(key.x, key.y, key.size).all { it.isFinite() })
val shape = key.shape
val kind = when (shape) { 5 -> InputElementKind.DPAD; 6 -> InputElementKind.STICK; 4 -> InputElementKind.TRIGGER; else -> InputElementKind.BUTTON }
val label = text(3).ifEmpty { text(2) }.ifEmpty { codes.filter { it != 0 }.joinToString("+") { pcKeyLabel(context, it) } }.ifBlank { "Button" }.take(80)
val image = text(4)
val icon = codes.singleOrNull()?.takeIf { InputButtonIcons.has(it) && text(3).isEmpty() && text(2).isEmpty() } ?: 0
val heightPx = position[2].coerceIn(24f, 140f) * density
val label = key.text.ifEmpty { key.glyph }.ifEmpty { codes.filter { it != 0 }.joinToString("+") { pcKeyLabel(context, it) } }.ifBlank { "Button" }.take(80)
val image = key.image
val icon = codes.singleOrNull()?.takeIf { InputButtonIcons.has(it) && key.text.isEmpty() && key.glyph.isEmpty() } ?: 0
val heightPx = key.size.coerceIn(24f, 140f) * density
val ratio = when { shape == 2 -> 1f; shape == 4 -> 1.7f; shape == 5 || shape == 6 || image.isNotEmpty() || icon != 0 -> 1.15f; else -> (.55f * label.length + 1.05f).coerceIn(1.7f, 4.6f) }
val w = (heightPx * ratio / width.coerceAtLeast(1)).coerceIn(.03f, 1f)
val h = (heightPx / height.coerceAtLeast(1)).coerceIn(.03f, 1f)
val element = InputSurfaceElement(kind.control, (position[0] - w / 2).coerceIn(0f, 1f - w), (position[1] - h / 2).coerceIn(0f, 1f - h), w, h,
val element = InputSurfaceElement(kind.control, (key.x - w / 2).coerceIn(0f, 1f - w), (key.y - h / 2).coerceIn(0f, 1f - h), w, h,
id = "imported:$index", kind = kind, name = label, floating = false,
toggle = parts.getOrNull(7) == "1" && kind != InputElementKind.DPAD && kind != InputElementKind.STICK,
icon = icon, image = image, opacity = (parts.getOrNull(5)?.toFloatOrNull() ?: 1f).coerceIn(.2f, 1f),
toggle = key.toggle && kind != InputElementKind.DPAD && kind != InputElementKind.STICK,
icon = icon, image = image, opacity = key.opacity.coerceIn(.2f, 1f),
buttonShape = when (shape) { 0 -> InputButtonShape.PILL; 2 -> InputButtonShape.CIRCLE; 3 -> InputButtonShape.RECTANGLE; else -> InputButtonShape.ROUNDED },
showLabel = parts.getOrNull(8) != "0").bounded()
showLabel = key.labels).bounded()
val action = when (kind) {
InputElementKind.DPAD -> InputAction.Directions(codes.getOrElse(0) { 0 }, codes.getOrElse(1) { 0 }, codes.getOrElse(2) { 0 }, codes.getOrElse(3) { 0 })
InputElementKind.STICK -> InputAction.Directions(codes.getOrElse(0) { 0 }, codes.getOrElse(2) { 0 }, codes.getOrElse(4) { 0 }, codes.getOrElse(6) { 0 }, listOf(1, 3, 5, 7).map { codes.getOrElse(it) { 0 } })
@@ -80,3 +111,9 @@ internal object LegacyScreenKeyMigration {
element to action
}
}
internal data class LegacyScreenKey(
val codes: List<Int>, val x: Float, val y: Float, val size: Float,
val glyph: String = "", val text: String = "", val image: String = "",
val opacity: Float = 1f, val shape: Int = 0, val toggle: Boolean = false, val labels: Boolean = true,
)
@@ -4,6 +4,7 @@ import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.os.Build
import android.view.Gravity
@@ -14,9 +15,15 @@ import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.ui.InputSurfaceView
class OnScreenControls(context: Context, pad: PadBridge?) : FrameLayout(context) {
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY)
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
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 set
@@ -54,25 +61,41 @@ class OnScreenControls(context: Context, pad: PadBridge?) : FrameLayout(context)
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 = layout?.elements.orEmpty()
surface.updateCustomLayout(when {
isButtonsOnly -> elements.filter { it.control == InputControl.GUIDE || it.control == InputControl.QAM || it.id == "builtin:keyboard" }
isQuickHidden -> elements.filter { it.id == "builtin:keyboard" }
else -> elements
})
val elements = placed()
surface.updateCustomLayout(if (isQuickHidden) elements.filter { it.id == "builtin:keyboard" } else elements)
val style = layout?.style ?: InputSurfaceStyle()
surface.updateStyle(style)
quickToggle.tint = style.tint
quickToggle.alpha = style.opacity / 100f
quickToggle.visibility = if (isButtonsOnly || layout == null) GONE else VISIBLE
quickToggle.visibility = if (isButtonsOnly || layout == null || dock != null) GONE else VISIBLE
quickToggle.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
fun releaseAll() = surface.releaseInputs()
fun reload() { releaseAll(); render() }
fun reload() { releaseAll(); placements.clear(); render() }
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val w = MeasureSpec.getSize(widthMeasureSpec)
val h = MeasureSpec.getSize(heightMeasureSpec)
if (w != viewWidth || h != viewHeight) {
viewWidth = w
viewHeight = h
render()
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onDetachedFromWindow() { releaseAll(); super.onDetachedFromWindow() }
@@ -87,6 +110,11 @@ class OnScreenControls(context: Context, pad: PadBridge?) : FrameLayout(context)
params.bottomMargin = bottom
quickToggle.layoutParams = params
}
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
if (fresh != safe) {
safe.set(fresh)
render()
}
return super.onApplyWindowInsets(insets)
}
@@ -136,5 +164,6 @@ class OnScreenControls(context: Context, pad: PadBridge?) : FrameLayout(context)
const val QUICK_CENTER_DP = 34f
const val QUICK_HIT_DP = 26f
const val QUICK_RADIUS_DP = 18f
const val PLACEMENT_CACHE = 4
}
}
@@ -0,0 +1,84 @@
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
object OnScreenLayout {
data class Dock(val portrait: Boolean, val grips: Boolean)
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
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)
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored)
val (reference, generated) = reference(context, layout, width, height)
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
val others = fit(stored.filterNot { generated && isGamepad(it) }, reference.first, reference.second, width, height, safe)
val placed = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips)
else -> generator.regenerate(gamepad)
}
val byId = (placed + others).associateBy { it.id }
return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
}
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
val w = width.toFloat()
val h = height.toFloat()
val scale = min(w / referenceWidth, h / referenceHeight)
return elements.map { e ->
val ew = e.width * referenceWidth * scale
val eh = e.height * referenceHeight * scale
val left = anchor(e.x, e.width, referenceWidth, w, scale).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - ew))
val top = anchor(e.y, e.height, referenceHeight, h, scale).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - eh))
e.copy(x = left / w, y = top / h, width = ew / w, height = eh / h).bounded()
}
}
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
val centre = start + size / 2f
val scaled = size * reference * scale
return when {
centre < 1f / 3f -> start * reference * scale
centre > 2f / 3f -> actual - (1f - start - size) * reference * scale - scaled
else -> centre * actual - scaled / 2f
}
}
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] }
for ((w, h) in listOfNotNull(named, width to height, long to short, short to long).distinct()) {
if (matches(gamepad, LegacyGamepadLayout(display, w, h, scale = layout.scale).elements())) 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
}
}
}
@@ -1,9 +1,11 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.hardware.display.DisplayManager
import android.view.Display
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindings: String? = null) {
NONE("none", R.string.second_mode_none),
@@ -16,6 +18,8 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi
val controls: Boolean get() = this == CUSTOM_CONTROLS || bindings != null
fun panel(context: Context): String? = if (this == DECK_CONTROLS) SessionPrefs.deckPanel(context).bindings else bindings
companion object {
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, bottomDesktop: Boolean = false, desktopSession: Boolean = false): SecondScreenMode {
entries.firstOrNull {
@@ -1558,6 +1558,13 @@ object SessionPrefs {
prefs(context).edit().putString(if (right) "gamepadRight" else "gamepadLeft", surface).apply()
}
fun deckPanel(context: Context): com.droiddeck.launcher.input.DeckPanel =
com.droiddeck.launcher.input.DeckPanel.from(prefs(context).getString("deckPanel", null))
fun setDeckPanel(context: Context, panel: com.droiddeck.launcher.input.DeckPanel) {
prefs(context).edit().putString("deckPanel", panel.id).apply()
}
fun suspendPolicy(context: Context, mode: String): String =
prefs(context).getString("suspendPolicy.${prefMode(mode)}",
if (mode == SessionService.MODE_STEAM) SUSPEND_NATIVE else SUSPEND_MANUAL)
@@ -12,6 +12,7 @@ import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
@@ -47,6 +48,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
@@ -59,6 +61,8 @@ internal class BarExtra(
val onClick: () -> Unit,
)
internal class BarTabs(val labels: List<String>, val selected: Int, val onSelect: (Int) -> Unit)
internal class BottomBarModel(
val title: String?,
val onClose: (() -> Unit)?,
@@ -67,10 +71,22 @@ internal class BottomBarModel(
val onQam: (() -> Unit)?,
val extras: List<BarExtra> = emptyList(),
val menuActive: Boolean = false,
val tabs: BarTabs? = null,
)
@Composable
internal fun BottomScreenBar(model: BottomBarModel, modifier: Modifier = Modifier) {
val tabs = model.tabs
if (tabs == null) BarRow(model, modifier) else Column(modifier.fillMaxWidth().blockTouches()) {
BarRow(model)
Box(Modifier.fillMaxWidth().padding(start = BAR_PAD, end = BAR_PAD, bottom = 8.dp), contentAlignment = Alignment.Center) {
TabStrip(tabs.labels, tabs.selected, tabs.onSelect, Modifier.testTag("bottom-bar-tabs"), bumpers = false)
}
}
}
@Composable
private fun BarRow(model: BottomBarModel, modifier: Modifier = Modifier) {
val colors = MaterialTheme.colorScheme
BoxWithConstraints(modifier.fillMaxWidth().height(BAR_HEIGHT).blockTouches()) {
val buttons = listOfNotNull(model.onClose, model.onMenu, model.onQam).size + model.extras.size
@@ -195,11 +211,15 @@ internal fun sessionBarModel(
onSteam: () -> Unit,
onQam: () -> Unit,
extras: List<BarExtra> = emptyList(),
tabs: BarTabs? = null,
): BottomBarModel {
val steam = SessionState.mode == SessionService.MODE_STEAM
return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras)
return BottomBarModel(title, onClose, onMenu, onSteam.takeIf { steam }, onQam.takeIf { steam }, extras, tabs = tabs)
}
internal fun deckPanelTabs(context: Context, selected: DeckPanel, onSelect: (DeckPanel) -> Unit) =
BarTabs(DeckPanel.entries.map { context.getString(it.label) }, selected.ordinal) { onSelect(DeckPanel.entries[it]) }
internal fun bottomScreenBarView(context: Context, model: () -> BottomBarModel): ComposeView = ComposeView(context).apply {
setContent { DroidDeckTheme { BottomScreenBar(model()) } }
}
@@ -6,20 +6,38 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.foundation.Canvas
import androidx.compose.ui.graphics.nativeCanvas
import com.droiddeck.launcher.input.*
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import com.droiddeck.launcher.R
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun InputElementProperties(element: InputSurfaceElement, onChange: (InputSurfaceElement) -> Unit) {
val current by rememberUpdatedState(element)
val change by rememberUpdatedState(onChange)
OutlinedTextField(element.name, { onChange(element.copy(name = it.take(80))) }, label = { Text(stringResource(R.string.input_name)) },
singleLine = true, modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp))
if (element.kind == InputElementKind.BUTTON || element.kind == InputElementKind.TRIGGER) {
val host = rememberMenuHost()
val context = LocalContext.current
val scope = rememberCoroutineScope()
val pickImage = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) scope.launch {
withContext(Dispatchers.IO) { InputButtonImages.import(context.applicationContext, uri) }?.let { change(current.copy(icon = 0, image = it)) }
}
}
ToggleRow(host, "element-toggle", stringResource(R.string.input_toggle_button), stringResource(R.string.input_toggle_button_hint), element.toggle) { onChange(element.copy(toggle = it)) }
ChoiceRow(host, "element-shape", stringResource(R.string.input_button_shape), null,
InputButtonShape.entries.map { it to stringResource(when (it) { InputButtonShape.ROUNDED -> R.string.input_shape_rounded; InputButtonShape.PILL -> R.string.input_shape_pill; InputButtonShape.CIRCLE -> R.string.input_shape_circle; InputButtonShape.RECTANGLE -> R.string.input_shape_rectangle }) },
@@ -30,6 +48,7 @@ internal fun InputElementProperties(element: InputSurfaceElement, onChange: (Inp
ValueChip(if (element.image.isNotEmpty()) stringResource(R.string.input_imported_image) else if (element.icon == 0) stringResource(R.string.input_button_text) else InputButtonIcons.label(context, element.icon), open) { host.open = if (open) null else "element-icon" }
AnchoredMenu(open, onDismiss = { host.open = null }, title = stringResource(R.string.input_button_symbol)) { firstItemFocus ->
MenuItem(stringResource(R.string.input_button_text), element.icon == 0 && element.image.isEmpty(), focusRequester = firstItemFocus) { onChange(element.copy(icon = 0, image = "")); host.open = null }
MenuItem(stringResource(R.string.screen_key_image), element.image.isNotEmpty()) { host.open = null; pickImage.launch("image/*") }
for (code in InputButtonIcons.codes) MenuItem(InputButtonIcons.label(context, code), element.icon == code && element.image.isEmpty(), leading = {
val color = MaterialTheme.colorScheme.onSurface
val symbol = remember(context, code) { InputButtonIcons.drawable(context, code) }
@@ -51,4 +70,10 @@ internal fun InputElementProperties(element: InputSurfaceElement, onChange: (Inp
ToggleRow(host, "element-floating", stringResource(R.string.input_floating_stick), null, element.floating) { onChange(element.copy(floating = it)) }
ToggleRow(host, "element-hide-idle", stringResource(R.string.input_hide_idle), null, element.hideWhenIdle) { onChange(element.copy(hideWhenIdle = it)) }
}
val host = rememberMenuHost()
if ((element.kind == InputElementKind.BUTTON || element.kind == InputElementKind.TRIGGER) && element.icon == 0 && element.image.isEmpty() ||
element.kind == InputElementKind.STICK && element.id.startsWith("legacy:"))
ToggleRow(host, "element-label", stringResource(R.string.input_show_label), null, element.showLabel) { onChange(element.copy(showLabel = it)) }
SliderRow(stringResource(R.string.ctrl_opacity), null, (element.opacity * 100).roundToInt().coerceIn(20, 100), 20..100, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("setting-element-opacity")) { onChange(element.copy(opacity = it / 100f)) }
}
@@ -1,6 +1,12 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import android.util.DisplayMetrics
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.focus.focusRequester
@@ -21,6 +27,9 @@ import androidx.compose.ui.window.DialogProperties
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
fun InputSettingsDialog(onBack: () -> Unit, onChanged: () -> Unit) {
@@ -88,7 +97,9 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
LaunchedEffect(surface) { onSurfaceEditing(surface) }
DisposableEffect(Unit) { onDispose { onSurfaceEditing(false) } }
var managingLayout by remember { mutableStateOf<SavedInputLayout?>(null) }
var exporting by remember { mutableStateOf<String?>(null) }
var error by remember { mutableStateOf<String?>(null) }
val scope = rememberCoroutineScope()
val controller = rememberControllerSettings()
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
@@ -107,6 +118,27 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
val profile = library.profile(profileId)
val preset = library.preset(profile.binding(role))
val layout = library.layout(profileId, role)
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
val target = role
scope.launch {
val raw = withContext(Dispatchers.IO) { readLayoutFile(context, uri) }
val metrics = inputDisplayMetrics(context, target)
val imported = raw?.let { InputLayoutFile.import(context, it, layoutFileName(context, uri) ?: context.getString(R.string.ctrl_layout),
if (target == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY, layout?.style ?: InputSurfaceStyle(),
metrics.widthPixels, metrics.heightPixels, metrics.density) }
if (imported == null) error = context.getString(R.string.input_layout_import_failed)
else if (update { it.withLayout(imported.first).withPreset(imported.second).chooseLayout(profileId, target, imported.first.id) }) go(InputPage.SOURCE)
}
}
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri ->
val text = exporting
exporting = null
if (uri != null && text != null) scope.launch {
val saved = withContext(Dispatchers.IO) { runCatching { context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(text.toByteArray()) } != null }.getOrDefault(false) }
if (!saved) error = context.getString(R.string.input_save_failed)
}
}
fun rename(title: Int, name: String, save: (String) -> Unit) {
naming = InputNameRequest(title, name) { value, _, _ -> save(value) }
}
@@ -249,6 +281,8 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } }
SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1,
format = { "$it%" }) { opacity -> update { it.withLayout(layout.copy(style = layout.style.copy(opacity = opacity))) } }
for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null,
button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } }
}
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
}
@@ -302,10 +336,14 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
if (other.isNotEmpty()) PadTextButton(onClick = { showOther = !showOther }, modifier = Modifier.padding(8.dp)) {
Text(stringResource(if (showOther) R.string.input_hide_other_layouts else R.string.input_other_layouts, other.size))
}
PadTextButton(onClick = { naming = InputNameRequest(R.string.input_new_layout, "") { name, _, _ ->
val created = SavedInputLayout(newInputId(), name, screen = if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY)
if (update { it.withLayout(created).useLayout(profileId, role, created.id, shared = true) }) { go(InputPage.SOURCE); surface = true }
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_layout)) }
Row {
PadTextButton(onClick = { naming = InputNameRequest(R.string.input_new_layout, "") { name, _, _ ->
val created = SavedInputLayout(newInputId(), name, screen = if (role == InputRole.PRIMARY) InputLayoutScreen.MAIN else InputLayoutScreen.SECONDARY)
if (update { it.withLayout(created).useLayout(profileId, role, created.id, shared = true) }) { go(InputPage.SOURCE); surface = true }
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.input_new_layout)) }
PadTextButton(onClick = { importer.launch(arrayOf("application/json", "text/plain", "application/octet-stream", "*/*")) },
modifier = Modifier.padding(8.dp).testTag("input-layout-import")) { Text(stringResource(R.string.boot_movie_import)) }
}
}
}
@@ -329,6 +367,16 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
managingLayout = null
rename(R.string.input_rename_layout, saved.name) { name -> update { it.withLayout(saved.copy(name = name)) } }
}
val exported = remember(saved, library) {
val metrics = inputDisplayMetrics(context, if (saved.screen == InputLayoutScreen.SECONDARY) InputRole.SECONDARY else InputRole.PRIMARY)
InputLayoutFile.export(saved, library.bindings.firstOrNull { it.id == preset.id && it.layoutId == saved.id }
?: library.bindings.firstOrNull { it.layoutId == saved.id }, metrics.widthPixels, metrics.heightPixels)
}
if (exported != null) SecondaryButton(stringResource(R.string.screen_key_layout_export)) {
managingLayout = null
exporting = exported
exporter.launch(InputLayoutFile.fileName(saved))
}
val used = library.usersOfLayout(saved.id).isNotEmpty() || library.bindings.any { it.layoutId == saved.id && library.selectedBindings(it.id) }
if (!used && saved.editable) SecondaryButton(stringResource(R.string.input_delete)) {
managingLayout = null
@@ -413,6 +461,38 @@ private fun InputNavigationRow(title: String, detail: String?, modifier: Modifie
}
}
internal fun quickButtonLabel(button: InputCommand) = when (button) {
InputCommand.STEAM -> R.string.ctrl_steam_button
InputCommand.QUICK_ACCESS -> R.string.ctrl_qam_button
else -> R.string.ctrl_keyboard_button
}
@Suppress("DEPRECATION")
internal fun inputDisplayMetrics(context: Context, role: InputRole): DisplayMetrics = DisplayMetrics().also { metrics ->
(context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputEditorDisplay(role)?.getRealMetrics(metrics)
?: metrics.setTo(context.resources.displayMetrics)
}
private fun readLayoutFile(context: Context, uri: Uri): String? = runCatching {
context.contentResolver.openInputStream(uri)?.use { input ->
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
if (out.size() > 1_000_000) return@use null
}
out.toString(Charsets.UTF_8.name())
}
}.getOrNull()
private fun layoutFileName(context: Context, uri: Uri): String? = runCatching {
context.contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0)?.substringBeforeLast('.')?.trim()?.takeIf { it.isNotEmpty() } else null
}
}.getOrNull()
@Composable
internal fun roleLabel(role: InputRole) = stringResource(when (role) {
InputRole.PHYSICAL -> R.string.input_physical; InputRole.PRIMARY -> R.string.input_primary; InputRole.SECONDARY -> R.string.input_secondary
@@ -58,7 +58,18 @@ import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionState
private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputBindings) {
private data class SurfaceSnapshot(val elements: List<InputSurfaceElement>, val actions: Map<String, InputAction>,
val clicks: Map<String, InputAction>, val scale: 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 gamepad: GamepadScaler? = null) {
var elements by mutableStateOf(layout.elements)
var actions by mutableStateOf(preset.elements)
var clicks by mutableStateOf(preset.clicks)
@@ -70,15 +81,41 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
var adding by mutableStateOf(false)
var properties by mutableStateOf(false)
var clickProperties by mutableStateOf(false)
var history by mutableStateOf<List<Triple<List<InputSurfaceElement>, Map<String, InputAction>, Map<String, InputAction>>>>(emptyList())
var history by mutableStateOf<List<SurfaceSnapshot>>(emptyList())
var layoutScale by mutableFloatStateOf(layout.scale)
private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
private var scaleValue by mutableIntStateOf(100)
private val rescales get() = gamepad != null && elements.any { it.id in gamepad.ids }
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(it) })
?.takeIf { it != elements || rescales && layoutScale != 1f }
val element get() = elements.firstOrNull { it.id == selected }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks
fun checkpoint() { history = (history + Triple(elements, actions, clicks)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.first; actions = it.second; clicks = it.third; history = history.dropLast(1) } }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; history = history.dropLast(1) } }
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
elements = if (base.third > 0f && gamepad != null) {
layoutScale = factor
val others = base.first.filterNot { it.id in gamepad.ids }.scaled(factor / base.third).associateBy { it.id }
gamepad.rescale(base.first, base.third, factor).map { others[it.id] ?: it }
} else base.first.scaled(factor)
scaleValue = percent; scaleBase = Triple(base.first, elements, base.third)
}
fun resetPositions() { positioned?.let { checkpoint(); elements = it; if (rescales) layoutScale = 1f } }
fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e)
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
}
@Suppress("DEPRECATION")
private fun displayAspect(display: Display): Float? = android.util.DisplayMetrics().also(display::getRealMetrics)
.takeIf { it.widthPixels > 0 && it.heightPixels > 0 }?.let { (it.widthPixels.toFloat() / it.heightPixels).coerceIn(.05f, 20f) }
@Composable
fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit,
role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) {
@@ -89,7 +126,14 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val savedBindings = remember { library.preset(bindingsId ?: library.profile(profile).binding(role)) }
val layoutUsers = library.usersOfLayout(savedLayout.id).size
val bindingUsers = library.usersOfBindings(savedBindings.id).size
val draft = remember { SurfaceDraft(savedLayout, savedBindings) }
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)
}
SurfaceDraft(savedLayout, savedBindings, InputLibraries.defaultPositions(context, library, savedLayout), gamepad)
}
val manager = remember { context.getSystemService(DisplayManager::class.java) }
var revision by remember { mutableIntStateOf(0) }
var discard by remember { mutableStateOf(false) }
@@ -109,7 +153,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
InputLibraries.update(context) { latest ->
val l = latest.layouts.first { it.id == savedLayout.id }
val p = latest.preset(savedBindings.id)
latest.withLayout(l.copy(elements = draft.elements)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
latest.withLayout(l.copy(elements = draft.elements, aspect = target?.let(::displayAspect) ?: l.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } }))
}
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
@@ -204,7 +248,7 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"),
update = { view ->
view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13))
view.style = draft.layout.style; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.style = draft.layout.style.copy(hidden = emptySet()); view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.isEnabled = !draft.properties && !draft.adding
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = draft::checkpoint
@@ -269,12 +313,15 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: ()
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_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) {
Checkbox(draft.snap, { draft.snap = it })
Text(stringResource(R.string.ctrl_editor_snap))
}
PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave)
}
if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(it) }
}
@OptIn(ExperimentalLayoutApi::class)
@@ -23,7 +23,6 @@ import com.droiddeck.launcher.input.PointerGestures
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import android.widget.TextView
import com.droiddeck.launcher.input.InputRole
@@ -35,7 +34,7 @@ import com.droiddeck.launcher.input.InputSurfaceSource
import com.droiddeck.launcher.input.InputElementKind
import com.droiddeck.launcher.input.InputButtonIcons
import com.droiddeck.launcher.input.InputButtonShape
import java.io.File
import com.droiddeck.launcher.input.InputButtonImages
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.atan2
@@ -49,40 +48,94 @@ class InputSurfaceView(
private var customLayout: List<InputSurfaceElement> = emptyList(),
private val inputRole: InputRole = InputRole.SECONDARY,
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
private val haptics: Boolean = inputRole != InputRole.PRIMARY,
) : FrameLayout(context) {
private val content = FrameLayout(context)
private val elementSources = ArrayList<InputSurfaceSource>()
private var customCanvas: ViewGroup? = null
init { addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
private val owners = HashMap<Int, View>()
private var requestedLayout = customLayout
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
var onTouchMiss: ((MotionEvent) -> Unit)? = null
private var forwardedPointers = 0
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) forwardedPointers = 0
if (onTouchMiss == null) return super.dispatchTouchEvent(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN) { forwardedPointers = 0; cancelOwners(event) }
if (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) {
val index = event.actionIndex
if (!takesTouchAt(event.getX(index), event.getY(index))) forwardedPointers = forwardedPointers or (1 shl event.getPointerId(index))
else if (SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
if (event.getToolType(index) == MotionEvent.TOOL_TYPE_MOUSE || !takesTouchAt(event.getX(index), event.getY(index)))
forwardedPointers = forwardedPointers or (1 shl event.getPointerId(index))
else if (onTouchMiss != null && SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
}
if (forwardedPointers == 0) return super.dispatchTouchEvent(event)
if (forwardedPointers == 0) return route(event)
var all = 0
for (index in 0 until event.pointerCount) all = all or (1 shl event.getPointerId(index))
event.pointerSubset(all and forwardedPointers.inv())?.let { split ->
try { super.dispatchTouchEvent(split) } finally { split.recycle() }
}
val routed = event.pointerSubset(all and forwardedPointers.inv())?.let { split ->
try { route(split) } finally { split.recycle() }
} ?: false
event.pointerSubset(all and forwardedPointers)?.let { split ->
try { onTouchMiss?.invoke(split) } finally { split.recycle() }
}
if (event.actionMasked == MotionEvent.ACTION_POINTER_UP) forwardedPointers = forwardedPointers and (1 shl event.getPointerId(event.actionIndex)).inv()
if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) forwardedPointers = 0
return true
return onTouchMiss != null || routed
}
private fun route(event: MotionEvent): Boolean {
val action = event.actionMasked
if (action == MotionEvent.ACTION_CANCEL) { cancelOwners(event); return true }
val index = event.actionIndex
val pointer = event.getPointerId(index)
var taken = true
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) {
val target = elementAt(event.getX(index), event.getY(index))
taken = target != null
when {
target is HoldButton -> { owners[pointer] = target; target.press(pointer, true) }
target != null && !(target is StickView && target in owners.values) -> owners[pointer] = target
}
}
if (action == MotionEvent.ACTION_MOVE) for (i in 0 until event.pointerCount) slide(event.getPointerId(i), event.getX(i), event.getY(i))
for (view in owners.values.distinct()) {
if (view is HoldButton) continue
var bits = 0
for ((id, owner) in owners) if (owner === view) bits = bits or (1 shl id)
event.pointerSubset(bits)?.let { split ->
try { split.offsetLocation(-originX(view), -originY(view)); view.dispatchTouchEvent(split) } finally { split.recycle() }
}
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
(owners.remove(pointer) as? HoldButton)?.press(pointer, false, event.flags and MotionEvent.FLAG_CANCELED != 0)
}
return taken
}
private fun slide(pointer: Int, x: Float, y: Float) {
val owner = owners[pointer]
if (owner != null && owner !is HoldButton) return
val over = elementAt(x, y) as? HoldButton
if (over === owner) return
(owner as? HoldButton)?.press(pointer, false, cancelled = true)
if (over == null) owners.remove(pointer) else { owners[pointer] = over; over.press(pointer, true) }
}
private fun cancelOwners(event: MotionEvent) {
if (owners.isEmpty()) return
val views = owners.values.distinct()
owners.clear()
for (view in views) {
if (view is HoldButton) { view.cancel(); continue }
val cancel = MotionEvent.obtain(event.downTime, event.eventTime, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
try { view.dispatchTouchEvent(cancel) } finally { cancel.recycle() }
}
}
fun updateStyle(style: InputSurfaceStyle) {
if (surfaceStyle == style) return
val relayout = surfaceStyle.hidden != style.hidden
surfaceStyle = style
if (relayout) updateCustomLayout(requestedLayout)
customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i)) }
}
@@ -92,23 +145,30 @@ class InputSurfaceView(
view.invalidate()
}
fun updateCustomLayout(layout: List<InputSurfaceElement>) {
fun updateCustomLayout(requested: List<InputSurfaceElement>) {
requestedLayout = requested
val layout = surfaceStyle.shown(requested)
val sameElements = customLayout.map { it.copy(x = 0f, y = 0f, width = 1f, height = 1f) } == layout.map { it.copy(x = 0f, y = 0f, width = 1f, height = 1f) }
customLayout = layout
if (sameElements) customCanvas?.requestLayout() else {
elementSources.forEach { it.close() }; elementSources.clear()
content.removeAllViews(); renderCustom(pad)
owners.clear(); content.removeAllViews(); renderCustom(pad)
}
}
fun releaseInputs() {
val now = android.os.SystemClock.uptimeMillis()
val cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
try { super.dispatchTouchEvent(cancel) } finally { cancel.recycle() }
try { cancelOwners(cancel) } finally { cancel.recycle() }
forwardedPointers = 0
elementSources.forEach { it.release() }
}
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility != VISIBLE) releaseInputs()
}
private fun renderCustom(pad: PadBridge?) {
val canvas = object : ViewGroup(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
@@ -129,7 +189,7 @@ class InputSurfaceView(
}
}
}
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && classic(it) }
canvas.clipChildren = customLayout.none { it.kind == InputElementKind.STICK && (classic(it) || adaptive(it)) }
for (element in customLayout) {
val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } }
canvas.addView(when (element.kind) {
@@ -146,7 +206,7 @@ class InputSurfaceView(
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (pad != null && elementSources.isEmpty()) {
content.removeAllViews()
owners.clear(); content.removeAllViews()
renderCustom(pad)
}
}
@@ -157,19 +217,52 @@ class InputSurfaceView(
super.onDetachedFromWindow()
}
fun takesTouchAt(x: Float, y: Float): Boolean = controlUnder(this, x, y)
fun takesTouchAt(x: Float, y: Float): Boolean = elementAt(x, y) != null
private fun controlUnder(view: View, x: Float, y: Float): Boolean {
if (view.visibility != VISIBLE || x < 0f || y < 0f || x >= view.width || y >= view.height) return false
if (view.isClickable || view is HorizontalScrollView || view is Surface || view is DirectionPad ||
view is androidx.compose.ui.platform.ComposeView) return true
val group = view as? ViewGroup ?: return false
return (group.childCount - 1 downTo 0).any { i ->
val child = group.getChildAt(i)
controlUnder(child, x + group.scrollX - child.x, y + group.scrollY - child.y)
}
private fun elementAt(x: Float, y: Float): View? {
val canvas = customCanvas ?: return null
if (visibility != VISIBLE || x < 0f || y < 0f || x >= width || y >= height) return null
val views = (canvas.childCount - 1 downTo 0).map(canvas::getChildAt).filter { it.visibility == VISIBLE }
views.firstOrNull { !(it is StickView && it.adaptive) && hits(it, x, y, 0f) }?.let { return it }
views.filter { it is HoldButton && hits(it, x, y, slack(it)) }.minByOrNull { distance(it, x, y) }?.let { return it }
if (views.any { it is HoldButton && hits(it, x, y, slack(it) + ADAPTIVE_CLEARANCE_PX) }) return null
return views.filter { it is StickView && it.adaptive && it !in owners.values && (hits(it, x, y, 0f) || it.captures(x - originX(it), y - originY(it))) }
.minByOrNull { distance(it, x, y) }
}
private fun hits(view: View, x: Float, y: Float, slack: Float): Boolean {
val left = originX(view)
val top = originY(view)
if ((view as? HoldButton)?.round == true && slack > 0f) {
val reach = min(view.width, view.height) / 2f + slack
return hypot(x - left - view.width / 2f, y - top - view.height / 2f) <= reach
}
return x >= left - slack && x < left + view.width + slack && y >= top - slack && y < top + view.height + slack
}
private fun slack(view: View) = if ((view as? HoldButton)?.gamepad == true) min(view.width, view.height) / 2f * HIT_SLACK else 0f
private fun distance(view: View, x: Float, y: Float): Float {
val cx = originX(view) + ((view as? StickView)?.centreX() ?: (view.width / 2f))
return hypot(x - cx, y - originY(view) - view.height / 2f)
}
private fun originX(view: View): Float {
var x = 0f
var at: View = view
while (at !== this) { x += at.left - ((at.parent as? View)?.scrollX ?: 0); at = at.parent as? View ?: break }
return x
}
private fun originY(view: View): Float {
var y = 0f
var at: View = view
while (at !== this) { y += at.top - ((at.parent as? View)?.scrollY ?: 0); at = at.parent as? View ?: break }
return y
}
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
@@ -231,11 +324,13 @@ class InputSurfaceView(
protected fun textColor(lit: Boolean) = if (lit) Color.WHITE else tint?.let { light(it, 210, 0.75f) } ?: TEXT
}
private class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
private var down = false
private val pointers = HashSet<Int>()
val round get() = element.buttonShape == InputButtonShape.CIRCLE
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
private val symbol = InputButtonIcons.drawable(context, element.icon)
private val bitmap = element.image.takeIf { it.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && it != "." && it != ".." }?.let { name ->
val file = File(File(context.filesDir, "screenkeys"), name)
private val bitmap = InputButtonImages.file(context, element.image)?.let { file ->
val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.path, size)
val options = BitmapFactory.Options().apply {
@@ -282,23 +377,20 @@ class InputSurfaceView(
canvas.drawText(element.name, cx, height / 2f + labelPaint.textSize * .35f, labelPaint)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> set(true)
MotionEvent.ACTION_UP -> set(false)
MotionEvent.ACTION_CANCEL -> { set(false); source?.release() }
}
return true
fun press(pointer: Int, pressed: Boolean, cancelled: Boolean = false) {
if (pressed) pointers.add(pointer) else pointers.remove(pointer)
set(pointers.isNotEmpty(), cancelled)
}
override fun onDetachedFromWindow() { set(false); source?.release(); super.onDetachedFromWindow() }
fun cancel() { pointers.clear(); set(false, cancelled = true); source?.release() }
private fun set(pressed: Boolean) {
override fun onDetachedFromWindow() { cancel(); super.onDetachedFromWindow() }
private fun set(pressed: Boolean, cancelled: Boolean = false) {
if (down == pressed) return
down = pressed
if (pressed) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
source?.update(if (pressed) 1f else 0f)
if (pressed) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
if (!pressed && cancelled) source?.cancel() else source?.update(if (pressed) 1f else 0f)
invalidate()
}
}
@@ -314,7 +406,7 @@ class InputSurfaceView(
}
override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { source?.gestureButton(button, pressed) }
override fun onWheel(steps: Int) { source?.gestureWheel(steps) }
override fun onLongPress() { performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) }
override fun onLongPress() { feedback(this@TrackpadView, HapticFeedbackConstants.LONG_PRESS) }
}).apply { bounds = RectF(-1e9f, -1e9f, 1e9f, 1e9f) }
private var touching = false
@@ -396,7 +488,7 @@ class InputSurfaceView(
private fun click(down: Boolean) {
if (clicked == down) return
clicked = down
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
if (down) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
source?.click(down)
invalidate()
}
@@ -418,9 +510,18 @@ class InputSurfaceView(
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
private fun reach() = min(width, height) * 0.30f
val adaptive get() = adaptive(element)
private fun centreX() = when {
fun reach() = min(width, height) * if (classic(element)) CLASSIC_REACH else PANEL_REACH
fun captures(x: Float, y: Float): Boolean {
val cx = centreX()
val dx = if (element.control == InputControl.LS) maxOf(0f, x - cx) else x - cx
val limit = reach() * ADAPTIVE_REACH
return dx * dx + (y - height / 2f) * (y - height / 2f) <= limit * limit
}
fun centreX() = when {
!classic(element) || width <= height -> width / 2f
element.control == InputControl.LS -> width - height / 2f
else -> height / 2f
@@ -465,7 +566,7 @@ class InputSurfaceView(
originX = if (floating) event.x else centreX()
originY = if (floating) event.y else height / 2f
touching = true
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
if (lastUp != 0L && event.eventTime - lastUp < CLICK_MS) setClick(true)
follow(event.x, event.y, r, force = true)
}
@@ -501,7 +602,7 @@ class InputSurfaceView(
private fun setClick(down: Boolean) {
if (clicking == down) return
clicking = down
if (down) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
if (down) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
source?.click(down)
}
@@ -556,7 +657,7 @@ class InputSurfaceView(
private fun set(bits: Int) {
if (bits == held) return
if (bits and held.inv() != 0) performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
if (bits and held.inv() != 0) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
held = bits
source?.update((if (bits and 2 != 0) 1f else 0f) - (if (bits and 8 != 0) 1f else 0f),
(if (bits and 4 != 0) 1f else 0f) - (if (bits and 1 != 0) 1f else 0f))
@@ -573,6 +674,11 @@ 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 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
@@ -588,6 +694,8 @@ class InputSurfaceView(
private val TEXT_DIM = Color.rgb(0x7A, 0x80, 0x8A)
private val KNOB = Color.rgb(0x2A, 0x2D, 0x33)
private fun adaptive(element: InputSurfaceElement) = element.kind == InputElementKind.STICK && element.floating && 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)
@@ -18,11 +18,13 @@ import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.KeyboardHost
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.BottomDesktop
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
@@ -39,6 +41,7 @@ class SecondScreenPresentation(
private val dashboard: (@androidx.compose.runtime.Composable () -> Unit)? = null,
private val onSwap: (() -> Unit)? = null,
private val onMenuTouched: () -> Unit = {},
private val onDeckPanel: (DeckPanel) -> Unit = { SessionPrefs.setDeckPanel(sessionActivity, it) },
) : Presentation(sessionActivity, display) {
private val frame = FrameLayout(context)
private var menuView: androidx.compose.ui.platform.ComposeView? = null
@@ -55,6 +58,7 @@ class SecondScreenPresentation(
private var currentMode = SecondScreenMode.NONE
private var keyboardHost: KeyboardHost? = null
private val keyboardShown = androidx.compose.runtime.mutableStateOf(false)
private val deckPanel = androidx.compose.runtime.mutableStateOf(DeckPanel.BOTH)
private var keyboardPending = false
private var imeSeen = false
private var fieldKeyboard = false
@@ -284,6 +288,8 @@ class SecondScreenPresentation(
when (mode) {
SecondScreenMode.TERMINAL -> renderTerminal()
SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.DECK_CONTROLS -> {
if (mode == SecondScreenMode.DECK_CONTROLS) deckPanel.value = SessionPrefs.deckPanel(context)
bar(mode)
val layout = panelLayout(mode)
val controls = InputSurfaceView(context, pad, layout?.elements.orEmpty(),
surfaceStyle = layout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle())
@@ -301,19 +307,39 @@ class SecondScreenPresentation(
}
private fun panelLayout(mode: SecondScreenMode) = com.droiddeck.launcher.input.InputLibraries.read(context)
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.bindings)
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context))
private fun bar(mode: SecondScreenMode, extras: () -> List<BarExtra> = { emptyList() }) {
root.addView(bottomScreenBarView(context) {
sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras())
}, LinearLayout.LayoutParams(-1, -2))
private fun bar(mode: SecondScreenMode) {
val first = barModel(mode) ?: return
root.addView(bottomScreenBarView(context) { barModel(mode) ?: first }, LinearLayout.LayoutParams(-1, -2))
}
internal fun barModel(mode: SecondScreenMode): BottomBarModel? {
val swap = listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) })
fun model(extras: List<BarExtra>, tabs: BarTabs? = null) =
sessionBarModel(context.getString(mode.label), onClose, onMenu, onSteamMenu, onQam, extras, tabs)
return when (mode) {
SecondScreenMode.KEYBOARD_TRACKPAD -> model(listOf(BarExtra(
context.getString(if (keyboardShown.value) R.string.second_hide_keyboard else R.string.second_show_keyboard),
icon = R.drawable.ic_bottom_keyboard, active = keyboardShown.value, tag = "bottom-keyboard") { showKeyboard() }))
SecondScreenMode.DECK_CONTROLS -> model(swap, deckPanelTabs(context, deckPanel.value, ::selectDeckPanel))
SecondScreenMode.DASHBOARD -> model(swap)
SecondScreenMode.TERMINAL -> model(listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard,
tag = "bottom-keyboard") { terminalPanel?.showKeyboard() }))
else -> null
}
}
private fun selectDeckPanel(panel: DeckPanel) {
if (deckPanel.value == panel) return
deckPanel.value = panel
onDeckPanel(panel)
refreshControls()
}
private fun renderDashboard() {
val content = dashboard ?: return
bar(SecondScreenMode.DASHBOARD) {
listOfNotNull(onSwap?.let { BarExtra(context.getString(R.string.swap_screens), icon = R.drawable.ic_bottom_swap, tag = "bottom-swap", onClick = it) })
}
bar(SecondScreenMode.DASHBOARD)
val view = androidx.compose.ui.platform.ComposeView(context).apply { setContent { content() } }
dashboardView = view
root.addView(view, weightParams())
@@ -337,11 +363,7 @@ class SecondScreenPresentation(
}
private fun renderTerminal() {
bar(SecondScreenMode.TERMINAL) {
listOf(BarExtra(context.getString(R.string.drawer_keyboard), icon = R.drawable.ic_bottom_keyboard, tag = "bottom-keyboard") {
terminalPanel?.showKeyboard()
})
}
bar(SecondScreenMode.TERMINAL)
val panel = SessionTerminalPanel(context)
terminalPanel = panel
root.addView(panel, weightParams())
@@ -316,6 +316,8 @@ class DrawerActions(
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 = {},
@@ -642,6 +644,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
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)
}