fix(input): keep custom layouts active on upgrade (#2950)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-20 14:44:46 -05:00
1 parent cb8e70b940
commit 089c18b49d
6 files changed
+733 -24

No files matched your search

@@ -60,15 +60,21 @@ object ControlsChoice {
val owners = owners(context, library)
val defaults = defaults(library)
val forGame = gameName?.takeIf { game != null && it.isNotBlank() }
val newKitDetail = context.getString(R.string.osc_try_new_layout)
fun detail(layout: SavedInputLayout): String? = when {
OnScreenLayout.generated(layout) && current == InputLibraries.previousLayoutId(layout.id) -> newKitDetail
layout.kitless && layout.id.startsWith("kept.") && layout.id != current -> context.getString(R.string.osc_restore_previous_layout)
game != null && game in owners[layout.id].orEmpty() && layout.id !in defaults && forGame != null ->
context.getString(R.string.osc_layout_detail_game, forGame)
else -> null
}
val saved = library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }
.filter { l -> l.id == current || l.id in defaults || owners[l.id].isNullOrEmpty() || game in owners[l.id].orEmpty() }
.map { l ->
val mine = game != null && game in owners[l.id].orEmpty() && l.id !in defaults
Option(l.id, l.name, if (mine && forGame != null) context.getString(R.string.osc_layout_detail_game, forGame) else null,
l.id != current && deletable(context, library, l))
}
.map { l -> Option(l.id, l.name, detail(l), l.id != current && deletable(context, library, l)) }
val stock = library.layouts.firstOrNull { it.id == InputLibraries.OVERLAY }
return (if (own) listOf(Option(DEFAULT, context.getString(R.string.osc_default))) else emptyList()) +
Option(InputLibraries.OVERLAY, context.getString(R.string.osc_layout_gamepad), context.getString(R.string.osc_layout_gamepad_detail)) +
Option(InputLibraries.OVERLAY, context.getString(R.string.osc_layout_gamepad),
stock?.let(::detail) ?: context.getString(R.string.osc_layout_gamepad_detail)) +
(if (steamMode) listOf(Option(GameControls.STEAM, context.getString(R.string.osc_layout_steam), context.getString(R.string.osc_layout_steam_detail))) else emptyList()) +
saved +
(if (forGame != null) listOf(Option(NEW, context.getString(R.string.osc_layout_new_for, forGame))) else emptyList())
@@ -115,7 +121,11 @@ object ControlsChoice {
val bindings = if (steam) null else {
val library = InputLibraries.read(context)
val layout = library.layouts.first { it.id == id }
library.bindings.firstOrNull { !it.physical && it.layoutId == layout.id && it.compatible(layout) }?.id ?: newInputId().also { newId ->
val available = library.bindings.filter { !it.physical && it.layoutId == layout.id && it.compatible(layout) }
val preferred = listOfNotNull(own(context, library, game), library.activePart(desktop, InputRole.PRIMARY).bindings,
library.profile(library.activeId(desktop)).binding(InputRole.PRIMARY))
preferred.firstNotNullOfOrNull { id -> relatedPreset(library, available, id, layout.id) }
?: available.firstOrNull()?.id ?: newInputId().also { newId ->
InputLibraries.update(context) { it.withPreset(SavedInputBindings(newId, layout.name, false, layout.id)) }
}
}
@@ -126,6 +136,15 @@ object ControlsChoice {
}
}
private fun relatedPreset(library: InputLibrary, available: List<SavedInputBindings>, id: String, target: String): String? {
val from = library.preset(id).layoutId ?: return null
return available.firstOrNull { candidate ->
candidate.id == id ||
target == InputLibraries.previousLayoutId(from) && candidate.id == InputLibraries.previousBindingsId(id, target) ||
from == InputLibraries.previousLayoutId(target) && id == InputLibraries.previousBindingsId(candidate.id, from)
}?.id
}
/** Copies the layout [game] draws now, actions included, into a layout of its own and chooses it for that game only. */
fun newForGame(context: Context, game: Long, name: String, desktop: Boolean): Pair<String, String> {
val layoutId = newInputId()
@@ -32,7 +32,7 @@ object InputLibraries {
if (version < 12) library = barStockLayouts(library)
if (version < 13) library = LegacyScreenKeyMigration.pin(library)
if (version < 14) library = deckGamepadSurfaces(context, library)
if (version < 15) library = kitGamepads(library)
if (version < 15) library = kitGamepads(context, library, version)
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) {
@@ -239,38 +239,78 @@ object InputLibraries {
return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate()
}
/**
* Gamepads saved by the old editor follow the virtual controller's kit again; their positions don't map onto the new controls.
* One that kept positions for the kit's controls is also kept as it was, under its own name, with its actions. Where the copy
* doesn't fit the library's limits, the gamepad itself keeps its positions instead.
*/
private fun kitGamepads(library: InputLibrary): InputLibrary {
private fun kitGamepads(context: Context, library: InputLibrary, version: Int): InputLibrary {
fun old(layout: SavedInputLayout) = (layout.origin ?: layout.id).let { it == OVERLAY || it.startsWith("migrated.layout.") }
fun follow(layout: SavedInputLayout): SavedInputLayout {
val extras = layout.elements.filterNot { KitLayout.isKit(it.id) }
return layout.copy(elements = extras, origin = if (layout.id == OVERLAY) null else OVERLAY, aspect = if (extras.isEmpty()) 0f else layout.aspect, scale = 1f)
}
val positioned = library.layouts.filter { old(it) && it.elements.any { e -> KitLayout.isKit(e.id) } }
val positioned = library.layouts.filter { layout ->
if (!old(layout)) return@filter false
val hasKit = layout.elements.any { KitLayout.isKit(it.id) }
if (hasKit) !stockLegacyGeometry(context, layout)
else version == 14 && layout.aspect > 0f
}
val inPlace = positioned.fold(library.copy(layouts = library.layouts.map { if (old(it) && it !in positioned) follow(it) else it })) { acc, layout ->
acc.withLayout(layout.copy(kitless = true))
}
var result = library.copy(layouts = library.layouts.map { if (old(it)) follow(it) else it })
val replacements = mutableMapOf<String, InputPart>()
for (layout in positioned) {
val id = "kept." + UUID.nameUUIDFromBytes(layout.id.toByteArray(Charsets.UTF_8))
val id = previousLayoutId(layout.id)
val presets = library.bindings.filter { it.layoutId == layout.id }
if (result.layouts.any { it.id == id } || result.layouts.size >= 256 || result.bindings.size + presets.size > 512) {
result = result.copy(layouts = result.layouts.map { if (it.id == layout.id) layout else it }).withLayout(layout.copy(kitless = true))
continue
}
val name = "${layout.name} (old layout)".take(80)
result = result.copy(bindings = result.bindings + presets.map { b ->
b.copy(id = "kept." + UUID.nameUUIDFromBytes((b.id + "\u0000" + id).toByteArray(Charsets.UTF_8)), name = name, layoutId = id)
}).withLayout(layout.copy(id = id, name = name, origin = null, kitless = true))
val saved = layout.copy(id = id, name = name, origin = null, kitless = true)
val savedPresets = presets.map { preset ->
val binding = previousBindingsId(preset.id, id)
replacements[preset.id] = InputPart(binding, id)
preset.copy(id = binding, name = name, layoutId = id,
elements = preset.elements.filterKeys { saved.element(it) != null },
clicks = preset.clicks.filterKeys { saved.element(it)?.hasClick == true })
}
result = result.copy(bindings = result.bindings + savedPresets).withLayout(saved)
}
val expanded = runCatching { result.validate() }.getOrNull()
val migrated = result.copy(
profiles = result.profiles.map { profile ->
profile.copy(parts = profile.parts.mapValues { (_, part) -> replacements[part.bindings] ?: part })
},
selections = result.selections.mapValues { (_, selection) ->
selection.copy(parts = selection.parts.mapValues { (_, bindings) -> replacements[bindings]?.bindings ?: bindings })
},
)
val expanded = runCatching { migrated.validate() }.getOrNull()
return if (expanded != null && encode(expanded).length <= 2_000_000) expanded else inPlace.validate()
}
internal fun previousLayoutId(layout: String) =
"kept." + UUID.nameUUIDFromBytes(layout.toByteArray(Charsets.UTF_8))
internal fun previousBindingsId(binding: String, previousLayout: String) =
"kept." + UUID.nameUUIDFromBytes((binding + "\u0000" + previousLayout).toByteArray(Charsets.UTF_8))
private fun stockLegacyGeometry(context: Context, layout: SavedInputLayout): Boolean {
if (layout.scale != 1f) return false
val (display, metrics) = primaryDisplay(context)
val width = metrics.widthPixels.coerceAtLeast(1)
val height = metrics.heightPixels.coerceAtLeast(1)
val named = (layout.origin ?: layout.id).removePrefix("migrated.layout.").split("x")
.mapNotNull(String::toIntOrNull).takeIf { it.size == 2 && it.all { side -> side > 0 } }
?.let { it[0] to it[1] }
val sizes = listOfNotNull(named, width to height, height to width).distinct()
val positions = layout.elements.filter { KitLayout.isKit(it.id) }.associateBy { it.id }
return sizes.any { (w, h) ->
if (layout.aspect != (w.toFloat() / h).coerceIn(.05f, 20f)) return@any false
val stock = LegacyLayoutGeometry(display, w, h)
listOf(stock.elements(), stock.elements(previousStickGeometry = true)).any { elements ->
elements.size == positions.size && elements.all { element -> positions[element.id] == element }
}
}
}
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)
@@ -0,0 +1,237 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sqrt
import kotlin.math.sin
// Recreates the stock geometry written by schema 14 so its migration can recognise unedited layouts.
internal class LegacyLayoutGeometry(context: Context, private val width: Int, private val height: Int) {
private val safe = Rect()
private val resources = context.resources
private var fit = 1f
private class Control(val id: String, val group: String, val stick: Int, val radiusDp: Float, val offsetXDp: Float, val offsetYDp: Float) {
var radius = 0f
var cx = 0f
var cy = 0f
val halfW get() = if (id in shoulderIds) radius * SHOULDER_WIDTH else radius
val halfH get() = if (id in shoulderIds) radius * SHOULDER_HEIGHT else radius
}
private val controls = listOf(
Control("up", "dpad", -1, 30f, 0f, -50f),
Control("right", "dpad", -1, 30f, 50f, 0f),
Control("down", "dpad", -1, 30f, 0f, 50f),
Control("left", "dpad", -1, 30f, -50f, 0f),
Control("ls", "ls", 0, 48f, 0f, 0f),
Control("rs", "rs", 1, 48f, 0f, 0f),
Control("a", "face", -1, 30f, 0f, 50f),
Control("b", "face", -1, 30f, 50f, 0f),
Control("x", "face", -1, 30f, -50f, 0f),
Control("y", "face", -1, 30f, 0f, -50f),
Control("lb", "lb", -1, 24f, 0f, 0f),
Control("rb", "rb", -1, 24f, 0f, 0f),
Control("lt", "lt", -1, 24f, 0f, 0f),
Control("rt", "rt", -1, 24f, 0f, 0f),
Control("select", "select", -1, 20f, 0f, 0f),
Control("start", "start", -1, 20f, 0f, 0f),
Control("guide", "guide", -1, 22f, 0f, 0f),
Control("qam", "qam", -1, 22f, 0f, 0f),
)
private val groups = controls.map { it.group }.distinct()
private fun dp(value: Float) = value * resources.displayMetrics.density
private fun scaled(value: Float) = dp(value) * fit
private fun fitScale(): Float {
val metrics = resources.displayMetrics
val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
}
private fun pxPerMm(dpi: Float): Float {
val nominal = resources.displayMetrics.densityDpi.toFloat()
return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
}
private fun placeAuto(w: Float, h: Float) {
val metrics = resources.displayMetrics
val mmX = pxPerMm(metrics.xdpi)
val mmY = pxPerMm(metrics.ydpi)
val usableW = w - safe.left - safe.right
val usableH = h - safe.top - safe.bottom
val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
val gap = dp(12f)
val floor = BOTTOM_MARGIN_MM * mmY
val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
put("ls", safe.left + inboard, restY)
put("face", w - safe.right - inboard, restY)
besideBelow("dpad", "ls", 1f, gap, floor)
besideBelow("rs", "face", -1f, gap, floor)
val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
val shoulderY = if (phone) safe.top + floor + halfH("lb")
else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
shoulders("face", "rb", "rt", -1f, gap, shoulderY)
val bottom = h - safe.bottom - floor - extent("guide")
val spread = extent("guide") + gap / 2f
put("guide", w / 2f - spread, bottom)
put("qam", w / 2f + spread, bottom)
val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
put("select", inner, restY)
put("start", w - inner, restY)
if (phone) {
val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
put("select", top, shoulderY)
put("start", w - top, shoulderY)
}
if (crowded("select", gap) || crowded("start", gap)) {
above("select", "dpad", gap)
val (sx, sy) = centre("select")
put("start", w - sx, sy)
if (crowded("start", gap)) above("start", "rs", gap)
}
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
val row = centre("select").second
put("guide", w / 2f - spread, row)
put("qam", w / 2f + spread, row)
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
val top = safe.top + dp(8f) + extent("guide")
put("guide", w / 2f - spread, top)
put("qam", w / 2f + spread, top)
}
}
}
private fun drop(group: String, anchor: String, gap: Float): Float =
(extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
val (ax, ay) = centre(anchor)
val reach = extent(anchor) + extent(group) + gap
val floor = height - safe.bottom - margin - extent(group)
val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
val dx = sqrt(max(0f, reach * reach - dy * dy))
put(group, ax + inward * dx, ay + dy)
}
private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
val (ax, _) = centre(anchor)
val spread = extent(bumper) + gap / 2f
put(bumper, ax + inward * spread, y)
put(trigger, ax - inward * spread, y)
}
private fun above(group: String, anchor: String, gap: Float) {
val (ax, ay) = centre(anchor)
put(group, ax, ay - extent(anchor) - gap - extent(group))
}
private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
val (x, y) = centre(group)
return groups.any { other ->
if (other == group || other == except) return@any false
val (ox, oy) = centre(other)
val dx = x - ox
val dy = y - oy
sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
}
}
private fun members(group: String) = controls.filter { it.group == group }
private fun centre(group: String): Pair<Float, Float> {
val first = members(group).first()
return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
}
private fun extent(group: String): Float = members(group).maxOf { control ->
sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
}
private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
private fun put(group: String, x: Float, y: Float) {
for (control in members(group)) {
control.cx = x + scaled(control.offsetXDp)
control.cy = y + scaled(control.offsetYDp)
}
}
private fun clamp(group: String) {
val list = members(group)
val margin = dp(4f)
val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
if (dx == 0f && dy == 0f) return
for (control in list) { control.cx += dx; control.cy += dy }
}
fun elements(previousStickGeometry: Boolean = false): List<InputSurfaceElement> {
fit = fitScale()
controls.forEach { it.radius = scaled(it.radiusDp) }
placeAuto(width.toFloat(), height.toFloat())
groups.forEach(::clamp)
val result = controls.map { c ->
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
2 * c.halfW / width, 2 * c.halfH / height, hideWhenIdle = c.stick >= 0,
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded()
}.toMutableList()
result += keyboard()
return result
}
private fun keyboard(): InputSurfaceElement {
val radius = dp(KEYBOARD_RADIUS_DP)
val cx = safe.left + dp(KEYBOARD_X_DP)
val cy = height - safe.bottom - dp(KEYBOARD_Y_DP)
return InputSurfaceElement(InputControl.A, (cx - radius) / width, (cy - radius) / height, 2 * radius / width, 2 * radius / height,
KitLayout.KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded()
}
private fun widenStickPreviously(e: InputSurfaceElement): InputSurfaceElement {
val extra = e.width * (STICK_REACH - 1f)
return when (e.control) {
InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) }
InputControl.RS -> e.copy(width = (e.width + extra).coerceAtMost(1f - e.x))
else -> e
}
}
private fun widenStick(e: InputSurfaceElement): InputSurfaceElement {
val extra = e.width * (STICK_REACH - 1f)
val width = e.width + extra
return when (e.control) {
InputControl.LS -> e.copy(x = (e.x - extra).coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width)
InputControl.RS -> e.copy(x = e.x.coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width)
else -> e
}
}
private companion object {
const val MIN_FACE_MM = 9.5f
const val FULL_SIZE_HEIGHT_MM = 85f
const val BOTTOM_MARGIN_MM = 5f
const val DROP_DEGREES = 35.0
const val PHONE_MAX_HEIGHT_MM = 90f
const val SHOULDER_WIDTH = 1.45f
const val SHOULDER_HEIGHT = 0.8f
val shoulderIds = setOf("lb", "rb", "lt", "rt")
const val STICK_REACH = 1.25f
const val KEYBOARD_RADIUS_DP = 18f
const val KEYBOARD_X_DP = 90f
const val KEYBOARD_Y_DP = 34f
}
}