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

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

No files matched your search

@@ -7,6 +7,21 @@ object ControllerPrefs {
const val STEAM_BLUE = 0xFF1A9FFF.toInt()
const val OFF = "off"
val tints = listOf(
STEAM_BLUE to R.string.ctrl_tint_steam_blue,
0xFF66C0F4.toInt() to R.string.ctrl_tint_sky,
0xFFE8EEF4.toInt() to R.string.ctrl_tint_white,
0xFFC77DFF.toInt() to R.string.ctrl_tint_violet,
0xFF3DDC84.toInt() to R.string.ctrl_tint_green,
0xFFFFA726.toInt() to R.string.ctrl_tint_amber,
0xFFFF5252.toInt() to R.string.ctrl_tint_red,
0xFFFF6FB5.toInt() to R.string.ctrl_tint_pink,
)
val opacities = listOf(40, 60, 80, 100)
val sizes = listOf(80, 90, 100, 110, 125)
val deadZones = listOf(0, 5, 8, 12, 15, 20, 25)
const val DEFAULT_DEAD_ZONE_PERCENT = 12
@@ -24,15 +39,20 @@ object ControllerPrefs {
OFF to R.string.ctrl_target_hidden,
)
/** Settings still read: the rest only seed the one-time library and layout migrations. */
class Settings(
val tint: Int,
val opacity: Int,
val size: Int,
val stickClick: Boolean,
val adaptiveSticks: Boolean,
val rumble: Boolean,
val steamButton: Boolean,
val qamButton: Boolean,
val keyboardButton: Boolean,
val selectSteam: Boolean,
val joyConVr: Boolean,
val snap: Boolean,
val customLayout: Boolean,
val mapping: Map<String, String>,
val deadZone: Int,
)
@@ -43,17 +63,50 @@ object ControllerPrefs {
val p = prefs(context)
return Settings(
tint = p.getInt("tint", STEAM_BLUE),
opacity = p.getInt("opacity", 100).coerceIn(1, 100),
opacity = p.getInt("opacity", 100).takeIf { it in opacities } ?: 100,
size = p.getInt("size", 100).takeIf { it in sizes } ?: 100,
stickClick = p.getBoolean("stickClick", true),
adaptiveSticks = p.getBoolean("adaptiveSticks", true),
rumble = rumbleEnabled(context),
steamButton = p.getBoolean("steamButton", true),
qamButton = p.getBoolean("qamButton", true),
keyboardButton = p.getBoolean("keyboardButton", true),
selectSteam = p.getBoolean("selectSteam", false),
joyConVr = joyConVr(context),
snap = snap(context),
mapping = mappable.associate { (id, _) -> id to (p.getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id) },
customLayout = p.all.keys.any { it.startsWith("layout.") },
mapping = mappable.associate { (id, _) -> id to target(context, id) },
deadZone = deadZone(context),
)
}
fun target(context: Context, id: String): String =
prefs(context).getString("map.$id", id)?.takeIf { t -> targets.any { it.first == t } } ?: id
fun setTarget(context: Context, id: String, target: String) {
prefs(context).edit().putString("map.$id", target).apply()
}
fun setTint(context: Context, tint: Int) {
prefs(context).edit().putInt("tint", tint).apply()
}
fun setOpacity(context: Context, percent: Int) {
prefs(context).edit().putInt("opacity", percent).apply()
}
fun setSize(context: Context, percent: Int) {
prefs(context).edit().putInt("size", percent).apply()
}
fun setStickClick(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("stickClick", on).apply()
}
fun setAdaptiveSticks(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("adaptiveSticks", on).apply()
}
fun rumbleEnabled(context: Context): Boolean = prefs(context).getBoolean("rumble", true)
fun deadZone(context: Context): Int =
@@ -67,6 +120,18 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("rumble", on).apply()
}
fun setSteamButton(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("steamButton", on).apply()
}
fun setKeyboardButton(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("keyboardButton", on).apply()
}
fun setSelectSteam(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("selectSteam", on).apply()
}
fun joyConVr(context: Context): Boolean = prefs(context).getBoolean("joyConVr", true)
fun setJoyConVr(context: Context, on: Boolean) {
@@ -79,6 +144,24 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("snap", on).apply()
}
fun layout(context: Context, width: Int, height: Int): Map<String, Pair<Float, Float>> {
val raw = prefs(context).getString("layout.${width}x$height", null) ?: return emptyMap()
return raw.split(';').mapNotNull { entry ->
val (group, pos) = entry.split(':').takeIf { it.size == 2 } ?: return@mapNotNull null
val (x, y) = pos.split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 2 } ?: return@mapNotNull null
group to (x to y)
}.toMap()
}
fun setLayout(context: Context, width: Int, height: Int, positions: Map<String, Pair<Float, Float>>) {
val raw = positions.entries.joinToString(";") { (group, pos) -> "$group:${pos.first},${pos.second}" }
prefs(context).edit().putString("layout.${width}x$height", raw).apply()
}
fun resetLayout(context: Context, width: Int, height: Int) {
prefs(context).edit().remove("layout.${width}x$height").apply()
}
fun resetAll(context: Context) {
prefs(context).edit().clear().putBoolean("rumble", true).apply()
}
@@ -1,216 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionPrefs
/** The on-screen layout each game draws, shared by the in-game Controller page and Settings › Controller. A null game is the default. */
object ControlsChoice {
const val NEW = "new"
const val DEFAULT = "default"
data class Game(val id: Long, val name: String, val layout: String)
private fun own(library: InputLibrary, id: String?): String? = id?.takeIf { bindings ->
library.bindings.any { it.id == bindings && !it.physical && it.layoutId?.let { l -> library.layouts.any { x -> x.id == l && x.supports(InputRole.PRIMARY) } } == true }
}
private fun own(context: Context, library: InputLibrary, game: Long?) = own(library, GameControls.bindings(context, game))
/** The input library with [game]'s main-screen layout selected, without saving it. */
fun library(context: Context, game: Long?, desktop: Boolean): InputLibrary {
val library = InputLibraries.read(context)
val chosen = own(context, library, game)
return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen)
}
data class Option(val id: String, val name: String, val detail: String? = null, val deletable: Boolean = false)
/** Layouts made for one game, so they're listed only for that game. Layouts made before that was recorded are recognised by carrying the name of the game that draws them. */
private fun owners(context: Context, library: InputLibrary): Map<String, Set<Long>> {
val named = GameControls.games(context).mapNotNull { game ->
val layout = own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } ?: return@mapNotNull null
val name = GameControls.name(context, game) ?: return@mapNotNull null
(layout to game).takeIf { library.layouts.any { it.id == layout && it.name == name } }
}
return (named + GameControls.madeFor(context).toList()).groupBy({ it.first }, { it.second }).mapValues { it.value.toSet() }
}
private fun defaults(library: InputLibrary) =
listOf(false, true).mapNotNull { library.activeLayout(it, InputRole.PRIMARY)?.id }.toSet()
private fun deletable(context: Context, library: InputLibrary, layout: SavedInputLayout): Boolean {
if (!layout.editable || layout.id == InputLibraries.OVERLAY || layout.id in defaults(library)) return false
if (GameControls.games(context).any { game -> own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } == layout.id }) return false
return library.profiles.none { p -> p.parts.any { (role, part) -> part.layout == layout.id && drawn(library, p.id, role) } } &&
library.bindings.none { it.layoutId == layout.id && library.selectedBindings(it.id) }
}
/** Whether [profile]'s [role] part is what a mode shows, rather than one a choice made since covers. */
private fun drawn(library: InputLibrary, profile: String, role: InputRole) =
listOf(false, true).any { desktop -> library.activeId(desktop) == profile && library.selection(desktop).parts[role] == null }
private fun keeps(library: InputLibrary, profile: String) =
profile == InputProfile.GAME || profile == InputProfile.DESKTOP || listOf(false, true).any { library.activeId(it) == profile }
fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null, desktop: Boolean = false): List<Option> {
val library = InputLibraries.read(context)
val own = game != null && game in GameControls.games(context)
val current = current(context, game, steamMode, desktop)
val owners = owners(context, library)
val defaults = defaults(library)
val forGame = gameName?.takeIf { game != null && it.isNotBlank() }
val newKitDetail = context.getString(R.string.osc_try_new_layout)
fun detail(layout: SavedInputLayout): String? = when {
OnScreenLayout.generated(layout) && current == InputLibraries.previousLayoutId(layout.id) -> newKitDetail
layout.kitless && layout.id.startsWith("kept.") && layout.id != current -> context.getString(R.string.osc_restore_previous_layout)
game != null && game in owners[layout.id].orEmpty() && layout.id !in defaults && forGame != null ->
context.getString(R.string.osc_layout_detail_game, forGame)
else -> null
}
val saved = library.layouts.filter { it.editable && it.supports(InputRole.PRIMARY) && it.id != InputLibraries.OVERLAY }
.filter { l -> l.id == current || l.id in defaults || owners[l.id].isNullOrEmpty() || game in owners[l.id].orEmpty() }
.map { l -> Option(l.id, l.name, detail(l), l.id != current && deletable(context, library, l)) }
val stock = library.layouts.firstOrNull { it.id == InputLibraries.OVERLAY }
return (if (own) listOf(Option(DEFAULT, context.getString(R.string.osc_default))) else emptyList()) +
Option(InputLibraries.OVERLAY, context.getString(R.string.osc_layout_gamepad),
stock?.let(::detail) ?: context.getString(R.string.osc_layout_gamepad_detail)) +
(if (steamMode) listOf(Option(GameControls.STEAM, context.getString(R.string.osc_layout_steam), context.getString(R.string.osc_layout_steam_detail))) else emptyList()) +
saved +
(if (forGame != null) listOf(Option(NEW, context.getString(R.string.osc_layout_new_for, forGame))) else emptyList())
}
/** Whether [game] chose Steam's touch controls but runs where they can't be shown. */
fun steamUnavailable(context: Context, game: Long?, steamMode: Boolean) = !steamMode && GameControls.steamLayout(context, game)
/** Deletes the saved layout [id] and its actions. A profile that can no longer be chosen goes with it; one that can falls back to the stock layout. */
fun delete(context: Context, id: String) {
val games = GameControls.games(context).mapNotNull { GameControls.bindings(context, it) }.toSet()
InputLibraries.update(context) { library ->
val layout = library.layouts.first { it.id == id }
require(deletable(context, library, layout))
val users = library.usersOfLayout(id)
val orphans = users.filterNot { keeps(library, it.id) }
var result = users.filter { keeps(library, it.id) }.fold(library) { acc, p ->
p.parts.filterValues { it.layout == id }.keys.fold(acc) { lib, role ->
lib.chooseLayout(p.id, role, when {
role == InputRole.PRIMARY -> InputLibraries.OVERLAY
p.base == InputProfile.DESKTOP -> InputLibraries.TRACKPAD
else -> InputLibraries.DECK
})
}
}
result = orphans.fold(result) { acc, p -> acc.removeProfile(p.id) }
val loose = orphans.flatMap { p -> p.parts.values.map { it.bindings } }.toSet()
.filter { b -> b !in games && result.usersOfBindings(b).isEmpty() && !result.selectedBindings(b) && result.bindings.any { it.id == b } }
.filterNot { b -> InputStockLayouts.presets(InputStockLayouts.layouts()).any { it.id == b } }
result = loose.fold(result) { acc, b -> acc.removeBindings(b) }
result.removeLayout(id)
}
GameControls.forgetLayout(context, id)
}
fun current(context: Context, game: Long?, steamMode: Boolean, desktop: Boolean = false): String =
if (steamMode && GameControls.steamLayout(context, game)) GameControls.STEAM
else library(context, game, desktop).activeLayout(desktop, InputRole.PRIMARY)?.id ?: InputLibraries.OVERLAY
fun choose(context: Context, game: Long?, id: String, desktop: Boolean, gameName: String? = null) {
require(id != NEW)
if (id == DEFAULT) { if (game != null) useDefault(context, game); return }
val steam = id == GameControls.STEAM
val bindings = if (steam) null else {
val library = InputLibraries.read(context)
val layout = library.layouts.first { it.id == id }
val available = library.bindings.filter { !it.physical && it.layoutId == layout.id && it.compatible(layout) }
val preferred = listOfNotNull(own(context, library, game), library.activePart(desktop, InputRole.PRIMARY).bindings,
library.profile(library.activeId(desktop)).binding(InputRole.PRIMARY))
preferred.firstNotNullOfOrNull { id -> relatedPreset(library, available, id, layout.id) }
?: available.firstOrNull { it.id != InputLibraries.primaryOf(library, !desktop) }?.id ?: newInputId().also { newId ->
InputLibraries.update(context) { it.withPreset(SavedInputBindings(newId, layout.name, false, layout.id)) }
}
}
if (game != null) GameControls.choose(context, game, bindings, steam, gameName)
else {
if (bindings != null) InputLibraries.update(context) { it.selectPart(desktop, InputRole.PRIMARY, bindings) }
SessionPrefs.setSteamTouchLayout(context, steam)
}
}
private fun relatedPreset(library: InputLibrary, available: List<SavedInputBindings>, id: String, target: String): String? {
val from = library.preset(id).layoutId ?: return null
return available.firstOrNull { candidate ->
candidate.id == id ||
target == InputLibraries.previousLayoutId(from) && candidate.id == InputLibraries.previousBindingsId(id, target) ||
from == InputLibraries.previousLayoutId(target) && id == InputLibraries.previousBindingsId(candidate.id, from)
}?.id
}
/** Copies the layout [game] draws now, actions included, into a layout of its own and chooses it for that game only. */
fun newForGame(context: Context, game: Long, name: String, desktop: Boolean): Pair<String, String> {
val layoutId = newInputId()
val bindingsId = newInputId()
InputLibraries.update(context) { latest -> copyForGame(context, latest, game, name, desktop, layoutId, bindingsId) }
GameControls.markMadeFor(context, layoutId, game)
GameControls.choose(context, game, bindingsId, steam = false, name = name)
return layoutId to bindingsId
}
/** [latest] with a copy of the layout [game] draws now, actions included, under the given ids. Nothing is chosen for the game. */
fun copyForGame(context: Context, latest: InputLibrary, game: Long, name: String, desktop: Boolean, layoutId: String, bindingsId: String): InputLibrary {
run {
val chosen = own(context, latest, game)
val part = (if (chosen == null) latest else latest.selectPart(desktop, InputRole.PRIMARY, chosen)).activePart(desktop, InputRole.PRIMARY)
val source = latest.layouts.firstOrNull { it.id == part.layout && it.editable } ?: latest.layouts.first { it.id == InputLibraries.OVERLAY }
val actions = latest.bindings.firstOrNull { it.id == part.bindings && it.compatible(source) }
?: latest.bindings.firstOrNull { !it.physical && it.compatible(source) }
?: SavedInputBindings(bindingsId, source.name, false, source.id)
val title = name.trim().take(80).ifEmpty { source.name }
return latest.withLayout(source.derived(layoutId, title)).withPreset(actions.copy(id = bindingsId, name = title, layoutId = layoutId))
}
}
/** Uses [bindingsId], made by [copyForGame], for [game] only. */
fun useForGame(context: Context, game: Long, name: String, bindingsId: String) {
InputLibraries.read(context).bindings.firstOrNull { it.id == bindingsId }?.layoutId?.let { GameControls.markMadeFor(context, it, game) }
GameControls.choose(context, game, bindingsId, steam = false, name = name)
}
/** The profile, layout and actions the editor opens for [game], or null when its layout can't be edited here. */
fun editTarget(context: Context, game: Long?, desktop: Boolean): Triple<String, String, String>? {
val library = library(context, game, desktop)
val layout = library.activeLayout(desktop, InputRole.PRIMARY)?.takeIf { it.editable } ?: return null
return Triple(library.activeId(desktop), layout.id, library.activePart(desktop, InputRole.PRIMARY).bindings)
}
/** Whether [game] has a layout of its own, rather than the default. */
fun hasOwn(context: Context, game: Long?): Boolean = own(context, InputLibraries.read(context), game) != null
/** Whether saving an edit of [game]'s layout would also change the default or another game. */
fun shared(context: Context, game: Long?): Boolean {
game ?: return false
val library = InputLibraries.read(context)
val bindings = own(context, library, game) ?: return true
val layout = library.preset(bindings).layoutId
fun drawsLayout(id: String) = library.bindings.firstOrNull { it.id == id }?.layoutId == layout
return library.usersOfLayout(layout ?: return true).isNotEmpty() ||
library.selections.values.any { s -> s.parts[InputRole.PRIMARY]?.let(::drawsLayout) == true } ||
GameControls.games(context).any { it != game && own(context, library, it)?.let(::drawsLayout) == true }
}
fun useDefault(context: Context, game: Long) = GameControls.clear(context, game)
/** Games with a layout of their own, by name. */
fun games(context: Context): List<Game> {
val library = InputLibraries.read(context)
return GameControls.games(context).mapNotNull { id ->
val layout = when {
GameControls.steamLayout(context, id) -> context.getString(R.string.osc_layout_steam)
else -> own(context, library, id)?.let { b -> library.layouts.firstOrNull { it.id == library.preset(b).layoutId }?.name } ?: return@mapNotNull null
}
val name = GameControls.name(context, id)
?: id.takeIf { it in Int.MIN_VALUE..Int.MAX_VALUE }?.let { runCatching { SteamTouchConfig.gameName(context, it.toInt()) }.getOrNull() }
?: id.toString()
Game(id, name, layout)
}.sortedBy { it.name.lowercase() }
}
}
@@ -1,41 +0,0 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.session.SessionPrefs
/** Decides where the on-screen controls go and why they're hidden, from the session's state alone. */
object ControlsPresenter {
enum class Place { NONE, MAIN, BOTTOM, STEAM }
data class State(
val mode: String,
val desktop: Boolean,
val virtualPad: Boolean,
val covered: Boolean,
val controllerInUse: Boolean,
val hiddenByTap: Boolean,
val steamLayout: Boolean,
val bottomScreen: Boolean,
)
data class Plan(val place: Place, val hidden: OnScreenControls.Hidden? = null, val shortcutsOnly: Boolean = false) {
val shown get() = place != Place.NONE && hidden == null
}
fun plan(state: State): Plan = when {
state.covered || !state.virtualPad || state.mode == SessionPrefs.OSC_NEVER -> Plan(Place.NONE)
state.mode == SessionPrefs.OSC_AUTO && state.desktop -> Plan(Place.NONE)
else -> Plan(
when {
state.bottomScreen -> Place.BOTTOM
state.steamLayout && state.mode != SessionPrefs.OSC_STEAM_QAM -> Place.STEAM
else -> Place.MAIN
},
when {
state.hiddenByTap -> OnScreenControls.Hidden.BY_TAP
state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse -> OnScreenControls.Hidden.BY_CONTROLLER
else -> null
},
shortcutsOnly = state.mode == SessionPrefs.OSC_STEAM_QAM,
)
}
}
@@ -1,46 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
/** Which on-screen layout each game uses. Games without a choice use the default profile's main-screen layout. */
object GameControls {
const val STEAM = "steam"
private const val MADE_FOR = "layout-for."
private fun prefs(context: Context) = context.getSharedPreferences("game-controls", Context.MODE_PRIVATE)
/** The main-screen bindings preset saved for [game], whose layout is the one drawn. */
fun bindings(context: Context, game: Long?): String? = game?.let { prefs(context).getString("$it.bindings", null) }
fun steamLayout(context: Context, game: Long?): Boolean {
val p = prefs(context)
return if (game != null && p.contains("$game.steam")) p.getBoolean("$game.steam", false) else SessionPrefs.steamTouchLayout(context)
}
fun choose(context: Context, game: Long, bindings: String?, steam: Boolean, name: String? = null) {
prefs(context).edit().apply { if (bindings == null) remove("$game.bindings") else putString("$game.bindings", bindings) }
.apply { if (!name.isNullOrBlank()) putString("$game.name", name) }
.putBoolean("$game.steam", steam).apply()
}
/** Games with their own choice, in the order of their ids. */
fun games(context: Context): List<Long> = prefs(context).all.keys
.filter { it.endsWith(".steam") || it.endsWith(".bindings") }
.mapNotNull { it.substringBeforeLast('.').toLongOrNull() }.distinct().sorted()
/** Layouts made for one game, by layout id. */
fun madeFor(context: Context): Map<String, Long> = prefs(context).all.mapNotNull { (key, value) ->
if (key.startsWith(MADE_FOR) && value is Long) key.removePrefix(MADE_FOR) to value else null
}.toMap()
fun markMadeFor(context: Context, layout: String, game: Long) { prefs(context).edit().putLong(MADE_FOR + layout, game).apply() }
fun forgetLayout(context: Context, layout: String) { prefs(context).edit().remove(MADE_FOR + layout).apply() }
fun name(context: Context, game: Long): String? = prefs(context).getString("$game.name", null)
fun clear(context: Context, game: Long) {
prefs(context).edit().remove("$game.bindings").remove("$game.steam").apply()
}
}
@@ -9,7 +9,6 @@ object GamepadGeometry {
VIEW, STEAM, QAM, MENU,
PANELS,
L4, L5, R5, R4,
LEFT_TOUCH, RIGHT_TOUCH,
}
data class Box(val cx: Float, val cy: Float, val width: Float, val height: Float) {
@@ -27,11 +26,10 @@ object GamepadGeometry {
fun tall(w: Float, h: Float): Boolean = h >= w * 0.45f
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false, grips: Boolean = false, upright: Boolean = false,
trackpads: Boolean = false): Map<Slot, Box> {
fun layout(w: Float, h: Float, density: Float, portraitDock: Boolean = false): Map<Slot, Box> {
if (w <= 0f || h <= 0f) return emptyMap()
if (upright || portraitDock && h >= w * 0.6f && w >= 300 * density && h >= 300 * density) {
return portraitLayout(w, h, density, grips, trackpads)
if (portraitDock && h >= w * 0.9f && w >= 300 * density && h >= 360 * density) {
return portraitLayout(w, h, density)
}
val pad = 8 * density
val buttonH = 40 * density
@@ -72,7 +70,6 @@ object GamepadGeometry {
else -> 1
}
middleGrid(columns, gap - 2 * gutter, shoulderY - buttonH / 2f)
if (grips) gripsBetween(boxes, w, gap - 2 * gutter, boxes.values.maxOf { if (it.cx in (w - gap) / 2f..(w + gap) / 2f) it.bottom else 0f } + gutter, h - pad, density)
} else {
val side = min(min(w * 0.5f, h * 0.70f), (w - 2 * gridButton - 2 * gutter) / 1.42f)
val main = side * 0.62f
@@ -88,75 +85,45 @@ object GamepadGeometry {
val gap = w - 2 * (side * 0.40f + main / 2f)
val columns = if (gap >= 2 * gridButton) 2 else 1
val rows = (middle.size + columns - 1) / columns
val gridTop = h - pad - rows * buttonH - (rows - 1) * 10 * density
middleGrid(columns, gap - 2 * gutter, gridTop)
if (grips) gripsBetween(boxes, w, w - 2 * (side * 0.74f + second / 2f) - 2 * gutter, shoulderY + buttonH / 2f + gutter, gridTop - gutter, density)
middleGrid(columns, gap - 2 * gutter, h - pad - rows * buttonH - (rows - 1) * 10 * density)
val panelsW = min(112 * density, w - 2 * (side * 0.57f + shoulderW / 2f) - 2 * gutter)
if (panelsW >= buttonH) boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
}
return boxes
}
/** The back grips in the gap between a landscape panel's two clusters: one row of four, or two rows of two. */
private fun gripsBetween(boxes: MutableMap<Slot, Box>, w: Float, span: Float, top: Float, bottom: Float, density: Float) {
val gap = 8 * density
val minimum = 44 * density
val rows = if ((span - 3 * gap) / 4f >= minimum) 1 else if ((span - gap) / 2f >= minimum) 2 else return
val perRow = 4 / rows
val cellW = ((span - (perRow - 1) * gap) / perRow).coerceAtMost(96 * density)
val cellH = ((bottom - top - (rows - 1) * gap) / rows).coerceAtMost(64 * density)
if (cellH < minimum) return
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
val col = i % perRow; val row = i / perRow
boxes[slot] = Box(w / 2f + (col - (perRow - 1) / 2f) * (cellW + gap), bottom - (rows - 1 - row) * (cellH + gap) - cellH / 2f, cellW, cellH)
}
}
/**
* The panel under a portrait game: shoulders with View and Menu across the top, the back grips under them when the kit has
* them, then the d-pad and face buttons and, along the bottom edge, the sticks or trackpads, each as large as the panel allows.
*/
private fun portraitLayout(w: Float, h: Float, density: Float, grips: Boolean, trackpads: Boolean): Map<Slot, Box> {
private fun portraitLayout(w: Float, h: Float, density: Float): Map<Slot, Box> {
val pad = 8 * density
val gap = 8 * density
val buttonH = 44 * density
val boxes = LinkedHashMap<Slot, Box>()
val topGap = 4 * density
val topW = (w - 2 * pad - 5 * topGap) / 6f
val top = listOf(Slot.LEFT_OUTER_SHOULDER, Slot.LEFT_INNER_SHOULDER, Slot.VIEW, Slot.MENU, Slot.RIGHT_INNER_SHOULDER, Slot.RIGHT_OUTER_SHOULDER)
for ((i, slot) in top.withIndex()) boxes[slot] = Box(pad + topW / 2f + i * (topW + topGap), pad + buttonH / 2f, topW, buttonH)
var areaTop = pad + buttonH + gap
if (grips) {
val gripW = (w - 2 * pad - 3 * gap) / 4f
val gripH = min(56 * density, (h - areaTop) * 0.12f).coerceAtLeast(buttonH)
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex())
boxes[slot] = Box(pad + gripW / 2f + i * (gripW + gap), areaTop + gripH / 2f, gripW, gripH)
areaTop += gripH + gap
}
val area = h - pad - areaTop - gap
if (trackpads) {
val second = min(w * 0.42f, area * 0.5f)
val rowH = area - second
val col = (w - 2 * pad - 3 * gap) / 4f
val stick = min(col, rowH)
val rowY = h - pad - rowH / 2f
val secondY = areaTop + second / 2f
boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second)
boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second)
boxes[Slot.LEFT_TOUCH] = Box(pad + col / 2f, rowY, col, rowH)
boxes[Slot.LEFT_MAIN] = Box(pad + col * 1.5f + gap, rowY, stick, stick)
boxes[Slot.RIGHT_MAIN] = Box(w - pad - col * 1.5f - gap, rowY, stick, stick)
boxes[Slot.RIGHT_TOUCH] = Box(w - pad - col / 2f, rowY, col, rowH)
return boxes
}
val main = min(w * 0.46f, area * 0.53f)
val second = min(w * 0.42f, area - main)
val secondY = areaTop + second / 2f
val scale = min(1f, (h - 2 * pad - 4 * gap - 3 * buttonH) / (w * 0.7f))
val main = w * 0.4f * scale
val second = w * 0.3f * scale
val mainY = h - pad - main / 2f
boxes[Slot.LEFT_SECOND] = Box(w * 0.25f, secondY, second, second)
boxes[Slot.RIGHT_SECOND] = Box(w * 0.75f, secondY, second, second)
boxes[Slot.LEFT_MAIN] = Box(w * 0.25f, mainY, main, main)
boxes[Slot.RIGHT_MAIN] = Box(w * 0.75f, mainY, main, main)
val secondY = mainY - main / 2f - gap - second / 2f
val shoulderY = secondY - second / 2f - gap - buttonH / 2f
val boxes = linkedMapOf(
Slot.LEFT_MAIN to Box(w * 0.25f, mainY, main, main),
Slot.RIGHT_MAIN to Box(w * 0.75f, mainY, main, main),
Slot.LEFT_SECOND to Box(w * 0.25f, secondY, second, second),
Slot.RIGHT_SECOND to Box(w * 0.75f, secondY, second, second),
)
val utilityW = (w - 2 * pad - 3 * gap) / 4f
for ((i, slot) in middle.withIndex()) {
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), pad + buttonH / 2f, utilityW, buttonH)
}
val gripTop = pad + buttonH + gap
val gripH = min(64 * density, shoulderY - buttonH / 2f - gap - gripTop)
for ((i, slot) in listOf(Slot.L4, Slot.L5, Slot.R5, Slot.R4).withIndex()) {
boxes[slot] = Box(pad + utilityW / 2f + i * (utilityW + gap), gripTop + gripH / 2f, utilityW, gripH)
}
val panelsW = min(112 * density, w * 0.22f)
val shoulderW = (w - 2 * pad - 4 * gap - panelsW) / 4f
boxes[Slot.PANELS] = Box(w / 2f, shoulderY, panelsW, buttonH)
boxes[Slot.LEFT_OUTER_SHOULDER] = Box(pad + shoulderW / 2f, shoulderY, shoulderW, buttonH)
boxes[Slot.LEFT_INNER_SHOULDER] = Box(pad + shoulderW * 1.5f + gap, shoulderY, shoulderW, buttonH)
boxes[Slot.RIGHT_INNER_SHOULDER] = Box(w - pad - shoulderW * 1.5f - gap, shoulderY, shoulderW, buttonH)
boxes[Slot.RIGHT_OUTER_SHOULDER] = Box(w - pad - shoulderW / 2f, shoulderY, shoulderW, buttonH)
return boxes
}
}
@@ -10,7 +10,11 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 16
private const val VERSION = 14
private val redesignVersions = 15..16
private const val KIT_DPAD = "kit:dpad"
private const val KEYBOARD = "builtin:keyboard"
private const val REDESIGN_BACKUP = "library-before-controller-revert"
private const val KEY = "library"
private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay"
@@ -23,17 +27,24 @@ object InputLibraries {
fun read(context: Context): InputLibrary {
val p = prefs(context)
val raw = p.getString(KEY, null)
val decoded = raw?.let(::decode)
val decoded = raw?.let { decode(it, context) }
if (raw != null && decoded == null) return scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, migrate(context))))
var library = decoded ?: scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, migrate(context))))
val version = raw?.let { JSONObject(it).getInt("version") } ?: 0
if (version in redesignVersions && raw != null) {
val encoded = encode(library)
if (encoded.length > 2_000_000) return library
if (!commitWithBackup(p, raw, REDESIGN_BACKUP, encoded)) {
android.util.Log.e("InputLibraries", "Could not save the restored input library")
return library
}
}
if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library)))
if (version < 11) library = neutralStockLayouts(library)
if (version < 10) library = restyleGamepads(context, library)
if (version < 12) library = barStockLayouts(library)
if (version < 13) library = LegacyScreenKeyMigration.pin(library)
if (version < 14) library = deckGamepadSurfaces(context, library)
if (version < 15) library = kitGamepads(context, library, version)
if (version < 16) library = ownModeSelections(library)
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
val legacy = LegacyScreenKeyMigration.snapshot(context)
if (legacy != null) {
@@ -76,24 +87,35 @@ object InputLibraries {
fun update(context: Context, change: (InputLibrary) -> InputLibrary): InputLibrary {
val p = prefs(context)
val stored = p.getString(KEY, null)
val invalid = stored != null && decode(stored) == null
val invalid = stored != null && decode(stored, context) == null
require(!invalid || runCatching { JSONObject(stored!!).getInt("version") }.getOrNull()?.let { it <= VERSION } != false) {
"The saved input library cannot be edited by this version."
}
val updated = change(read(context)).validate()
if (invalid) {
val backupKey = when {
invalid -> RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8))
stored != null && p.getString(KEY, null) == stored &&
JSONObject(stored).getInt("version") in redesignVersions -> REDESIGN_BACKUP
else -> null
}
if (backupKey != null) {
val encoded = encode(updated)
require(encoded.length <= 2_000_000) { "The input library is too large to save." }
val recovery = RECOVERY + UUID.nameUUIDFromBytes(stored!!.toByteArray(Charsets.UTF_8))
if (!p.edit().putString(recovery, stored).putString(KEY, encoded).commit()) {
// A failed commit has already changed the in-memory preferences; put the previous library back.
p.edit().putString(KEY, stored).remove(recovery).apply()
error("Could not save the input library and its recovery copy.")
check(commitWithBackup(p, requireNotNull(stored), backupKey, encoded)) {
"Could not save the input library and its recovery copy."
}
} else write(context, updated)
return updated
}
private fun commitWithBackup(prefs: android.content.SharedPreferences, raw: String, backupKey: String, encoded: String): Boolean {
val previousBackup = prefs.getString(backupKey, null)
if (prefs.edit().putString(backupKey, raw).putString(KEY, encoded).commit()) return true
// SharedPreferences updates its in-memory values even when the disk write fails.
prefs.edit().putString(KEY, raw).putString(backupKey, previousBackup).apply()
return false
}
private fun write(context: Context, library: InputLibrary) {
val encoded = encode(library.validate())
require(encoded.length <= 2_000_000) { "The input library is too large to save." }
@@ -130,14 +152,27 @@ object InputLibraries {
return InputLibrary(profiles, layouts, bindings, selected).validate()
}
fun setAdaptiveSticks(context: Context, layoutId: String, on: Boolean): Boolean = runCatching {
update(context) { library ->
library.copy(layouts = library.layouts.map { layout ->
if (layout.id != layoutId || !layout.editable) layout
else layout.copy(elements = layout.elements.map { if (it.kind == InputElementKind.STICK) it.copy(floating = on, hideWhenIdle = on) else it })
})
}
}.onSuccess { ControllerPrefs.setAdaptiveSticks(context, on) }.isSuccess
fun setQuickButton(context: Context, layoutId: String, button: InputCommand, shown: Boolean): Boolean = runCatching {
update(context) { library -> library.layouts.firstOrNull { it.id == layoutId && it.editable }?.let { library.withLayout(it.withQuickButton(button, shown)) } ?: library }
}.isSuccess
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): Pair<List<InputSurfaceElement>, Float>? {
val origin = layout.origin ?: layout.id
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements to it.aspect }
if (origin == OVERLAY) {
if (origin == OVERLAY || origin.startsWith("migrated.layout.")) {
val (surfaceContext, metrics) = primaryDisplay(context)
val w = metrics.widthPixels.coerceAtLeast(1)
val h = metrics.heightPixels.coerceAtLeast(1)
return KitLayout.elements(surfaceContext, PadKit.current(context), w, h, scale = layout.scale) to w.toFloat() / h
val size = if (origin == OVERLAY) listOf(metrics.widthPixels, metrics.heightPixels)
else origin.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() to it[0].toFloat() / it[1] }
}
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect }
}
@@ -149,12 +184,29 @@ object InputLibraries {
return surfaceContext to DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) }
}
private fun restyleGamepads(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.none { it.id == OVERLAY || it.id.startsWith("migrated.layout.") }) return library
val (surfaceContext, metrics) = primaryDisplay(context)
return library.copy(layouts = library.layouts.map { layout ->
val size = when {
layout.id == OVERLAY -> listOf(metrics.widthPixels, metrics.heightPixels)
layout.id.startsWith("migrated.layout.") -> layout.id.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
else -> emptyList()
}
if (size.size != 2 || size.any { it <= 0 }) layout
else layout.copy(elements = LegacyGamepadLayout(surfaceContext, size[0], size[1]).restyle(layout.elements))
})
}
private fun upgradeOverlay(context: Context, library: InputLibrary): InputLibrary {
if (library.layouts.none { it.template == InputLayoutTemplate.OVERLAY }) return library
val (surfaceContext, metrics) = primaryDisplay(context)
val settings = ControllerPrefs.read(context)
val style = InputSurfaceStyle(opacity = settings.opacity)
val elements = LegacyGamepadLayout(surfaceContext, metrics.widthPixels.coerceAtLeast(1), metrics.heightPixels.coerceAtLeast(1)).elements()
val style = InputSurfaceStyle(settings.tint, settings.opacity)
val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old ->
old.id to old.copy(name = "Gamepad", elements = emptyList(), template = InputLayoutTemplate.CUSTOM, style = style)
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style,
aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f))
}
var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
val migrated = mutableMapOf<Pair<String, String>, String>()
@@ -165,8 +217,9 @@ object InputLibraries {
val id = migrated.getOrPut(key) {
val old = library.preset(part.bindings)
val newId = migrationBindingId(result, old.id, layout.id)
val clicks = if (settings.stickClick) old.clicks else old.clicks + KitLayout.clickIds.associateWith { InputAction.Disabled }
result = result.withPreset(old.copy(id = newId, layoutId = layout.id, clicks = clicks))
val keyboard = elements.filter { it.id == "builtin:keyboard" }.associate { it.id to InputAction.Command(InputCommand.KEYBOARD) }
val clicks = if (settings.stickClick) old.clicks else old.clicks + elements.filter { it.hasClick }.associate { it.id to InputAction.Disabled }
result = result.withPreset(old.copy(id = newId, layoutId = layout.id, elements = old.elements + keyboard, clicks = clicks))
newId
}
part.copy(bindings = id)
@@ -175,6 +228,15 @@ object InputLibraries {
}
val oldBindings = migrated.keys.map { it.first }.toSet()
result = result.copy(bindings = result.bindings.filter { it.id !in oldBindings || result.usersOfBindings(it.id).isNotEmpty() })
// Older editor layouts were resolution-specific. Keep each as a selectable saved layout.
for (key in ControllerPrefs.prefs(context).all.keys.filter { it.startsWith("layout.") }.sorted()) {
val size = key.removePrefix("layout.").split('x').mapNotNull { it.toIntOrNull() }
if (size.size != 2 || size.any { it <= 0 } || result.layouts.size >= 128) continue
if (size[0] == metrics.widthPixels && size[1] == metrics.heightPixels) continue
val id = "migrated.$key"
if (result.layouts.none { it.id == id }) result = result.withLayout(SavedInputLayout(id, "Gamepad ${size[0]} × ${size[1]}",
LegacyGamepadLayout(surfaceContext, size[0], size[1]).elements(), style = style, aspect = (size[0].toFloat() / size[1]).coerceIn(.05f, 20f)))
}
return result.validate()
}
@@ -240,90 +302,6 @@ object InputLibraries {
return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate()
}
private fun kitGamepads(context: Context, library: InputLibrary, version: Int): InputLibrary {
fun old(layout: SavedInputLayout) = (layout.origin ?: layout.id).let { it == OVERLAY || it.startsWith("migrated.layout.") }
fun follow(layout: SavedInputLayout): SavedInputLayout {
val extras = layout.elements.filterNot { KitLayout.isKit(it.id) }
return layout.copy(elements = extras, origin = if (layout.id == OVERLAY) null else OVERLAY, aspect = if (extras.isEmpty()) 0f else layout.aspect, scale = 1f)
}
val positioned = library.layouts.filter { layout ->
if (!old(layout)) return@filter false
val hasKit = layout.elements.any { KitLayout.isKit(it.id) }
if (hasKit) !stockLegacyGeometry(context, layout)
else version == 14 && layout.aspect > 0f
}
val inPlace = positioned.fold(library.copy(layouts = library.layouts.map { if (old(it) && it !in positioned) follow(it) else it })) { acc, layout ->
acc.withLayout(layout.copy(kitless = true))
}
var result = library.copy(layouts = library.layouts.map { if (old(it)) follow(it) else it })
val replacements = mutableMapOf<String, InputPart>()
for (layout in positioned) {
val id = previousLayoutId(layout.id)
val presets = library.bindings.filter { it.layoutId == layout.id }
if (result.layouts.any { it.id == id } || result.layouts.size >= 256 || result.bindings.size + presets.size > 512) {
result = result.copy(layouts = result.layouts.map { if (it.id == layout.id) layout else it }).withLayout(layout.copy(kitless = true))
continue
}
val name = "${layout.name} (old layout)".take(80)
val saved = layout.copy(id = id, name = name, origin = null, kitless = true)
val savedPresets = presets.map { preset ->
val binding = previousBindingsId(preset.id, id)
replacements[preset.id] = InputPart(binding, id)
preset.copy(id = binding, name = name, layoutId = id,
elements = preset.elements.filterKeys { saved.element(it) != null },
clicks = preset.clicks.filterKeys { saved.element(it)?.hasClick == true })
}
result = result.copy(bindings = result.bindings + savedPresets).withLayout(saved)
}
val migrated = result.copy(
profiles = result.profiles.map { profile ->
profile.copy(parts = profile.parts.mapValues { (_, part) -> replacements[part.bindings] ?: part })
},
selections = result.selections.mapValues { (_, selection) ->
selection.copy(parts = selection.parts.mapValues { (_, bindings) -> replacements[bindings]?.bindings ?: bindings })
},
)
val expanded = runCatching { migrated.validate() }.getOrNull()
return if (expanded != null && encode(expanded).length <= 2_000_000) expanded else inPlace.validate()
}
internal fun previousLayoutId(layout: String) =
"kept." + UUID.nameUUIDFromBytes(layout.toByteArray(Charsets.UTF_8))
internal fun previousBindingsId(binding: String, previousLayout: String) =
"kept." + UUID.nameUUIDFromBytes((binding + "\u0000" + previousLayout).toByteArray(Charsets.UTF_8))
private fun stockLegacyGeometry(context: Context, layout: SavedInputLayout): Boolean {
if (layout.scale != 1f) return false
val (display, metrics) = primaryDisplay(context)
val width = metrics.widthPixels.coerceAtLeast(1)
val height = metrics.heightPixels.coerceAtLeast(1)
val named = (layout.origin ?: layout.id).removePrefix("migrated.layout.").split("x")
.mapNotNull(String::toIntOrNull).takeIf { it.size == 2 && it.all { side -> side > 0 } }
?.let { it[0] to it[1] }
val sizes = listOfNotNull(named, width to height, height to width).distinct()
val positions = layout.elements.filter { KitLayout.isKit(it.id) }.associateBy { it.id }
return sizes.any { (w, h) ->
if (layout.aspect != (w.toFloat() / h).coerceIn(.05f, 20f)) return@any false
val stock = LegacyLayoutGeometry(display, w, h)
listOf(stock.elements(), stock.elements(previousStickGeometry = true)).any { elements ->
elements.size == positions.size && elements.all { element -> positions[element.id] == element }
}
}
}
internal fun primaryOf(library: InputLibrary, desktop: Boolean) =
library.profiles.firstOrNull { it.id == library.activeId(desktop) }?.parts?.get(InputRole.PRIMARY)?.bindings
/** Choosing a layout used to take the first actions saved for it, which could be the other mode's mouse and keys. */
private fun ownModeSelections(library: InputLibrary): InputLibrary = library.copy(selections = library.selections.mapValues { (mode, selection) ->
val desktop = mode == InputProfile.DESKTOP
val chosen = selection.parts[InputRole.PRIMARY]
if (chosen != null && chosen == primaryOf(library, !desktop) && chosen != primaryOf(library, desktop))
selection.copy(parts = selection.parts - InputRole.PRIMARY)
else selection
})
private fun migrationBindingId(library: InputLibrary, binding: String, layout: String): String {
val seed = JSONArray(listOf(binding, layout)).toString().toByteArray(Charsets.UTF_8)
val base = "migrated.bindings." + UUID.nameUUIDFromBytes(seed)
@@ -356,7 +334,7 @@ object InputLibraries {
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL).put("kitless", layout.kitless))
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
}
val bindings = JSONArray()
for (b in library.bindings) {
@@ -385,22 +363,32 @@ object InputLibraries {
.put("profiles", profiles).put("layouts", layouts).put("bindings", bindings).toString()
}
internal fun decode(raw: String): InputLibrary? = runCatching {
internal fun decode(raw: String, context: Context? = null): InputLibrary? = runCatching {
require(raw.length <= 2_000_000)
val doc = JSONObject(raw); require(doc.getInt("version") in 2..VERSION)
val doc = JSONObject(raw)
val version = doc.getInt("version")
val restore = context != null && version in redesignVersions
require(version in 2..VERSION || restore)
val generated = mutableSetOf<String>()
val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
val elements = layout.getJSONArray("elements").objects(64).map { e ->
val stored = layout.getJSONArray("elements").objects(64).map { e ->
InputSurfaceElement(requireNotNull(InputControl.fromId(e.getString("control"))), e.getDouble("x").toFloat(),
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
}
SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")),
val id = layout.getString("id")
val origin = layout.optionalString("origin")
val followsGamepad = restore && !layout.optBoolean("kitless") &&
(id == OVERLAY || origin == OVERLAY) &&
stored.none { it.id.startsWith("legacy:") || it.id == KIT_DPAD || it.id == KEYBOARD }
if (followsGamepad) generated += id
SavedInputLayout(id, layout.getString("name"), if (restore) stored.map { it.bounded() } else stored, InputLayoutTemplate.valueOf(layout.getString("template")),
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
layout.optJSONArray("hidden")?.let { hidden -> (0 until hidden.length()).map { InputCommand.valueOf(hidden.getString(it)) }.toSet() }.orEmpty()),
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), layout.optionalString("origin"),
layout.optDouble("scale", 1.0).toFloat(), layout.optBoolean("kitless", false))
InputLayoutScreen.valueOf(layout.optString("screen", InputLayoutScreen.BOTH.name)), layout.optDouble("aspect", 0.0).toFloat(), origin,
layout.optDouble("scale", 1.0).toFloat())
}
val bindings = doc.getJSONArray("bindings").objects(512).map { b ->
val controls = b.getJSONObject("controls").actions(28).mapKeys { requireNotNull(InputControl.fromId(it.key)) }
@@ -427,9 +415,41 @@ object InputLibraries {
value.optBoolean("profileSelected", profile != InputProfiles.AUTO || parts.length() == 0))
}
}.orEmpty()
InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections).validate()
val library = InputLibrary(profiles, layouts, bindings, doc.getString("selected"), doc.getString("steam"), doc.getString("desktop"), selections)
(if (restore) restoreGamepads(requireNotNull(context), library, generated) else library).validate()
}.getOrNull()
private fun restoreGamepads(context: Context, library: InputLibrary, generated: Set<String>): InputLibrary {
val (display, metrics) = primaryDisplay(context)
val height = metrics.heightPixels.coerceAtLeast(1)
val layouts = library.layouts.map { layout ->
if (layout.id !in generated) return@map layout
val width = if (layout.aspect > 0f) (layout.aspect * height).toInt().coerceAtLeast(1)
else metrics.widthPixels.coerceAtLeast(1)
val gamepad = LegacyGamepadLayout(display, width, height, scale = layout.scale).elements()
layout.copy(elements = gamepad.take(64 - layout.elements.size) + layout.elements,
aspect = (width.toFloat() / height).coerceIn(.05f, 20f))
}
val byId = layouts.associateBy { it.id }
val bindings = library.bindings.map { preset ->
val layout = byId[preset.layoutId] ?: return@map preset
val elements = layout.elements.associateBy { it.id }
val defaults = layout.elements.mapNotNull { element ->
val action = when (element.id) {
KEYBOARD -> InputAction.Command(InputCommand.KEYBOARD)
KIT_DPAD -> InputAction.Native()
else -> return@mapNotNull null
}
element.id to action
}.toMap()
preset.copy(
elements = defaults + preset.elements.filter { (id, action) -> elements[id]?.let { action.validFor(it) } == true },
clicks = preset.clicks.filter { (id, action) -> elements[id]?.hasClick == true && action.validForClick() },
)
}
return library.copy(layouts = layouts, bindings = bindings)
}
private fun JSONArray.objects(limit: Int): List<JSONObject> {
require(length() <= limit)
return (0 until length()).map { getJSONObject(it) }
@@ -22,8 +22,6 @@ data class SavedInputLayout(
val aspect: Float = 0f,
val origin: String? = null,
val scale: Float = 1f,
/** The player removed every kit control from this gamepad, so it must not follow the virtual controller again. */
val kitless: Boolean = false,
) {
val editable get() = template == InputLayoutTemplate.CUSTOM
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
@@ -51,7 +49,7 @@ data class SavedInputBindings(
fun action(element: InputSurfaceElement) = elements[element.id]
?: if (element.id == "legacy:${element.control.id}") controls[element.control] ?: InputAction.Native()
else defaultElementAction(element.id)
else InputAction.Disabled
fun clickAction(element: InputSurfaceElement) = clicks[element.id]
?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() }
@@ -138,8 +136,8 @@ data class InputLibrary(
fun withPreset(value: SavedInputBindings) = copy(bindings = bindings.filterNot { it.id == value.id } + value)
fun withLayout(value: SavedInputLayout) = copy(layouts = layouts.filterNot { it.id == value.id } + value,
bindings = bindings.map { preset -> if (preset.layoutId != value.id) preset else preset.copy(
elements = preset.elements.filter { (id, action) -> value.element(id)?.let { action.validFor(it) } == true },
clicks = preset.clicks.filter { (id, action) -> value.element(id)?.hasClick == true && action.validForClick() }) })
elements = preset.elements.filter { (id, action) -> value.elements.any { it.id == id && action.validFor(it) } },
clicks = preset.clicks.filter { (id, action) -> value.elements.any { it.id == id && it.hasClick && action.validForClick() } }) })
fun duplicateProfile(id: String, name: String, newId: String = newInputId(), sharePhysical: Boolean = false): InputLibrary {
require(profiles.size < 64)
@@ -273,8 +271,8 @@ data class InputLibrary(
require(preset.physical || preset.keys.isEmpty())
val layout = preset.layoutId?.let { id -> layouts.first { it.id == id } }
require(!preset.physical || layout == null && preset.elements.isEmpty() && preset.clicks.isEmpty())
require(preset.elements.all { (id, action) -> layout?.element(id)?.let { action.validFor(it) } == true })
require(preset.clicks.all { (id, action) -> layout?.element(id)?.hasClick == true && action.validForClick() })
require(preset.elements.all { (id, action) -> layout?.elements?.firstOrNull { it.id == id }?.let { action.validFor(it) } == true })
require(preset.clicks.all { (id, action) -> layout?.elements?.any { it.id == id && it.hasClick } == true && action.validForClick() })
require(preset.keys.all { it.key.device.isNotBlank() && it.key.keyCode >= 0 && it.key.scanCode >= 0 &&
it.action.validFor(InputControl.A) && (it.action !is InputAction.Native || it.action.target == null) })
}
@@ -314,12 +312,3 @@ internal fun InputAction.validFor(element: InputSurfaceElement): Boolean = when
element.kind == InputElementKind.TRIGGER -> target == InputControl.LT || target == InputControl.RT
else -> target.dimensions == 1 && target != InputControl.LT && target != InputControl.RT
}
/**
* A saved element, or the kit control that [id] names: in a layout made from the built-in gamepad every kit control keeps its
* binding while it's removed, so Reset or Restore brings it back with its action.
*/
internal fun SavedInputLayout.element(id: String): InputSurfaceElement? =
elements.firstOrNull { it.id == id } ?: KitLayout.element(id)?.takeIf {
this.id == InputLibraries.OVERLAY || origin == InputLibraries.OVERLAY || KitLayout.bindsTo(id, elements)
}
@@ -48,7 +48,7 @@ data class InputProfile(
copy(bindings = bindings + (role to (bindings[role].orEmpty() + (control to action))))
fun elementAction(role: InputRole, id: String, control: InputControl): InputAction =
elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else defaultElementAction(id)
elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else InputAction.Disabled
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
@@ -115,12 +115,3 @@ internal fun InputAction.validFor(control: InputControl): Boolean = when (this)
is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f
else -> true
}
/** What an on-screen element with no saved action does: kit controls press their own button, everything else is unassigned. */
internal fun defaultElementAction(id: String): InputAction = when (id) {
KitLayout.DPAD_ID -> InputAction.Native()
KitLayout.KEYBOARD_ID -> InputAction.Command(InputCommand.KEYBOARD)
OnScreenLayout.STEAM_SHORTCUT_ID -> InputAction.Command(InputCommand.STEAM)
OnScreenLayout.QAM_SHORTCUT_ID -> InputAction.Command(InputCommand.QUICK_ACCESS)
else -> InputAction.Disabled
}
@@ -38,13 +38,8 @@ data class InputSurfaceElement(
) {
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
fun bounded() = copy(x = x.coerceIn(0f, 1f - MIN_SIZE), y = y.coerceIn(0f, 1f - MIN_SIZE),
width = width.coerceIn(MIN_SIZE, (1f - x.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)),
height = height.coerceIn(MIN_SIZE, (1f - y.coerceIn(0f, 1f - MIN_SIZE)).coerceAtLeast(MIN_SIZE)))
companion object {
const val MIN_SIZE = .01f
}
fun bounded() = copy(x = x.coerceIn(0f, 0.97f), y = y.coerceIn(0f, 0.97f),
width = width.coerceIn(0.03f, (1f - x.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)), height = height.coerceIn(0.03f, (1f - y.coerceIn(0f, 0.97f)).coerceAtLeast(0.03f)))
}
internal val QUICK_BUTTONS = listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.KEYBOARD)
@@ -56,31 +51,15 @@ val InputSurfaceElement.quickButton: InputCommand? get() = when {
else -> null
}
/** Controls whose boxes touch, grown by 15%, scale around one shared anchor so a cluster such as the face buttons keeps its shape. */
internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> {
internal fun List<InputSurfaceElement>.scaled(factor: Float): List<InputSurfaceElement> = map { e ->
fun anchor(centre: Float) = when { centre < 1f / 3f -> 0f; centre > 2f / 3f -> 1f; else -> .5f }
val group = IntArray(size) { it }
fun root(i: Int): Int = if (group[i] == i) i else root(group[i]).also { group[i] = it }
for (i in indices) for (j in i + 1 until size) {
val a = this[i]; val b = this[j]
val near = kotlin.math.abs(a.x + a.width / 2 - b.x - b.width / 2) < (a.width + b.width) / 2 * 1.15f &&
kotlin.math.abs(a.y + a.height / 2 - b.y - b.height / 2) < (a.height + b.height) / 2 * 1.15f
if (near) group[root(i)] = root(j)
}
val anchors = indices.groupBy(::root).mapValues { (_, members) ->
anchor(members.map { this[it].x + this[it].width / 2 }.average().toFloat()) to anchor(members.map { this[it].y + this[it].height / 2 }.average().toFloat())
}
return mapIndexed { i, e -> e.scaledAround(factor, anchors.getValue(root(i))) }
}
private fun InputSurfaceElement.scaledAround(factor: Float, anchor: Pair<Float, Float>): InputSurfaceElement {
val e = this
val w = (e.width * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val h = (e.height * factor).coerceIn(InputSurfaceElement.MIN_SIZE, 1f)
val w = (e.width * factor).coerceIn(.03f, 1f)
val h = (e.height * factor).coerceIn(.03f, 1f)
val cx = e.x + e.width / 2
val cy = e.y + e.height / 2
val (ax, ay) = anchor
return e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h),
val ax = anchor(cx)
val ay = anchor(cy)
e.copy(x = (ax + (cx - ax) * factor - w / 2).coerceIn(0f, 1f - w), y = (ay + (cy - ay) * factor - h / 2).coerceIn(0f, 1f - h),
width = w, height = h).bounded()
}
@@ -3,10 +3,6 @@ package com.droiddeck.launcher.input
class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole, val element: InputSurfaceElement) {
private val router = pad.inputRouter
private val route = router?.channel(role, element.control, element = element)
/** The kit's D-pad keeps each direction's own binding, as the separate direction buttons it replaced did. */
private val arms = if (element.id == KitLayout.DPAD_ID && router != null)
listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { router.channel(role, it, element = KitLayout.element("legacy:${it.id}")) }
else emptyList()
private val deck = DeckControls.source(role, routed = true)
private val clickDeck = DeckControls.source(role, routed = true)
private val clickOwner = Any()
@@ -59,15 +55,6 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
fingerDown = down
if (latched) 1f else 0f
} else value
if (arms.isNotEmpty() && route?.action is InputAction.Native) {
val ready = route.update(x, y, touching) != null
val values = listOf(y < -.5f, x > .5f, y > .5f, x < -.5f).map { if (it && ready) 1f else 0f }
val toPad = arms.mapIndexed { i, arm -> arm.update(values[i])?.takeIf { it.isPad }?.let { it to values[i] } }.filterNotNull()
if (toPad.isNotEmpty() || nativePad) writePad(this, null) { state -> state.clear(); for ((t, v) in toPad) state.add(t, v) }
nativePad = toPad.isNotEmpty()
InputTiming.end(timing)
return
}
val target = if (router == null) element.control else route?.update(x, y, touching)
val toPad = target?.isPad == true
val toDeck = target != null && !target.isPad
@@ -88,7 +75,6 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
fun cancel() {
if (closed) return
route?.takeIf { it.action is InputAction.Command }?.release()
arms.filter { it.action is InputAction.Command }.forEach { it.release() }
update(0f)
}
@@ -126,13 +112,13 @@ class InputSurfaceSource(private val pad: PadBridge, private val role: InputRole
closed = true
router?.removeSnapshot(snapshot)
releaseNative(); resetLatch()
route?.close(); arms.forEach { it.close() }; clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close()
route?.close(); clickRoute?.close(); gestureWheel?.close(); gestureRight?.close(); gestureMiddle?.close(); deck.close(); clickDeck.close()
}
fun release() {
if (closed) return
releaseNative(); resetLatch()
route?.release(); arms.forEach { it.release() }; clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release()
route?.release(); clickRoute?.release(); gestureWheel?.release(); gestureRight?.release(); gestureMiddle?.release()
}
}
@@ -1,297 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import android.graphics.RectF
import kotlin.math.max
import kotlin.math.min
/**
* Places a virtual controller's default on-screen controls. Each kit is drawn on a 1600 × 900 reference screen; controls keep
* their distance from the nearest edge, so wider screens spread them apart instead of stretching them. Clusters such as the face
* buttons are placed by their centre so they move as one, and the row along the bottom-left edge always starts after DroidDeck's
* corner button.
*/
object KitLayout {
const val DPAD_ID = "kit:dpad"
const val KEYBOARD_ID = "builtin:keyboard"
/** Whether [id] names one of a kit's own controls rather than a key or control the player added. */
fun isKit(id: String) = id.startsWith("legacy:") || id == DPAD_ID || id == KEYBOARD_ID
internal fun visibleOnOverlay(control: InputControl, rearButtons: Boolean, trackpads: Boolean): Boolean = when (control) {
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> rearButtons
InputControl.LEFT_PAD, InputControl.RIGHT_PAD -> trackpads
else -> true
}
/** The control a kit id stands for in a layout that keeps no kit positions, so bindings saved for it stay valid. */
fun element(id: String): InputSurfaceElement? = when {
id == DPAD_ID -> InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, id, InputElementKind.DPAD)
id == KEYBOARD_ID -> InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, id)
id.startsWith("legacy:") -> InputControl.entries.firstOrNull { "legacy:${it.id}" == id }
?.let { InputSurfaceElement(it, 0f, 0f, .1f, .1f, id, InputElementKind.from(it)) }
else -> null
}
/** The direction buttons the kit's D-pad stands in for; their saved overrides stay with the D-pad. */
val dpadDirectionIds = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT).map { "legacy:${it.id}" }
/** Whether a binding for [id] belongs to a layout made of [elements]. */
fun bindsTo(id: String, elements: List<InputSurfaceElement>) =
elements.any { it.id == id } || id in dpadDirectionIds && elements.any { it.id == DPAD_ID }
/** Every kit control that has a click, across all virtual controllers. */
val clickIds = listOf(InputControl.LS, InputControl.RS, InputControl.LEFT_PAD, InputControl.RIGHT_PAD).map { "legacy:${it.id}" }
private const val REF_W = 1600f
private const val REF_H = 900f
/** The widest pair of side controls on any kit: a larger size never pushes the two halves, or the rows, into each other. */
private const val MIN_SPAN = 1200f
private const val MAX_HEIGHT_MM = 80f
/** The smallest half-size of any kit control in reference units. */
private const val SMALLEST_HALF = 26f
private const val CORNER_DP = 52f
private const val ROW_DP = 60f
private const val BUTTON_DP = 44f
private const val GAP_DP = 8f
private class Spec(val control: InputControl, val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw, val id: String = "legacy:${control.id}",
val kind: InputElementKind = InputElementKind.from(control), val shape: InputButtonShape = InputButtonShape.CIRCLE, val icon: Int = 0, val name: String = control.label,
val ax: Float = cx, val ay: Float = cy)
private fun shoulders() = listOf(
Spec(InputControl.LT, 140f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.LB, 140f, 148f, 88f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.RT, 1460f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.RB, 1460f, 148f, 88f, 30f, shape = InputButtonShape.PILL))
private fun face(cx: Float, cy: Float, r: Float, off: Float) = listOf(
Spec(InputControl.Y, cx, cy - off, r, ax = cx, ay = cy), Spec(InputControl.X, cx - off, cy, r, ax = cx, ay = cy),
Spec(InputControl.B, cx + off, cy, r, ax = cx, ay = cy), Spec(InputControl.A, cx, cy + off, r, ax = cx, ay = cy))
private fun dpad(cx: Float, cy: Float, half: Float) =
Spec(InputControl.LS, cx, cy, half, id = DPAD_ID, kind = InputElementKind.DPAD, shape = InputButtonShape.ROUNDED, name = "D-pad")
private fun keyboard(cx: Float) = Spec(InputControl.A, cx, 848f, 46f, id = KEYBOARD_ID, icon = InputButtonIcons.KEYBOARD, name = "Keyboard")
private fun specs(kit: PadKit): List<Spec> = when {
kit.steam -> shoulders() + listOf(
Spec(InputControl.L4, 30f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.L5, 30f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.R4, 1570f, 470f, 30f, 58f, shape = InputButtonShape.ROUNDED), Spec(InputControl.R5, 1570f, 590f, 30f, 58f, shape = InputButtonShape.ROUNDED),
dpad(220f, 345f, 150f)) + face(1375f, 345f, 58f, 96f) + listOf(
Spec(InputControl.LS, 290f, 640f, 96f), Spec(InputControl.RS, 1310f, 640f, 96f),
Spec(InputControl.LEFT_PAD, 470f, 360f, 88f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1130f, 360f, 88f, shape = InputButtonShape.ROUNDED),
Spec(InputControl.SELECT, 660f, 850f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 850f, 46f, 26f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL),
keyboard(136f))
kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 58f, 96f) + listOf(
Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f),
Spec(InputControl.L3, 430f, 590f, 42f, ax = 565f, ay = 690f), Spec(InputControl.R3, 1170f, 590f, 42f, ax = 1035f, ay = 690f),
Spec(InputControl.SELECT, 640f, 850f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 850f, 50f, 30f, shape = InputButtonShape.PILL),
Spec(InputControl.GUIDE, 800f, 850f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 675f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf(
Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f, ax = 235f, ay = 400f), Spec(InputControl.R3, 1290f, 790f, 42f, ax = 1130f, ay = 690f),
Spec(InputControl.SELECT, 690f, 850f, 38f), Spec(InputControl.GUIDE, 800f, 850f, 46f), Spec(InputControl.START, 910f, 850f, 38f),
Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
}
/** The default controls for [kit] on a [width] × [height] screen. */
fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f,
cutouts: List<Rect> = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true,
addedControls: List<InputSurfaceElement> = emptyList()): List<InputSurfaceElement> {
if (width <= 0 || height <= 0) return emptyList()
// Insets stay as reported unless what's left is too small to keep every control above the minimum element size.
val smallestUnit = InputSurfaceElement.MIN_SIZE * max(width, height) / (2 * SMALLEST_HALF)
fun fit(a: Int, b: Int, side: Int, reference: Float): Pair<Int, Int> {
val first = a.coerceAtLeast(0); val second = b.coerceAtLeast(0)
val room = (side - (smallestUnit * reference).toInt() - 1).coerceAtLeast(0)
return if (first + second <= room) first to second else (first.toLong() * room / (first + second)).toInt() to (second.toLong() * room / (first + second)).toInt()
}
val (left, right) = fit(inset.left, inset.right, width, MIN_SPAN)
val (top, bottom) = fit(inset.top, inset.bottom, height, REF_H)
val safe = Rect(left, top, right, bottom)
if (height > width) return portrait(context, kit, width, height, safe, scale)
.filter { visibleOnOverlay(it.control, rearButtons, trackpads) }
val controls = specs(kit).filter { visibleOnOverlay(it.control, rearButtons, trackpads) }
val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left }
val rightCutouts = cutouts.filter { inset.right > 0 && it.left >= width - inset.right }
if ((leftCutouts.isNotEmpty() || rightCutouts.isNotEmpty()) &&
(left == 0 || leftCutouts.isNotEmpty()) && (right == 0 || rightCutouts.isNotEmpty())) {
val corner = cornerInset(safe, cutouts, height, context.resources.displayMetrics.density)
val fullWidth = landscape(context, kit, width, height, Rect(0, top, 0, bottom), scale, corner, controls)
avoidSideCutouts(fullWidth, leftCutouts, rightCutouts, width, height, addedControls)?.let { return it }
}
return landscape(context, kit, width, height, safe, scale, left, controls)
}
internal fun cornerInset(inset: Rect, cutouts: List<Rect>, height: Int, density: Float): Int {
val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left }
val floor = height - inset.bottom
return if (height <= 0 || leftCutouts.isEmpty() ||
leftCutouts.any { it.top < floor && it.bottom > floor - CORNER_DP * density && it.left < CORNER_DP * density })
inset.left else 0
}
private fun landscape(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float,
cornerInset: Int, controls: List<Spec>): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val unit = (min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale).coerceAtMost(min((w - safe.left - safe.right).coerceAtLeast(1f) / MIN_SPAN, (h - safe.top - safe.bottom).coerceAtLeast(1f) / REF_H))
fun x(ref: Float) = when {
ref < REF_W / 3f -> safe.left + ref * unit
ref > REF_W * 2f / 3f -> w - safe.right - (REF_W - ref) * unit
else -> (w / 2f + (ref - REF_W / 2f) * unit).between(safe.left + ref * unit, w - safe.right - (REF_W - ref) * unit)
}
fun y(ref: Float) = when {
ref < REF_H / 3f -> safe.top + ref * unit
ref > REF_H * 2f / 3f -> h - safe.bottom - (REF_H - ref) * unit
else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit)
}
val density = context.resources.displayMetrics.density
var edge = cornerInset + CORNER_DP * density
val row = controls.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s ->
val hw = s.hw * unit
max(x(s.cx), edge + hw).also { edge = it + hw + GAP_DP * density }
}
return controls.map { s ->
val cx = if (s.cy > REF_H * .88f && s.cx > REF_W / 3f && s.cx < REF_W * 2f / 3f) (w + safe.left - safe.right) / 2f + (s.cx - REF_W / 2f) * unit
else row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit)
val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit
InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, if (s.name == s.control.label) kit.name(s.control) else s.name,
floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded()
}
}
private fun avoidSideCutouts(elements: List<InputSurfaceElement>, leftCutouts: List<Rect>, rightCutouts: List<Rect>,
width: Int, height: Int, addedControls: List<InputSurfaceElement>): List<InputSurfaceElement>? {
fun bounds(e: InputSurfaceElement) = RectF(e.x * width, e.y * height, (e.x + e.width) * width, (e.y + e.height) * height)
val boxes = elements.map(::bounds)
val addedBoxes = addedControls.map(::bounds)
// Move a face-button cross or a stick and its click button together.
val groups = elements.indices.groupBy { index ->
val element = elements[index]
when (element.control) {
InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> if (element.id == KEYBOARD_ID) element.id else "face"
InputControl.L3 -> "legacy:ls"
InputControl.R3 -> "legacy:rs"
else -> element.id
}
}.values
val shifts = FloatArray(elements.size)
val left = leftCutouts.map(::RectF)
val right = rightCutouts.map(::RectF)
val obstacles = left + right
for (group in groups) {
val leftEdge = left.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.maxOfOrNull { it.right }
val rightEdge = right.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.minOfOrNull { it.left }
val shift = when {
leftEdge != null && rightEdge != null -> return null
leftEdge != null -> leftEdge - group.minOf { boxes[it].left } + 1f
rightEdge != null -> rightEdge - group.maxOf { boxes[it].right } - 1f
else -> continue
}
for (index in group) shifts[index] = shift
}
val moved = boxes.mapIndexed { index, box -> RectF(box).apply { offset(shifts[index], 0f) } }
for (i in moved.indices) {
if (moved[i].left < 0f || moved[i].right > width || obstacles.any { RectF.intersects(moved[i], it) }) return null
if (shifts[i] != 0f && addedBoxes.any { RectF.intersects(moved[i], it) }) return null
for (j in 0 until i) {
if (shifts[i] != shifts[j] && RectF.intersects(moved[i], moved[j]) && !RectF.intersects(boxes[i], boxes[j])) return null
}
}
return elements.mapIndexed { index, e -> e.copy(x = e.x + shifts[index] / width).bounded() }
}
/**
* A portrait surface gets the same pad as the panel under the game, in the lower part of the screen, with the keyboard,
* Steam, Quick Access, Start, Select and stick-click buttons in a row along the bottom edge.
*/
private fun portrait(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val density = context.resources.displayMetrics.density
val row = ROW_DP * density
val inner = (w - safe.left - safe.right).coerceAtLeast(1f)
val area = (min(h * .6f, inner * 1.15f) * scale).coerceAtMost(h - safe.top - safe.bottom - row).coerceAtLeast(1f)
val top = h - safe.bottom - row - area
val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true)
.filterNot { it.control == InputControl.SELECT || it.control == InputControl.START }.map { e ->
e.copy(x = (safe.left + e.x * inner) / w, y = (top + e.y * area) / h, width = e.width * inner / w, height = e.height * area / h,
floating = e.kind == InputElementKind.STICK)
}
val specs = specs(kit)
fun spec(control: InputControl, id: String = "legacy:${control.id}") = specs.firstOrNull { it.control == control && it.id == id }
val gap = GAP_DP * density
val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3), spec(InputControl.SELECT))
val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3), spec(InputControl.START))
val start = safe.left + CORNER_DP * density
val span = (w - safe.right - gap - start - gap * (leftRow.size + rightRow.size - 1)).coerceAtLeast(1f)
val size = min(BUTTON_DP * density, span / (leftRow + rightRow).sumOf { (it.hw / it.hh).toDouble() }.toFloat())
val cy = h - safe.bottom - row / 2f
val placed = mutableListOf<InputSurfaceElement>()
fun put(s: Spec, cx: Float) {
val bw = size * s.hw / s.hh
placed += InputSurfaceElement(s.control, (cx - bw / 2) / w, (cy - size / 2) / h, bw / w, size / h, s.id, s.kind,
if (s.name == s.control.label) kit.name(s.control) else s.name, buttonShape = s.shape, icon = s.icon)
}
var left = start
for (s in leftRow) {
val bw = size * s.hw / s.hh
put(s, left + bw / 2); left += bw + gap
}
var right = w - safe.right - gap
for (s in rightRow) {
val bw = size * s.hw / s.hh
put(s, right - bw / 2); right -= bw + gap
}
return pad + placed
}
/** Controls for the panel below the game, in [GamepadGeometry]'s slots. */
fun dock(context: Context, kit: PadKit, width: Int, height: Int, portrait: Boolean, left: InputControl, right: InputControl,
upright: Boolean = false): List<InputSurfaceElement> {
val w = width.toFloat(); val h = height.toFloat()
val boxes = GamepadGeometry.layout(w, h, context.resources.displayMetrics.density, portrait, grips = kit.steam, upright = upright,
trackpads = kit.steam)
val placed = mutableListOf<InputSurfaceElement>()
fun put(control: InputControl, box: GamepadGeometry.Box?, shape: InputButtonShape, id: String = "legacy:${control.id}",
kind: InputElementKind = InputElementKind.from(control), name: String = kit.name(control)) {
val b = box ?: return
placed += InputSurfaceElement(control, b.left / w, b.top / h, b.width / w, b.height / h, id, kind, name, floating = false, buttonShape = shape).bounded()
}
fun square(box: GamepadGeometry.Box?) = box?.let { val side = min(it.width, it.height); GamepadGeometry.Box(it.cx, it.cy, side, side) }
val four = GamepadGeometry.Slot.LEFT_TOUCH in boxes
val leftMain = if (four || !kit.steam && left == InputControl.LEFT_PAD) InputControl.LS else left
val rightMain = if (four || !kit.steam && right == InputControl.RIGHT_PAD) InputControl.RS else right
if (four) {
put(InputControl.LEFT_PAD, boxes[GamepadGeometry.Slot.LEFT_TOUCH], InputButtonShape.ROUNDED)
put(InputControl.RIGHT_PAD, boxes[GamepadGeometry.Slot.RIGHT_TOUCH], InputButtonShape.ROUNDED)
}
put(leftMain, square(boxes[GamepadGeometry.Slot.LEFT_MAIN]), InputButtonShape.CIRCLE)
put(InputControl.LS, square(boxes[GamepadGeometry.Slot.LEFT_SECOND]), InputButtonShape.ROUNDED, DPAD_ID, InputElementKind.DPAD, "D-pad")
put(rightMain, square(boxes[GamepadGeometry.Slot.RIGHT_MAIN]), InputButtonShape.CIRCLE)
square(boxes[GamepadGeometry.Slot.RIGHT_SECOND])?.let { b ->
val r = b.width * .17f; val off = b.width * .3f
listOf(InputControl.Y to (0f to -1f), InputControl.B to (1f to 0f), InputControl.A to (0f to 1f), InputControl.X to (-1f to 0f)).forEach { (c, d) ->
put(c, GamepadGeometry.Box(b.cx + d.first * off, b.cy + d.second * off, 2 * r, 2 * r), InputButtonShape.CIRCLE)
}
}
put(InputControl.LT, boxes[GamepadGeometry.Slot.LEFT_OUTER_SHOULDER], InputButtonShape.PILL)
put(InputControl.LB, boxes[GamepadGeometry.Slot.LEFT_INNER_SHOULDER], InputButtonShape.PILL)
put(InputControl.RB, boxes[GamepadGeometry.Slot.RIGHT_INNER_SHOULDER], InputButtonShape.PILL)
put(InputControl.RT, boxes[GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER], InputButtonShape.PILL)
put(InputControl.SELECT, boxes[GamepadGeometry.Slot.VIEW], InputButtonShape.PILL)
put(InputControl.START, boxes[GamepadGeometry.Slot.MENU], InputButtonShape.PILL)
if (kit.steam) listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4).forEach { (c, slot) -> put(c, boxes[slot], InputButtonShape.ROUNDED) }
return placed
}
private fun cap(context: Context, shortSide: Int): Float {
val metrics = context.resources.displayMetrics
val nominal = metrics.densityDpi.toFloat()
val dpi = metrics.ydpi.takeIf { it > nominal * .6f && it < nominal * 1.6f } ?: nominal
val mm = shortSide / dpi * 25.4f
return min(1f, MAX_HEIGHT_MM / max(mm, 1f))
}
/** The middle band never comes closer to an edge than the edge rows' own reference spacing allows. */
private fun Float.between(low: Float, high: Float) = coerceIn(low, max(low, high))
}
@@ -2,16 +2,12 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sqrt
import kotlin.math.sin
import kotlin.math.*
// Recreates the stock geometry written by schema 14 so its migration can recognise unedited layouts.
internal class LegacyLayoutGeometry(context: Context, private val width: Int, private val height: Int) {
private val safe = Rect()
private val resources = context.resources
internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int, private val safe: Rect = Rect(),
private val scale: Float = 1f) {
private val resources get() = context.resources
private val settings = ControllerPrefs.read(context)
private var fit = 1f
private class Control(val id: String, val group: String, val stick: Int, val radiusDp: Float, val offsetXDp: Float, val offsetYDp: Float) {
var radius = 0f
@@ -45,7 +41,7 @@ internal class LegacyLayoutGeometry(context: Context, private val width: Int, pr
private fun dp(value: Float) = value * resources.displayMetrics.density
private fun scaled(value: Float) = dp(value) * fit
private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit
private fun fitScale(): Float {
val metrics = resources.displayMetrics
@@ -184,22 +180,139 @@ internal class LegacyLayoutGeometry(context: Context, private val width: Int, pr
fit = fitScale()
controls.forEach { it.radius = scaled(it.radiusDp) }
placeAuto(width.toFloat(), height.toFloat())
for ((group, position) in ControllerPrefs.layout(context, width, height)) {
if (group in groups && position.first.isFinite() && position.second.isFinite()) put(group, position.first * width, position.second * height)
}
groups.forEach(::clamp)
val result = controls.map { c ->
val result = controls.filter {
settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton)
}.map { c ->
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
2 * c.halfW / width, 2 * c.halfH / height, hideWhenIdle = c.stick >= 0,
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded()
}.toMutableList()
result += keyboard()
if (settings.keyboardButton) result += keyboard()
return result
}
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
val before = from.elements().associateBy { it.id }
val after = elements().associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
}
}
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
val inset = dp(BUTTONS_ONLY_INSET_DP)
val bottom = height - safe.bottom - inset
val radius = dp(BUTTONS_ONLY_RADIUS_DP)
fun pick(control: InputControl, shown: Boolean) = stored.firstOrNull { it.id == "legacy:${control.id}" }
?: stored.firstOrNull { it.control == control && it.kind == InputElementKind.BUTTON }
?: InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE).takeIf { shown }
return listOfNotNull(
pick(InputControl.GUIDE, settings.steamButton)?.let { circle(it, safe.left + inset, bottom, radius) },
pick(InputControl.QAM, settings.qamButton)?.let { circle(it, width - safe.right - inset, bottom, radius) },
stored.firstOrNull { it.id == KEYBOARD_ID }?.let { circle(it, width / 2f, bottom, dp(KEYBOARD_RADIUS_DP)) },
)
}
fun dock(stored: List<InputSurfaceElement>, portrait: Boolean, grips: Boolean, left: InputControl = InputControl.LS,
right: InputControl = InputControl.RS): List<InputSurfaceElement> {
val boxes = GamepadGeometry.layout(width.toFloat(), height.toFloat(), resources.displayMetrics.density, portrait)
val placed = mutableListOf<InputSurfaceElement>()
fun box(control: InputControl, slot: GamepadGeometry.Slot, shape: InputButtonShape) {
val b = boxes[slot] ?: return
placed += InputSurfaceElement(control, b.left / width, b.top / height, b.width / width, b.height / height,
floating = false, buttonShape = shape).bounded()
}
fun cross(controls: List<InputControl>, slot: GamepadGeometry.Slot) {
val b = boxes[slot] ?: return
val side = min(b.width, b.height)
val spread = side * CROSS_SPREAD
val radius = side * CROSS_RADIUS
controls.zip(listOf(0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f)).forEach { (control, direction) ->
placed += circle(InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE),
b.cx + direction.first * spread, b.cy + direction.second * spread, radius)
}
}
box(left, GamepadGeometry.Slot.LEFT_MAIN, InputButtonShape.CIRCLE)
cross(DPAD_ORDER, GamepadGeometry.Slot.LEFT_SECOND)
box(right, GamepadGeometry.Slot.RIGHT_MAIN, InputButtonShape.CIRCLE)
cross(FACE_ORDER, GamepadGeometry.Slot.RIGHT_SECOND)
box(InputControl.LT, GamepadGeometry.Slot.LEFT_OUTER_SHOULDER, InputButtonShape.PILL)
box(InputControl.LB, GamepadGeometry.Slot.LEFT_INNER_SHOULDER, InputButtonShape.PILL)
box(InputControl.RB, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER, InputButtonShape.PILL)
box(InputControl.RT, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER, InputButtonShape.PILL)
box(InputControl.SELECT, GamepadGeometry.Slot.VIEW, InputButtonShape.PILL)
box(InputControl.START, GamepadGeometry.Slot.MENU, InputButtonShape.PILL)
if (grips) GRIPS.forEach { (control, slot) -> box(control, slot, InputButtonShape.ROUNDED) }
val surfaces = listOf(left, right).filter { it.isTrackpad }
return withGeometry(stored, placed) + placed.filter { p -> (GRIPS.any { it.first == p.control } || p.control in surfaces) && stored.none { it.id == p.id } }
}
private fun circle(e: InputSurfaceElement, cx: Float, cy: Float, radius: Float) =
e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height).bounded()
private fun withGeometry(stored: List<InputSurfaceElement>, placed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = placed.associateBy { it.id }
return stored.mapNotNull { e -> byId[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } }
}
private fun keyboard(): InputSurfaceElement {
val radius = dp(KEYBOARD_RADIUS_DP)
val cx = safe.left + dp(KEYBOARD_X_DP)
val cy = height - safe.bottom - dp(KEYBOARD_Y_DP)
return InputSurfaceElement(InputControl.A, (cx - radius) / width, (cy - radius) / height, 2 * radius / width, 2 * radius / height,
KitLayout.KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded()
KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded()
}
fun restyle(elements: List<InputSurfaceElement>): List<InputSurfaceElement> {
val dpad = elements.filter { it.id == "legacy:${it.control.id}" && it.control in DPAD && it.buttonShape == InputButtonShape.ROUNDED }
val centreX = dpad.map { (it.x + it.width / 2f) * width }.average().toFloat()
val centreY = dpad.map { (it.y + it.height / 2f) * height }.average().toFloat()
val resize = untouchedDpad(dpad, centreX, centreY)
return elements.map { e ->
when {
e.id == KEYBOARD_ID && e.icon == 0 && e.name == "Keyboard" && e.buttonShape == InputButtonShape.ROUNDED &&
e.x == .02f && e.y == .9f && e.width == .12f && e.height == .08f -> keyboard()
e.id == "legacy:${e.control.id}" && e.buttonShape == InputButtonShape.ROUNDED -> {
val round = e.copy(buttonShape = if (e.control.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE)
(if (resize && e.control in DPAD) resizeDpad(round, centreX, centreY) else widenStick(round)).bounded()
}
else -> e
}
}
}
private fun untouchedDpad(dpad: List<InputSurfaceElement>, centreX: Float, centreY: Float): Boolean {
if (dpad.size != DPAD.size) return false
val radius = dpad[0].width * width / 2f
val tolerance = 1.5f
val offset = radius * LEGACY_DPAD_OFFSET_DP / LEGACY_DPAD_RADIUS_DP
return dpad.all { e ->
val old = controls.first { it.id == e.control.id }
val dx = (e.x + e.width / 2f) * width - centreX
val dy = (e.y + e.height / 2f) * height - centreY
abs(e.width * width / 2f - radius) <= tolerance && abs(e.height * height / 2f - radius) <= tolerance &&
abs(dx - offset * sign(old.offsetXDp)) <= tolerance && abs(dy - offset * sign(old.offsetYDp)) <= tolerance
}
}
private fun resizeDpad(e: InputSurfaceElement, centreX: Float, centreY: Float): InputSurfaceElement {
val old = controls.first { it.id == e.control.id }
val radius = e.width * width / 2f * old.radiusDp / LEGACY_DPAD_RADIUS_DP
val cx = centreX + ((e.x + e.width / 2f) * width - centreX) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
val cy = centreY + ((e.y + e.height / 2f) * height - centreY) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height)
}
private fun widenStickPreviously(e: InputSurfaceElement): InputSurfaceElement {
@@ -230,8 +343,20 @@ internal class LegacyLayoutGeometry(context: Context, private val width: Int, pr
const val SHOULDER_HEIGHT = 0.8f
val shoulderIds = setOf("lb", "rb", "lt", "rt")
const val STICK_REACH = 1.25f
const val LEGACY_DPAD_RADIUS_DP = 26f
const val LEGACY_DPAD_OFFSET_DP = 52f
val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
const val KEYBOARD_ID = "builtin:keyboard"
const val KEYBOARD_RADIUS_DP = 18f
const val KEYBOARD_X_DP = 90f
const val KEYBOARD_Y_DP = 34f
const val BUTTONS_ONLY_RADIUS_DP = 30f
const val BUTTONS_ONLY_INSET_DP = 44f
const val CROSS_SPREAD = .30f
const val CROSS_RADIUS = .16f
val DPAD_ORDER = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
val FACE_ORDER = listOf(InputControl.Y, InputControl.B, InputControl.A, InputControl.X)
val GRIPS = listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
}
}
@@ -3,99 +3,103 @@ package com.droiddeck.launcher.input
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Typeface
import android.os.Build
import android.view.Gravity
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.InputSurfaceView
import com.droiddeck.launcher.ui.PadArt
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
/** Why the controls are hidden while the corner button stays. */
enum class Hidden { BY_TAP, BY_CONTROLLER }
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
private var layout: SavedInputLayout? = null
private val safe = Rect()
private var cutouts = emptyList<Rect>()
private var viewWidth = 0
private var viewHeight = 0
private val corner = CornerButton(context)
var hidden: Hidden? = null
private val placements = object : LinkedHashMap<Placement, List<InputSurfaceElement>>(4, .75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Placement, List<InputSurfaceElement>>) = size > PLACEMENT_CACHE
}
private val quickToggle = QuickToggle(context)
var isButtonsOnly = false
private set
var shortcutsOnly = false
var isQuickHidden = false
private set
/** Holding the corner button opens DroidDeck's controller menu. */
var onCornerHold: (() -> Unit)? = null
/** The player tapped the corner button. */
var onCornerTap: ((Hidden?) -> Unit)? = null
val inputSurface: InputSurfaceView get() = surface
var isPinnedOnly = false
private set
val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true
val inputSurface: com.droiddeck.launcher.ui.InputSurfaceView get() = surface
var onTouchMiss: ((MotionEvent) -> Unit)?
get() = surface.onTouchMiss
set(value) { surface.onTouchMiss = value }
init {
addView(surface, LayoutParams(-1, -1))
val size = (CORNER_HIT_DP * resources.displayMetrics.density).toInt()
addView(corner, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
val size = (QUICK_HIT_DP * 2 * resources.displayMetrics.density).toInt()
addView(quickToggle, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
}
fun updateLayout(value: SavedInputLayout?) {
val kit = PadKit.current(context)
if (layout == value && surface.kit == kit) return
if (layout == value) return
releaseAll()
layout = value
surface.kit = kit
render()
}
fun setPresentation(value: Hidden?, shortcuts: Boolean = false) {
if (hidden == value && shortcutsOnly == shortcuts) return
fun setButtonsOnly(enabled: Boolean) {
if (isButtonsOnly == enabled) return
releaseAll()
hidden = value
shortcutsOnly = shortcuts
isButtonsOnly = enabled
isQuickHidden = false
render()
}
fun setQuickHidden(hidden: Boolean) {
if (isButtonsOnly || isQuickHidden == hidden) return
releaseAll()
isQuickHidden = hidden
render()
}
fun setPinnedOnly(enabled: Boolean) {
if (isPinnedOnly == enabled) return
releaseAll()
isPinnedOnly = enabled
render()
}
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
private fun placed(): List<InputSurfaceElement> {
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
return placements.getOrPut(key) {
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock)
}
}
private fun render() {
val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock, cutouts,
rearButtons = SessionPrefs.oscRearButtons(context), trackpads = SessionPrefs.oscTrackpads(context))
val elements = placed()
surface.updateCustomLayout(when {
isPinnedOnly -> elements.filter { it.alwaysShown }
isQuickHidden -> elements.filter { it.id == "builtin:keyboard" || it.alwaysShown }
else -> elements
})
val style = layout?.style ?: InputSurfaceStyle()
val visible = if (hidden == null && !shortcutsOnly) placed else {
val pinned = placed.filter { it.alwaysShown && !style.hides(it) }
if (hidden != null) pinned else pinned + OnScreenLayout.steamShortcuts(viewWidth, viewHeight, safe, resources.displayMetrics.density, pinned)
}
surface.updateCustomLayout(visible)
surface.updateStyle(style)
corner.visibility = if (layout == null || dock != null) GONE else VISIBLE
corner.alpha = (layout?.style?.opacity ?: 100) / 100f
val density = resources.displayMetrics.density
val margin = (CORNER_MARGIN_DP * density).toInt()
val params = corner.layoutParams as LayoutParams
val leftInset = if (dock == null && viewWidth >= viewHeight && layout?.let(OnScreenLayout::generated) == true)
KitLayout.cornerInset(safe, cutouts, viewHeight, density) else safe.left
if (params.leftMargin != leftInset + margin || params.bottomMargin != safe.bottom + margin) {
params.leftMargin = leftInset + margin
params.bottomMargin = safe.bottom + margin
corner.layoutParams = params
}
corner.invalidate()
quickToggle.tint = style.tint
quickToggle.alpha = style.opacity / 100f
quickToggle.visibility = if (isButtonsOnly || isPinnedOnly || layout == null || dock != null) GONE else VISIBLE
quickToggle.invalidate()
}
fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y) ||
corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
fun cornerTakes(x: Float, y: Float) = corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
quickToggle.visibility == VISIBLE && x >= quickToggle.left && x < quickToggle.right && y >= quickToggle.top && y < quickToggle.bottom
fun releaseAll() = surface.releaseInputs()
fun reload() { releaseAll(); surface.kit = PadKit.current(context); render() }
fun reload() { releaseAll(); placements.clear(); render() }
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val w = MeasureSpec.getSize(widthMeasureSpec)
@@ -112,55 +116,59 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
val offset = ((QUICK_CENTER_DP - QUICK_HIT_DP) * resources.displayMetrics.density).toInt()
val params = quickToggle.layoutParams as LayoutParams
val left = (cutout?.safeInsetLeft ?: 0) + offset
val bottom = (cutout?.safeInsetBottom ?: 0) + offset
if (params.leftMargin != left || params.bottomMargin != bottom) {
params.leftMargin = left
params.bottomMargin = bottom
quickToggle.layoutParams = params
}
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
val bounds = cutout?.boundingRects.orEmpty()
if (fresh != safe || bounds != cutouts) {
if (fresh != safe) {
safe.set(fresh)
cutouts = bounds
render()
}
return super.onApplyWindowInsets(insets)
}
private inner class CornerButton(context: Context) : View(context) {
private val art = PadArt(context)
private val badge = Paint(Paint.ANTI_ALIAS_FLAG)
private inner class QuickToggle(context: Context) : View(context) {
var tint: Int? = ControllerPrefs.STEAM_BLUE
private val density = resources.displayMetrics.density
private var armed = false
private var held = false
private val hold = Runnable { if (armed) { held = true; performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } }
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.5f * density }
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
textAlign = Paint.Align.CENTER
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
textSize = 22 * density
}
override fun onDraw(canvas: Canvas) {
val w = width.toFloat(); val h = height.toFloat()
val dimmed = hidden != null && !armed
if (dimmed) canvas.saveLayerAlpha(0f, 0f, w, h, 170)
art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.MARK, armed)
if (dimmed) canvas.restore()
if (hidden == Hidden.BY_CONTROLLER) {
val d = art.density
val r = RectF(w - 15 * d, 3 * d, w - 2 * d, 12 * d)
badge.style = Paint.Style.FILL; badge.color = Color.rgb(0x16, 0x19, 0x1E)
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
badge.style = Paint.Style.STROKE; badge.strokeWidth = 1.3f * d; badge.color = Color.rgb(0xFF, 0xB3, 0x47)
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
}
val x = width / 2f
val y = height / 2f
val radius = QUICK_RADIUS_DP * density
val color = tint
fill.color = if (color != null) InputSurfaceView.shade(color, 190, 0.12f) else (InputSurfaceView.SURFACE and 0x00ffffff) or (190 shl 24)
canvas.drawCircle(x, y, radius, fill)
stroke.color = if (color != null) InputSurfaceView.light(color, 150, 0.25f) else InputSurfaceView.LINE
canvas.drawCircle(x, y, radius, stroke)
text.color = if (color != null) InputSurfaceView.light(color, 210, 0.75f) else InputSurfaceView.TEXT
canvas.drawText(if (isQuickHidden) "+" else "−", x, y + text.textSize * 0.35f, text)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> { armed = true; held = false; postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()); invalidate() }
MotionEvent.ACTION_CANCEL -> { armed = false; removeCallbacks(hold); invalidate() }
MotionEvent.ACTION_DOWN -> armed = true
MotionEvent.ACTION_CANCEL -> armed = false
MotionEvent.ACTION_UP -> {
removeCallbacks(hold)
if (armed && held) post { onCornerHold?.invoke() }
else if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
val next = if (hidden == null) Hidden.BY_TAP else null
setPresentation(next, shortcutsOnly)
onCornerTap?.invoke(next)
setQuickHidden(!isQuickHidden)
}
armed = false
invalidate()
}
}
return true
@@ -168,7 +176,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
}
private companion object {
const val CORNER_HIT_DP = 48f
const val CORNER_MARGIN_DP = 4f
const val QUICK_CENTER_DP = 34f
const val QUICK_HIT_DP = 26f
const val QUICK_RADIUS_DP = 18f
const val PLACEMENT_CACHE = 4
}
}
@@ -2,8 +2,10 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
object OnScreenLayout {
data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) {
@@ -19,66 +21,25 @@ object OnScreenLayout {
}
}
/**
* The built-in gamepad keeps no kit positions until its kit is edited; until then the kit follows the virtual controller and
* the layout stores only the keys and controls the player added on top.
*/
fun generated(layout: SavedInputLayout) = hasBuiltInKit(layout) && layout.elements.none { KitLayout.isKit(it.id) }
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
fun hasBuiltInKit(layout: SavedInputLayout) =
!layout.kitless && (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY)
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null,
cutouts: List<Rect> = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true): List<InputSurfaceElement> {
layout ?: return emptyList()
if (width <= 0 || height <= 0) return layout.elements
if (generated(layout)) {
val kit = PadKit.current(context)
val extras = if (layout.elements.isEmpty()) emptyList() else fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
return (if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right)
else KitLayout.elements(context, kit, width, height, safe, layout.scale, cutouts, rearButtons, trackpads, addedControls = extras)) + extras
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null): List<InputSurfaceElement> {
val stored = layout?.elements ?: return emptyList()
if (width <= 0 || height <= 0) return stored
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val (reference, generated) = reference(context, layout, width, height)
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
val placed = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
else -> generator.regenerate(gamepad)
}
val elements = if (dock == null && hasBuiltInKit(layout)) layout.elements.filter { element ->
!KitLayout.isKit(element.id) || KitLayout.visibleOnOverlay(element.control, rearButtons, trackpads)
} else layout.elements
return fit(elements, aspect(context, layout), 1f, width, height, safe)
}
internal const val STEAM_SHORTCUT_ID = "shortcut:steam"
internal const val QAM_SHORTCUT_ID = "shortcut:qam"
internal fun steamShortcuts(width: Int, height: Int, safe: Rect, density: Float,
pinned: List<InputSurfaceElement> = emptyList()): List<InputSurfaceElement> {
if (width <= 0 || height <= 0) return emptyList()
val size = min(48f * density, (width - safe.left - safe.right - 64f * density) / 2f)
if (size <= 0f || height - safe.bottom - safe.top < size) return emptyList()
val gap = 4f * density
val left = safe.left + 56f * density
val right = width - safe.right - size - gap
val middle = (left + right) / 2f
val pinnedFromBottom = pinned.sortedByDescending { it.y }
fun button(control: InputControl, id: String, leftSide: Boolean): InputSurfaceElement? {
val edge = if (leftSide) left else right
val range = if (leftSide) left..(middle - size / 2f) else (middle + size / 2f)..right
val candidates = listOf(edge) + pinned.map {
if (leftSide) (it.x + it.width) * width + gap else it.x * width - size - gap
}.filter { it in range }.sortedBy { kotlin.math.abs(it - edge) }
for (x in candidates) {
var y = max(safe.top.toFloat(), height - safe.bottom - size - gap)
for (element in pinnedFromBottom) {
if (x >= (element.x + element.width) * width || x + size <= element.x * width) continue
if (y >= (element.y + element.height) * height || y + size <= element.y * height) continue
y = element.y * height - size - gap
}
if (y >= safe.top) return InputSurfaceElement(control, x / width, y / height, size / width, size / height,
id, buttonShape = InputButtonShape.PILL).bounded()
}
return null
}
return listOfNotNull(
button(InputControl.GUIDE, STEAM_SHORTCUT_ID, leftSide = true),
button(InputControl.QAM, QAM_SHORTCUT_ID, leftSide = false),
)
val byId = (placed + others).associateBy { it.id }
return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
@@ -93,23 +54,15 @@ object OnScreenLayout {
val w = width.toFloat()
val h = height.toFloat()
val scale = min(w / referenceWidth, h / referenceHeight)
// A layout shown on a screen of the other orientation keeps its shape: spread by thirds, its clusters would come apart.
val turned = (w > h) != (referenceWidth > referenceHeight)
val blockX = turned && w > referenceWidth * scale * BLOCK_STRETCH
val blockY = turned && h > referenceHeight * scale * BLOCK_STRETCH
return elements.map { e ->
val ew = e.width * referenceWidth * scale
val eh = e.height * referenceHeight * scale
val x = if (blockX) (w + safe.left - safe.right) / 2f + (e.x - .5f) * referenceWidth * scale else anchor(e.x, e.width, referenceWidth, w, scale)
val y = if (blockY) h - safe.bottom - (1f - e.y) * referenceHeight * scale else anchor(e.y, e.height, referenceHeight, h, scale)
val left = x.coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - ew))
val top = y.coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - eh))
val left = anchor(e.x, e.width, referenceWidth, w, scale).coerceIn(safe.left.toFloat(), max(safe.left.toFloat(), w - safe.right - ew))
val top = anchor(e.y, e.height, referenceHeight, h, scale).coerceIn(safe.top.toFloat(), max(safe.top.toFloat(), h - safe.bottom - eh))
e.copy(x = left / w, y = top / h, width = ew / w, height = eh / h).bounded()
}
}
private const val BLOCK_STRETCH = 1.5f
private fun anchor(start: Float, size: Float, reference: Float, actual: Float, scale: Float): Float {
val centre = start + size / 2f
val scaled = size * reference * scale
@@ -120,8 +73,35 @@ object OnScreenLayout {
}
}
private fun aspect(context: Context, layout: SavedInputLayout): Float = layout.aspect.takeIf { it > 0f } ?: run {
val metrics = InputLibraries.primaryDisplay(context).second
max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1).toFloat() / min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
reference(context, layout, width, height).takeIf { it.second }?.first?.let { it.first.toInt() to it.second.toInt() }
private fun reference(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Pair<Float, Float>, Boolean> {
val (display, metrics) = InputLibraries.primaryDisplay(context)
val long = max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val short = min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
val gamepad = layout.elements.filter(::isGamepad)
if (gamepad.any { it.id.startsWith("legacy:") }) {
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f }
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true))) return (w.toFloat() to h.toFloat()) to true
}
}
val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short)
return (aspect to 1f) to false
}
private fun matches(stored: List<InputSurfaceElement>, generated: List<InputSurfaceElement>): Boolean {
val byId = generated.associateBy { it.id }
return stored.all { e ->
val g = byId[e.id] ?: return@all false
abs(e.x - g.x) <= TOLERANCE && abs(e.y - g.y) <= TOLERANCE && abs(e.width - g.width) <= TOLERANCE && abs(e.height - g.height) <= TOLERANCE
}
}
}
@@ -107,8 +107,6 @@ public final class PadBridge {
private volatile Runnable onPlayerInput;
private Runnable onChordInput;
private final java.util.concurrent.atomic.AtomicBoolean playerInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private volatile Runnable onPhysicalInput;
private final java.util.concurrent.atomic.AtomicBoolean physicalInputPosted = new java.util.concurrent.atomic.AtomicBoolean();
private static final long STATS_WINDOW_MS = 10_000;
private int statButtons, statAxes, statOnScreen, statDropped;
@@ -370,20 +368,6 @@ public final class PadBridge {
onPlayerInput = listener;
}
/** Input from a controller the player holds, never from the on-screen controls. */
public void setOnPhysicalInput(Runnable listener) {
onPhysicalInput = listener;
}
private void notePhysicalInput() {
Runnable listener = onPhysicalInput;
if (listener == null || !physicalInputPosted.compareAndSet(false, true)) return;
mainHandler.post(() -> {
physicalInputPosted.set(false);
listener.run();
});
}
public synchronized void setOnChordInput(Runnable listener) {
onChordInput = listener;
}
@@ -449,7 +433,7 @@ public final class PadBridge {
}
noteDevice(device, slot);
if (pressed && event.getRepeatCount() == 0 && !event.isCanceled()) noteChordInput(slot);
if (pressed) { notePlayerInput(); notePhysicalInput(); }
if (pressed) notePlayerInput();
statButtons++;
scheduleStats();
publish(slot);
@@ -537,7 +521,7 @@ public final class PadBridge {
retainStick(slot, side, x, y);
projectSticks(slot);
if (chordStickInput) noteChordInput(slot);
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) { notePlayerInput(); notePhysicalInput(); }
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
publish(slot);
InputTiming.end(timing);
return true;
@@ -579,7 +563,6 @@ public final class PadBridge {
if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f
|| lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) {
notePlayerInput();
notePhysicalInput();
}
publish(slot);
InputTiming.end(timing);
@@ -1,48 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
enum class DpadStyle { CROSS, DISC, ARROWS }
enum class StickCap { RINGED, DISHED, KNURLED }
enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) {
STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true),
DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED),
DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED);
val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER
val playStation get() = this == DUALSHOCK || this == DUALSENSE
fun label(control: InputControl): String = when (control) {
InputControl.LB -> if (xbox) "LB" else "L1"
InputControl.RB -> if (xbox) "RB" else "R1"
InputControl.LT -> if (xbox) "LT" else "L2"
InputControl.RT -> if (xbox) "RT" else "R2"
else -> control.label
}
/** What the player calls [control] on this controller. */
fun name(control: InputControl): String = if (!playStation) label(control) else when (control) {
InputControl.A -> "Cross"
InputControl.B -> "Circle"
InputControl.X -> "Square"
InputControl.Y -> "Triangle"
else -> label(control)
}
companion object {
fun of(type: String) = when (type) {
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
else -> STEAM_DECK
}
fun current(context: Context) = of(SessionPrefs.steamController(context))
}
}
@@ -25,10 +25,7 @@ data class PhysicalInputKey(val device: String, val name: String, val keyCode: I
data class PhysicalInputBinding(val key: PhysicalInputKey, val action: InputAction)
class PhysicalInputBindings(
private val router: InputRouter,
private val onPress: (KeyEvent) -> Unit = {},
) {
class PhysicalInputBindings(private val router: InputRouter) {
private class Entry(val binding: PhysicalInputBinding, val channel: InputRouter.Channel) {
var heldDevice = -1
var suppressed = false
@@ -69,10 +66,7 @@ class PhysicalInputBindings(
if (identity != key.device) continue
entry.heldDevice = event.deviceId
entry.suppressed = event.repeatCount != 0
if (!entry.suppressed) {
entry.channel.update(1f)
onPress(event)
}
if (!entry.suppressed) entry.channel.update(1f)
return true
}
return false
@@ -20,11 +20,7 @@ import java.util.ArrayDeque
import java.util.UUID
@SuppressLint("MissingPermission")
class SteamControllerBle(
private val context: Context,
router: InputRouter? = null,
private val onPhysicalInput: (() -> Unit)? = null,
) {
class SteamControllerBle(private val context: Context, router: InputRouter? = null) {
private val inputLock = router ?: Any()
private var routedInput = router?.let(::TritonInputRouter)
@Volatile private var stopped = false
@@ -43,7 +39,6 @@ class SteamControllerBle(
private var outputSequence = 0L
private var outputWritePending = false
private var featureRead = 0L
private var lastPressedControls = 0
fun start(): Unit = synchronized(inputLock) {
if (stopped || started) return@synchronized
@@ -271,18 +266,12 @@ class SteamControllerBle(
val timing = InputTiming.begin()
FakeInputWriter.writeTritonState(SLOT, reportId, routedInput?.route(data) ?: data)
InputTiming.end(timing)
if (connected && onPhysicalInput != null) {
val pressed = TritonInputRouter.pressedControls(data)
if (pressed and lastPressedControls.inv() != 0) onPhysicalInput()
lastPressedControls = pressed
}
}
private fun release() = synchronized(inputLock) {
if (stopped) return@synchronized
routedInput?.release()
withSlot {
lastPressedControls = 0
FakeInputWriter.writeTritonState(SLOT, if (reportId == 0x47) 0x47 else 0x45, ByteArray(STATE_BYTES))
}
}
@@ -119,7 +119,6 @@ class SteamTouchControls(
private var selectedArm = 0
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val art = com.droiddeck.launcher.ui.PadArt(context)
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; isFakeBoldText = true }
@@ -241,10 +240,7 @@ class SteamTouchControls(
private fun cx(e: Element) = e.x * width
private fun cy(e: Element) = e.y * height
private fun reach(e: Element, x: Float, y: Float): Float {
val dx = (x - cx(e)) / radius(e); val dy = (y - cy(e)) / radiusY(e)
return if (e.type in TRACKPADS) max(abs(dx), abs(dy)) else hypot(dx, dy)
}
private fun reach(e: Element, x: Float, y: Float) = hypot((x - cx(e)) / radius(e), (y - cy(e)) / radiusY(e))
private fun hit(list: List<Element>, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
@@ -285,61 +281,58 @@ class SteamTouchControls(
val r = radius(e)
val pressed = !editing && e.type in pressedTypes()
val alpha = (255 * alphaScale * if (faded) FADED else 1f).toInt().coerceIn(30, 255)
stroke.color = Color.rgb(Color.red(tint), Color.green(tint), Color.blue(tint)); stroke.strokeWidth = lineWidth()
fill.color = Color.argb(217, 230, 233, 236)
if (alpha < 255) canvas.saveLayerAlpha(x - r * 1.5f, y - r * 1.5f, x + r * 1.5f, y + r * 1.5f, alpha)
val ink = Color.argb(alpha, Color.red(tint), Color.green(tint), Color.blue(tint))
stroke.color = if (isSelected) Color.rgb(26, 159, 255) else ink
stroke.strokeWidth = if (isSelected) lineWidth() * 2f else lineWidth()
fill.color = Color.argb((alpha * 0.85f).toInt(), 230, 233, 236)
text.color = ink
text.typeface = android.graphics.Typeface.DEFAULT_BOLD
when (e.type) {
SteamTouchConfig.DPAD -> if (visuals[SteamTouchConfig.DPAD].orEmpty().any { it.binding?.hasIcon == true }) drawDpad(canvas, e, x, y, r) else {
val bits = if (editing) 0L else dpadBits(e)
val held = (if (bits and DPAD_UP != 0L) 1 else 0) or (if (bits and DPAD_RIGHT != 0L) 2 else 0) or
(if (bits and DPAD_DOWN != 0L) 4 else 0) or (if (bits and DPAD_LEFT != 0L) 8 else 0)
canvas.save(); canvas.translate(x - r, y - r)
art.dpad(canvas, 2 * r, 2 * r, PadKit.STEAM_DECK, held, ink = glyphInk())
canvas.restore()
}
SteamTouchConfig.DPAD -> drawDpad(canvas, e, x, y, r)
SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> {
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
var kx = 0f; var ky = 0f
if (f != null) {
canvas.drawCircle(x, y, r, stroke)
val f = fingers.values.firstOrNull { it.element?.type == e.type }
if (f != null && !editing) {
val d = hypot(f.x - x, f.y - y)
val k = if (d > r) r / d else 1f
kx = (f.x - x) * k * .54f; ky = (f.y - y) * k * .54f
val kx = x + (f.x - x) * k
val ky = y + (f.y - y) * k
canvas.drawCircle(kx, ky, r * 0.42f, fill)
}
art.stick(canvas, x, y, r, PadKit.STEAM_DECK, kx, ky, f != null)
}
SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> {
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
canvas.save(); canvas.translate(x - r, y - r)
art.trackpad(canvas, r * 2f, r * 2f, f != null, (f?.x ?: x) - x + r, (f?.y ?: y) - y + r)
canvas.restore()
if (editing) art.text(canvas, context.getString(R.string.deck_surface_trackpad), x, y, r * .3f, Color.argb(128, 255, 255, 255))
val rect = RectF(x - r * 1.3f, y - r * 0.85f, x + r * 1.3f, y + r * 0.85f)
if (pressed) canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, fill)
canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, stroke)
if (editing) {
text.textSize = r * 0.3f
text.color = Color.argb(alpha / 2, 255, 255, 255)
canvas.drawText(context.getString(R.string.deck_surface_trackpad), x, y - (text.descent() + text.ascent()) / 2, text)
}
}
SteamTouchConfig.STEAM -> {
if (isSelected) canvas.drawCircle(x, y, r, stroke)
drawMark(canvas, x, y, r * 0.5f, if (pressed) accent else ink, alpha)
}
SteamTouchConfig.STEAM -> systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.PILL, com.droiddeck.launcher.ui.PadArt.Icon.STEAM, pressed)
SteamTouchConfig.SELECT, SteamTouchConfig.START -> {
val binding = visuals[e.type]?.firstOrNull()?.binding
if (binding?.hasIcon == true) drawFace(canvas, e.type, binding, x, y, r, pressed)
else systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.CHIP,
if (e.type == SteamTouchConfig.START) com.droiddeck.launcher.ui.PadArt.Icon.MENU else com.droiddeck.launcher.ui.PadArt.Icon.VIEW, pressed)
if (binding?.hasIcon == true) {
drawFace(canvas, e.type, binding, x, y, r, alpha, pressed); return
}
val rect = RectF(x - r * 1.08f, y - r * 0.55f, x + r * 1.08f, y + r * 0.55f)
if (pressed) canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, fill)
canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, stroke)
val t = r * 0.26f
val dir = if (e.type == SteamTouchConfig.START) 1f else -1f
val tri = Path().apply {
moveTo(x + dir * t, y); lineTo(x - dir * t * 0.75f, y - t); lineTo(x - dir * t * 0.75f, y + t); close()
}
canvas.drawPath(tri, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (pressed) Color.argb(alpha, 23, 26, 33) else ink })
}
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, pressed)
}
if (alpha < 255) canvas.restore()
if (isSelected) {
stroke.color = accent; stroke.strokeWidth = lineWidth() * 2f
if (isSquare(e.type)) canvas.drawRoundRect(RectF(x - r, y - r, x + r, y + r), r * .3f, r * .3f, stroke) else canvas.drawCircle(x, y, r, stroke)
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, alpha, pressed)
}
}
private fun systemButton(canvas: Canvas, x: Float, y: Float, r: Float, shape: com.droiddeck.launcher.ui.PadArt.Shape,
icon: com.droiddeck.launcher.ui.PadArt.Icon, pressed: Boolean) {
canvas.save(); canvas.translate(x - r * 1.4f, y - r * 1.4f)
art.system(canvas, r * 2.8f, r * 2.8f, shape, icon, pressed, glyphInk())
canvas.restore()
}
/** Glyphs follow the colour picked for Steam touch controls; white keeps the shared artwork's own ink. */
private fun glyphInk() = if (tint != Color.WHITE) tint else com.droiddeck.launcher.ui.PadArt.INK
private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT,
SteamTouchConfig.TRIGGER_LEFT, SteamTouchConfig.TRIGGER_RIGHT, SteamTouchConfig.THUMB, SteamTouchConfig.KEYBOARD,
SteamTouchConfig.PASTE, SteamTouchConfig.MACRO_1_FINGER, SteamTouchConfig.MACRO_2_FINGER) ||
@@ -357,29 +350,53 @@ class SteamTouchControls(
canvas.restore()
}
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float, pressed: Boolean) {
val shape = if (isSquare(type)) art.roundRect(x - r, y - r, x + r, y + r, r * .3f) else art.circle(x, y, r)
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
alpha: Int, pressed: Boolean) {
val square = isSquare(type)
val rect = RectF(x - r, y - r, x + r, y + r)
val corner = r * 0.3f
fun shape(paint: Paint) = if (square) canvas.drawRoundRect(rect, corner, corner, paint) else canvas.drawCircle(x, y, r, paint)
val icon = binding?.icon?.takeIf { it.isNotEmpty() }?.let(::iconOrLoad)
val custom = binding != null && binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
art.glass(canvas, shape, pressed && !custom, if (custom) parseColor(binding!!.background, SteamTouchBindings.DEFAULT_BACKGROUND) else 0x850E1014.toInt())
val ink = if (pressed && !custom) com.droiddeck.launcher.ui.PadArt.ON_ACCENT else glyphInk()
if (icon != null) {
val s = r * 0.62f
if (custom) canvas.drawBitmap(tinted(binding!!.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s), Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
else canvas.drawBitmap(inked(binding!!.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN) })
val custom = binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
if (custom) {
shape(Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = parseColor(binding.background, SteamTouchBindings.DEFAULT_BACKGROUND)
this.alpha = if (pressed) alpha else (alpha * 0.85f).toInt()
})
canvas.drawBitmap(tinted(binding.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { this.alpha = alpha })
} else {
if (pressed) shape(fill)
val ink = if (pressed) Color.argb(alpha, 23, 26, 33) else stroke.color
canvas.drawBitmap(inked(binding.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply {
colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN)
})
}
shape(stroke)
return
}
if (type == SteamTouchConfig.THUMB) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.QAM, ink); return }
if (type == SteamTouchConfig.KEYBOARD) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.KEYBOARD, ink); return }
val shown = label(type)
val size = when {
if (pressed) shape(fill)
shape(stroke)
if (type == SteamTouchConfig.THUMB) { drawDots(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
if (type == SteamTouchConfig.KEYBOARD) { drawKeyboardGlyph(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
val own = label(type)
val shown = own
text.textSize = when {
shown.length <= 1 -> r * 0.9f
shown.length <= 2 -> r * 0.66f
shown.length <= 5 -> r * 0.4f
else -> r * 0.3f
}
art.text(canvas, if (shown.length > 10) shown.take(9) + "…" else shown, x, y, size, ink, r * 1.8f)
text.color = when {
pressed -> Color.argb(alpha, 23, 26, 33)
shown == own -> LABEL_COLORS[type]?.let { Color.argb(alpha, Color.red(it), Color.green(it), Color.blue(it)) } ?: text.color
else -> text.color
}
val line = if (shown.length > 10) shown.take(9) + "…" else shown
canvas.drawText(line, x, y - (text.descent() + text.ascent()) / 2, text)
}
private fun drawDots(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
@@ -387,6 +404,15 @@ class SteamTouchControls(
for (i in -1..1) canvas.drawCircle(x + i * r * 0.3f, y + r * 0.22f, r * 0.08f, p)
}
private fun drawKeyboardGlyph(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = lineWidth() * 0.8f }
val body = RectF(x - r * 0.6f, y - r * 0.34f, x + r * 0.6f, y + r * 0.34f)
canvas.drawRoundRect(body, r * 0.08f, r * 0.08f, p)
val dot = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color }
for (row in 0..1) for (i in 0..5) canvas.drawCircle(body.left + r * 0.15f + i * r * 0.18f, body.top + r * 0.18f + row * r * 0.17f, r * 0.035f, dot)
canvas.drawLine(x - r * 0.3f, body.bottom - r * 0.14f, x + r * 0.3f, body.bottom - r * 0.14f, p)
}
private val iconsLoading = HashSet<String>()
private val inkedIcons = android.util.LruCache<String, android.graphics.Bitmap>(48)
@@ -1452,7 +1478,6 @@ class SteamTouchControls(
var onSaved: () -> Unit = {}
companion object {
private val TRACKPADS = setOf(SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER)
private const val TAG = "SteamTouch"
private const val POLL_MS = 150L
private const val MOVE_REDRAW_MS = 33L
@@ -1494,5 +1519,11 @@ class SteamTouchControls(
put(SteamTouchConfig.PASTE, 0L)
}
private val LABEL_COLORS = mapOf(
SteamTouchConfig.A to Color.rgb(72, 133, 48),
SteamTouchConfig.B to Color.rgb(211, 68, 37),
SteamTouchConfig.X to Color.rgb(23, 60, 184),
SteamTouchConfig.Y to Color.rgb(235, 200, 70),
)
}
}
@@ -63,25 +63,16 @@ class TritonInputRouter(private val router: InputRouter) {
fun release() = synchronized(router) { channels.forEach { it.release() }; last = null }
fun close() = synchronized(router) { release(); channels.forEach { it.close() }; router.removeSnapshot(snapshot) }
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
private fun putBits(data: ByteArray, value: Int) { for (i in 0..3) data[i + 1] = (value ushr (i * 8)).toByte() }
private fun short(data: ByteArray, offset: Int) = ((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
private fun axis(data: ByteArray, offset: Int): Float = short(data, offset).let { it / if (it < 0) 32768f else 32767f }
private fun shortValue(value: Float) = (value * if (value < 0f) 32768f else 32767f).roundToInt().coerceIn(-32768, 32767)
private fun putShort(data: ByteArray, offset: Int, value: Int) { data[offset] = value.toByte(); data[offset + 1] = (value shr 8).toByte() }
companion object {
private const val CONTROL_BITS = 0x0fffffff
internal fun pressedControls(data: ByteArray): Int {
var active = bits(data) and CONTROL_BITS
if ((5..15 step 2).any { kotlin.math.abs(short(data, it)) > 16384 }) active = active or (1 shl 28)
return active
}
private fun bits(data: ByteArray): Int = (data[1].toInt() and 255) or ((data[2].toInt() and 255) shl 8) or
((data[3].toInt() and 255) shl 16) or ((data[4].toInt() and 255) shl 24)
private fun short(data: ByteArray, offset: Int) =
((data[offset].toInt() and 255) or (data[offset + 1].toInt() shl 8)).toShort().toInt()
private fun bit(c: InputControl): Int = when (c) {
InputControl.A -> 0x1; InputControl.B -> 0x2; InputControl.X -> 0x4; InputControl.Y -> 0x8
InputControl.QAM -> 0x10; InputControl.R3 -> 0x20; InputControl.START -> 0x40