mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 06:15:58 +00:00
feat(input): draw on-screen controls per virtual controller with a corner button and a simpler controller page
This commit is contained in:
1 parent
6ed281f78d
commit
0fba656ee2
20 files changed
+1295
-1146
No files matched your search
@@ -0,0 +1,40 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
/** Decides where the on-screen controls go and why they're hidden, from the session's state alone. */
|
||||
object ControlsPresenter {
|
||||
enum class Place { NONE, MAIN, BOTTOM, STEAM }
|
||||
|
||||
data class State(
|
||||
val mode: String,
|
||||
val desktop: Boolean,
|
||||
val virtualPad: Boolean,
|
||||
val covered: Boolean,
|
||||
val controllerInUse: Boolean,
|
||||
val hiddenByTap: Boolean,
|
||||
val steamLayout: Boolean,
|
||||
val bottomScreen: Boolean,
|
||||
)
|
||||
|
||||
data class Plan(val place: Place, val hidden: OnScreenControls.Hidden? = null) {
|
||||
val shown get() = place != Place.NONE && hidden == null
|
||||
}
|
||||
|
||||
fun plan(state: State): Plan = when {
|
||||
state.covered || !state.virtualPad || state.mode == SessionPrefs.OSC_NEVER -> Plan(Place.NONE)
|
||||
state.mode == SessionPrefs.OSC_AUTO && state.desktop -> Plan(Place.NONE)
|
||||
else -> Plan(
|
||||
when {
|
||||
state.steamLayout -> Place.STEAM
|
||||
state.bottomScreen -> Place.BOTTOM
|
||||
else -> Place.MAIN
|
||||
},
|
||||
when {
|
||||
state.hiddenByTap -> OnScreenControls.Hidden.BY_TAP
|
||||
state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse -> OnScreenControls.Hidden.BY_CONTROLLER
|
||||
else -> null
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
/** Which on-screen layout each game uses. Games without a choice use the default profile's main-screen layout. */
|
||||
object GameControls {
|
||||
const val STEAM = "steam"
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("game-controls", Context.MODE_PRIVATE)
|
||||
|
||||
/** The main-screen bindings preset saved for [game], whose layout is the one drawn. */
|
||||
fun bindings(context: Context, game: Long?): String? = game?.let { prefs(context).getString("$it.bindings", null) }
|
||||
|
||||
fun steamLayout(context: Context, game: Long?): Boolean {
|
||||
val p = prefs(context)
|
||||
return if (game != null && p.contains("$game.steam")) p.getBoolean("$game.steam", false) else SessionPrefs.steamTouchLayout(context)
|
||||
}
|
||||
|
||||
fun choose(context: Context, game: Long, bindings: String?, steam: Boolean) {
|
||||
prefs(context).edit().apply { if (bindings == null) remove("$game.bindings") else putString("$game.bindings", bindings) }
|
||||
.putBoolean("$game.steam", steam).apply()
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import org.json.JSONObject
|
||||
import java.util.UUID
|
||||
|
||||
object InputLibraries {
|
||||
private const val VERSION = 14
|
||||
private const val VERSION = 15
|
||||
private const val KEY = "library"
|
||||
private const val RECOVERY = "library-recovery."
|
||||
const val OVERLAY = "builtin.overlay"
|
||||
@@ -29,10 +29,10 @@ object InputLibraries {
|
||||
val version = raw?.let { JSONObject(it).getInt("version") } ?: 0
|
||||
if (version < 5) library = scopeLayouts(upgradeStockLayouts(upgradeOverlay(context, library)))
|
||||
if (version < 11) library = neutralStockLayouts(library)
|
||||
if (version < 10) library = restyleGamepads(context, library)
|
||||
if (version < 12) library = barStockLayouts(library)
|
||||
if (version < 13) library = LegacyScreenKeyMigration.pin(library)
|
||||
if (version < 14) library = deckGamepadSurfaces(context, library)
|
||||
if (version < 15) library = kitGamepads(library)
|
||||
if (version < 6 || !p.contains(LegacyScreenKeyMigration.BACKUP)) {
|
||||
val legacy = LegacyScreenKeyMigration.snapshot(context)
|
||||
if (legacy != null) {
|
||||
@@ -141,11 +141,11 @@ object InputLibraries {
|
||||
fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): Pair<List<InputSurfaceElement>, Float>? {
|
||||
val origin = layout.origin ?: layout.id
|
||||
InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements to it.aspect }
|
||||
if (origin == OVERLAY || origin.startsWith("migrated.layout.")) {
|
||||
if (origin == OVERLAY) {
|
||||
val (surfaceContext, metrics) = primaryDisplay(context)
|
||||
val size = if (origin == OVERLAY) listOf(metrics.widthPixels, metrics.heightPixels)
|
||||
else origin.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
|
||||
return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() to it[0].toFloat() / it[1] }
|
||||
val w = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
|
||||
val h = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
|
||||
return KitLayout.elements(surfaceContext, PadKit.current(context), w, h) to w.toFloat() / h
|
||||
}
|
||||
return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect }
|
||||
}
|
||||
@@ -157,29 +157,13 @@ object InputLibraries {
|
||||
return surfaceContext to DisplayMetrics().also { if (display != null) display.getRealMetrics(it) else it.setTo(context.resources.displayMetrics) }
|
||||
}
|
||||
|
||||
private fun restyleGamepads(context: Context, library: InputLibrary): InputLibrary {
|
||||
if (library.layouts.none { it.id == OVERLAY || it.id.startsWith("migrated.layout.") }) return library
|
||||
val (surfaceContext, metrics) = primaryDisplay(context)
|
||||
return library.copy(layouts = library.layouts.map { layout ->
|
||||
val size = when {
|
||||
layout.id == OVERLAY -> listOf(metrics.widthPixels, metrics.heightPixels)
|
||||
layout.id.startsWith("migrated.layout.") -> layout.id.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() }
|
||||
else -> emptyList()
|
||||
}
|
||||
if (size.size != 2 || size.any { it <= 0 }) layout
|
||||
else layout.copy(elements = LegacyGamepadLayout(surfaceContext, size[0], size[1]).restyle(layout.elements))
|
||||
})
|
||||
}
|
||||
|
||||
private fun upgradeOverlay(context: Context, library: InputLibrary): InputLibrary {
|
||||
if (library.layouts.none { it.template == InputLayoutTemplate.OVERLAY }) return library
|
||||
val (surfaceContext, metrics) = primaryDisplay(context)
|
||||
val settings = ControllerPrefs.read(context)
|
||||
val elements = LegacyGamepadLayout(surfaceContext, metrics.widthPixels.coerceAtLeast(1), metrics.heightPixels.coerceAtLeast(1)).elements()
|
||||
val style = InputSurfaceStyle(settings.tint, settings.opacity)
|
||||
val elements = emptyList<InputSurfaceElement>()
|
||||
val style = InputSurfaceStyle(opacity = settings.opacity)
|
||||
val replacements = library.layouts.filter { it.template == InputLayoutTemplate.OVERLAY }.associate { old ->
|
||||
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style,
|
||||
aspect = (metrics.widthPixels.coerceAtLeast(1).toFloat() / metrics.heightPixels.coerceAtLeast(1)).coerceIn(.05f, 20f))
|
||||
old.id to old.copy(name = "Gamepad", elements = elements, template = InputLayoutTemplate.CUSTOM, style = style)
|
||||
}
|
||||
var result = library.copy(layouts = library.layouts.map { replacements[it.id] ?: it })
|
||||
val migrated = mutableMapOf<Pair<String, String>, String>()
|
||||
@@ -201,15 +185,6 @@ object InputLibraries {
|
||||
}
|
||||
val oldBindings = migrated.keys.map { it.first }.toSet()
|
||||
result = result.copy(bindings = result.bindings.filter { it.id !in oldBindings || result.usersOfBindings(it.id).isNotEmpty() })
|
||||
// Older editor layouts were resolution-specific. Keep each as a selectable saved layout.
|
||||
for (key in ControllerPrefs.prefs(context).all.keys.filter { it.startsWith("layout.") }.sorted()) {
|
||||
val size = key.removePrefix("layout.").split('x').mapNotNull { it.toIntOrNull() }
|
||||
if (size.size != 2 || size.any { it <= 0 } || result.layouts.size >= 128) continue
|
||||
if (size[0] == metrics.widthPixels && size[1] == metrics.heightPixels) continue
|
||||
val id = "migrated.$key"
|
||||
if (result.layouts.none { it.id == id }) result = result.withLayout(SavedInputLayout(id, "Gamepad ${size[0]} × ${size[1]}",
|
||||
LegacyGamepadLayout(surfaceContext, size[0], size[1]).elements(), style = style, aspect = (size[0].toFloat() / size[1]).coerceIn(.05f, 20f)))
|
||||
}
|
||||
return result.validate()
|
||||
}
|
||||
|
||||
@@ -275,6 +250,17 @@ object InputLibraries {
|
||||
return library.withLayout(saved.copy(elements = InputStockLayouts.gamepad(leftPad, rightStick))).validate()
|
||||
}
|
||||
|
||||
/** Gamepads saved by the old editor follow the virtual controller's kit again; their positions don't map onto the new controls. */
|
||||
private fun kitGamepads(library: InputLibrary): InputLibrary {
|
||||
var result = library
|
||||
for (layout in library.layouts) {
|
||||
val origin = layout.origin ?: layout.id
|
||||
if (origin != OVERLAY && !origin.startsWith("migrated.layout.")) continue
|
||||
result = result.withLayout(layout.copy(elements = emptyList(), origin = if (layout.id == OVERLAY) null else OVERLAY, aspect = 0f, scale = 1f))
|
||||
}
|
||||
return result.validate()
|
||||
}
|
||||
|
||||
private fun migrationBindingId(library: InputLibrary, binding: String, layout: String): String {
|
||||
val seed = JSONArray(listOf(binding, layout)).toString().toByteArray(Charsets.UTF_8)
|
||||
val base = "migrated.bindings." + UUID.nameUUIDFromBytes(seed)
|
||||
|
||||
@@ -49,7 +49,7 @@ data class SavedInputBindings(
|
||||
|
||||
fun action(element: InputSurfaceElement) = elements[element.id]
|
||||
?: if (element.id == "legacy:${element.control.id}") controls[element.control] ?: InputAction.Native()
|
||||
else InputAction.Disabled
|
||||
else defaultElementAction(element.id)
|
||||
|
||||
fun clickAction(element: InputSurfaceElement) = clicks[element.id]
|
||||
?: defaultElementClick(element, action(element)) { controls[it] ?: InputAction.Native() }
|
||||
|
||||
@@ -48,7 +48,7 @@ data class InputProfile(
|
||||
copy(bindings = bindings + (role to (bindings[role].orEmpty() + (control to action))))
|
||||
|
||||
fun elementAction(role: InputRole, id: String, control: InputControl): InputAction =
|
||||
elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else InputAction.Disabled
|
||||
elements[role]?.get(id) ?: if (id == "legacy:${control.id}") action(role, control) else defaultElementAction(id)
|
||||
|
||||
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
|
||||
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
|
||||
@@ -115,3 +115,10 @@ internal fun InputAction.validFor(control: InputControl): Boolean = when (this)
|
||||
is InputAction.Scroll -> control.dimensions == 2 && speed.isFinite() && speed in 1f..60f
|
||||
else -> true
|
||||
}
|
||||
|
||||
/** What an on-screen element with no saved action does: kit controls press their own button, everything else is unassigned. */
|
||||
internal fun defaultElementAction(id: String): InputAction = when (id) {
|
||||
KitLayout.DPAD_ID -> InputAction.Native()
|
||||
KitLayout.KEYBOARD_ID -> InputAction.Command(InputCommand.KEYBOARD)
|
||||
else -> InputAction.Disabled
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Rect
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
/**
|
||||
* Places a virtual controller's default on-screen controls. Each kit is drawn on a 1600 × 900 reference screen; controls keep
|
||||
* their distance from the nearest edge, so wider screens spread them apart instead of stretching them.
|
||||
*/
|
||||
object KitLayout {
|
||||
const val DPAD_ID = "kit:dpad"
|
||||
const val KEYBOARD_ID = "builtin:keyboard"
|
||||
private const val REF_W = 1600f
|
||||
private const val REF_H = 900f
|
||||
private const val MAX_HEIGHT_MM = 80f
|
||||
|
||||
private class Spec(val control: InputControl, val cx: Float, val cy: Float, val hw: Float, val hh: Float = hw, val id: String = "legacy:${control.id}",
|
||||
val kind: InputElementKind = InputElementKind.from(control), val shape: InputButtonShape = InputButtonShape.CIRCLE, val icon: Int = 0, val name: String = control.label)
|
||||
|
||||
private fun shoulders() = listOf(
|
||||
Spec(InputControl.LT, 140f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.LB, 140f, 148f, 88f, 28f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.RT, 1460f, 66f, 88f, 34f, shape = InputButtonShape.PILL), Spec(InputControl.RB, 1460f, 148f, 88f, 28f, shape = InputButtonShape.PILL))
|
||||
|
||||
private fun face(cx: Float, cy: Float, r: Float, off: Float) = listOf(
|
||||
Spec(InputControl.Y, cx, cy - off, r), Spec(InputControl.X, cx - off, cy, r), Spec(InputControl.B, cx + off, cy, r), Spec(InputControl.A, cx, cy + off, r))
|
||||
|
||||
private fun dpad(cx: Float, cy: Float, half: Float) =
|
||||
Spec(InputControl.LS, cx, cy, half, id = DPAD_ID, kind = InputElementKind.DPAD, shape = InputButtonShape.ROUNDED, name = "D-pad")
|
||||
|
||||
private fun keyboard(cx: Float) = Spec(InputControl.A, cx, 848f, 46f, id = KEYBOARD_ID, icon = InputButtonIcons.KEYBOARD, name = "Keyboard")
|
||||
|
||||
private fun specs(kit: PadKit): List<Spec> = when {
|
||||
kit.steam -> shoulders() + listOf(
|
||||
Spec(InputControl.L4, 30f, 470f, 30f, 62f, shape = InputButtonShape.ROUNDED), Spec(InputControl.L5, 30f, 590f, 30f, 62f, shape = InputButtonShape.ROUNDED),
|
||||
Spec(InputControl.R4, 1570f, 470f, 30f, 62f, shape = InputButtonShape.ROUNDED), Spec(InputControl.R5, 1570f, 590f, 30f, 62f, shape = InputButtonShape.ROUNDED),
|
||||
dpad(215f, 330f, 100f)) + face(1385f, 330f, 50f, 82f) + listOf(
|
||||
Spec(InputControl.LS, 290f, 610f, 96f), Spec(InputControl.RS, 1310f, 610f, 96f),
|
||||
Spec(InputControl.LEFT_PAD, 480f, 345f, 95f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1120f, 345f, 95f, shape = InputButtonShape.ROUNDED),
|
||||
Spec(InputControl.SELECT, 660f, 150f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 150f, 46f, 26f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL),
|
||||
keyboard(136f))
|
||||
kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 56f, 92f) + listOf(
|
||||
Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f),
|
||||
Spec(InputControl.L3, 420f, 790f, 42f), Spec(InputControl.R3, 1180f, 790f, 42f),
|
||||
Spec(InputControl.SELECT, 640f, 150f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 150f, 50f, 30f, shape = InputButtonShape.PILL),
|
||||
Spec(InputControl.GUIDE, 800f, 250f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
|
||||
else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 690f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf(
|
||||
Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f), Spec(InputControl.R3, 1290f, 790f, 42f),
|
||||
Spec(InputControl.SELECT, 690f, 162f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 162f, 38f),
|
||||
Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f))
|
||||
}
|
||||
|
||||
/** The default controls for [kit] on a [width] × [height] screen. */
|
||||
fun elements(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect = Rect(), scale: Float = 1f): List<InputSurfaceElement> {
|
||||
if (width <= 0 || height <= 0) return emptyList()
|
||||
val w = width.toFloat(); val h = height.toFloat()
|
||||
val unit = min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale
|
||||
fun x(ref: Float) = when {
|
||||
ref < REF_W / 3f -> safe.left + ref * unit
|
||||
ref > REF_W * 2f / 3f -> w - safe.right - (REF_W - ref) * unit
|
||||
else -> w / 2f + (ref - REF_W / 2f) * unit
|
||||
}
|
||||
fun y(ref: Float) = when {
|
||||
ref < REF_H / 3f -> safe.top + ref * unit
|
||||
ref > REF_H * 2f / 3f -> h - safe.bottom - (REF_H - ref) * unit
|
||||
else -> h / 2f + (ref - REF_H / 2f) * unit
|
||||
}
|
||||
return specs(kit).map { s ->
|
||||
val cx = x(s.cx); val cy = y(s.cy); val hw = s.hw * unit; val hh = s.hh * unit
|
||||
InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, s.name,
|
||||
floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded()
|
||||
}
|
||||
}
|
||||
|
||||
/** Controls for the panel below the game, in [GamepadGeometry]'s slots. */
|
||||
fun dock(context: Context, kit: PadKit, width: Int, height: Int, portrait: Boolean, left: InputControl, right: InputControl): List<InputSurfaceElement> {
|
||||
val w = width.toFloat(); val h = height.toFloat()
|
||||
val boxes = GamepadGeometry.layout(w, h, context.resources.displayMetrics.density, portrait)
|
||||
val placed = mutableListOf<InputSurfaceElement>()
|
||||
fun put(control: InputControl, box: GamepadGeometry.Box?, shape: InputButtonShape, id: String = "legacy:${control.id}",
|
||||
kind: InputElementKind = InputElementKind.from(control), name: String = control.label) {
|
||||
val b = box ?: return
|
||||
placed += InputSurfaceElement(control, b.left / w, b.top / h, b.width / w, b.height / h, id, kind, name, floating = false, buttonShape = shape).bounded()
|
||||
}
|
||||
fun square(box: GamepadGeometry.Box?) = box?.let { val side = min(it.width, it.height); GamepadGeometry.Box(it.cx, it.cy, side, side) }
|
||||
put(left, square(boxes[GamepadGeometry.Slot.LEFT_MAIN]), InputButtonShape.CIRCLE)
|
||||
put(InputControl.LS, square(boxes[GamepadGeometry.Slot.LEFT_SECOND]), InputButtonShape.ROUNDED, DPAD_ID, InputElementKind.DPAD, "D-pad")
|
||||
put(right, square(boxes[GamepadGeometry.Slot.RIGHT_MAIN]), InputButtonShape.CIRCLE)
|
||||
square(boxes[GamepadGeometry.Slot.RIGHT_SECOND])?.let { b ->
|
||||
val r = b.width * .17f; val off = b.width * .3f
|
||||
listOf(InputControl.Y to (0f to -1f), InputControl.B to (1f to 0f), InputControl.A to (0f to 1f), InputControl.X to (-1f to 0f)).forEach { (c, d) ->
|
||||
put(c, GamepadGeometry.Box(b.cx + d.first * off, b.cy + d.second * off, 2 * r, 2 * r), InputButtonShape.CIRCLE)
|
||||
}
|
||||
}
|
||||
put(InputControl.LT, boxes[GamepadGeometry.Slot.LEFT_OUTER_SHOULDER], InputButtonShape.PILL)
|
||||
put(InputControl.LB, boxes[GamepadGeometry.Slot.LEFT_INNER_SHOULDER], InputButtonShape.PILL)
|
||||
put(InputControl.RB, boxes[GamepadGeometry.Slot.RIGHT_INNER_SHOULDER], InputButtonShape.PILL)
|
||||
put(InputControl.RT, boxes[GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER], InputButtonShape.PILL)
|
||||
put(InputControl.SELECT, boxes[GamepadGeometry.Slot.VIEW], InputButtonShape.PILL)
|
||||
put(InputControl.START, boxes[GamepadGeometry.Slot.MENU], InputButtonShape.PILL)
|
||||
if (kit.steam) listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
|
||||
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4).forEach { (c, slot) -> put(c, boxes[slot], InputButtonShape.ROUNDED) }
|
||||
return placed
|
||||
}
|
||||
|
||||
private fun cap(context: Context, shortSide: Int): Float {
|
||||
val metrics = context.resources.displayMetrics
|
||||
val nominal = metrics.densityDpi.toFloat()
|
||||
val dpi = metrics.ydpi.takeIf { it > nominal * .6f && it < nominal * 1.6f } ?: nominal
|
||||
val mm = shortSide / dpi * 25.4f
|
||||
return min(1f, MAX_HEIGHT_MM / max(mm, 1f))
|
||||
}
|
||||
}
|
||||
@@ -1,362 +0,0 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Rect
|
||||
import kotlin.math.*
|
||||
|
||||
internal class LegacyGamepadLayout(private val context: Context, private val width: Int, private val height: Int, private val safe: Rect = Rect(),
|
||||
private val scale: Float = 1f) {
|
||||
private val resources get() = context.resources
|
||||
private val settings = ControllerPrefs.read(context)
|
||||
private var fit = 1f
|
||||
private class Control(val id: String, val group: String, val stick: Int, val radiusDp: Float, val offsetXDp: Float, val offsetYDp: Float) {
|
||||
var radius = 0f
|
||||
var cx = 0f
|
||||
var cy = 0f
|
||||
val halfW get() = if (id in shoulderIds) radius * SHOULDER_WIDTH else radius
|
||||
val halfH get() = if (id in shoulderIds) radius * SHOULDER_HEIGHT else radius
|
||||
}
|
||||
private val controls = listOf(
|
||||
Control("up", "dpad", -1, 30f, 0f, -50f),
|
||||
Control("right", "dpad", -1, 30f, 50f, 0f),
|
||||
Control("down", "dpad", -1, 30f, 0f, 50f),
|
||||
Control("left", "dpad", -1, 30f, -50f, 0f),
|
||||
Control("ls", "ls", 0, 48f, 0f, 0f),
|
||||
Control("rs", "rs", 1, 48f, 0f, 0f),
|
||||
Control("a", "face", -1, 30f, 0f, 50f),
|
||||
Control("b", "face", -1, 30f, 50f, 0f),
|
||||
Control("x", "face", -1, 30f, -50f, 0f),
|
||||
Control("y", "face", -1, 30f, 0f, -50f),
|
||||
Control("lb", "lb", -1, 24f, 0f, 0f),
|
||||
Control("rb", "rb", -1, 24f, 0f, 0f),
|
||||
Control("lt", "lt", -1, 24f, 0f, 0f),
|
||||
Control("rt", "rt", -1, 24f, 0f, 0f),
|
||||
Control("select", "select", -1, 20f, 0f, 0f),
|
||||
Control("start", "start", -1, 20f, 0f, 0f),
|
||||
Control("guide", "guide", -1, 22f, 0f, 0f),
|
||||
Control("qam", "qam", -1, 22f, 0f, 0f),
|
||||
)
|
||||
|
||||
private val groups = controls.map { it.group }.distinct()
|
||||
|
||||
private fun dp(value: Float) = value * resources.displayMetrics.density
|
||||
|
||||
private fun scaled(value: Float) = dp(value) * settings.size / 100f * scale * fit
|
||||
|
||||
private fun fitScale(): Float {
|
||||
val metrics = resources.displayMetrics
|
||||
val heightMm = (height - safe.top - safe.bottom) / pxPerMm(metrics.ydpi)
|
||||
val faceMm = dp(60f) / pxPerMm(metrics.xdpi)
|
||||
val floor = (MIN_FACE_MM / faceMm).coerceAtMost(1f)
|
||||
return (heightMm / FULL_SIZE_HEIGHT_MM).coerceIn(floor, 1f)
|
||||
}
|
||||
|
||||
private fun pxPerMm(dpi: Float): Float {
|
||||
val nominal = resources.displayMetrics.densityDpi.toFloat()
|
||||
return (if (dpi > nominal * 0.6f && dpi < nominal * 1.6f) dpi else nominal) / 25.4f
|
||||
}
|
||||
|
||||
private fun placeAuto(w: Float, h: Float) {
|
||||
val metrics = resources.displayMetrics
|
||||
val mmX = pxPerMm(metrics.xdpi)
|
||||
val mmY = pxPerMm(metrics.ydpi)
|
||||
val usableW = w - safe.left - safe.right
|
||||
val usableH = h - safe.top - safe.bottom
|
||||
val inboard = (0.17f * usableW / mmX).coerceIn(24f, 40f) * mmX
|
||||
val lift = (0.285f * usableH / mmY).coerceIn(22f, 45f) * mmY
|
||||
val gap = dp(12f)
|
||||
val floor = BOTTOM_MARGIN_MM * mmY
|
||||
val drop = max(drop("dpad", "ls", gap), drop("rs", "face", gap))
|
||||
val restY = min(h - safe.bottom - lift, h - safe.bottom - floor - drop)
|
||||
put("ls", safe.left + inboard, restY)
|
||||
put("face", w - safe.right - inboard, restY)
|
||||
besideBelow("dpad", "ls", 1f, gap, floor)
|
||||
besideBelow("rs", "face", -1f, gap, floor)
|
||||
val phone = usableH / mmY < PHONE_MAX_HEIGHT_MM
|
||||
val shoulderY = if (phone) safe.top + floor + halfH("lb")
|
||||
else min(centre("ls").second - extent("ls"), centre("face").second - extent("face")) - gap - halfH("lb")
|
||||
shoulders("ls", "lb", "lt", 1f, gap, shoulderY)
|
||||
shoulders("face", "rb", "rt", -1f, gap, shoulderY)
|
||||
val bottom = h - safe.bottom - floor - extent("guide")
|
||||
val spread = extent("guide") + gap / 2f
|
||||
put("guide", w / 2f - spread, bottom)
|
||||
put("qam", w / 2f + spread, bottom)
|
||||
val inner = max(centre("dpad").first + extent("dpad"), w - centre("rs").first + extent("rs")) + gap + extent("select")
|
||||
put("select", inner, restY)
|
||||
put("start", w - inner, restY)
|
||||
if (phone) {
|
||||
val top = max(centre("lb").first + extent("lb"), w - centre("rb").first + extent("rb")) + gap * 2.5f + extent("select")
|
||||
put("select", top, shoulderY)
|
||||
put("start", w - top, shoulderY)
|
||||
}
|
||||
if (crowded("select", gap) || crowded("start", gap)) {
|
||||
above("select", "dpad", gap)
|
||||
val (sx, sy) = centre("select")
|
||||
put("start", w - sx, sy)
|
||||
if (crowded("start", gap)) above("start", "rs", gap)
|
||||
}
|
||||
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
|
||||
val row = centre("select").second
|
||||
put("guide", w / 2f - spread, row)
|
||||
put("qam", w / 2f + spread, row)
|
||||
if (crowded("guide", gap, gap, "qam") || crowded("qam", gap, gap, "guide")) {
|
||||
val top = safe.top + dp(8f) + extent("guide")
|
||||
put("guide", w / 2f - spread, top)
|
||||
put("qam", w / 2f + spread, top)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun drop(group: String, anchor: String, gap: Float): Float =
|
||||
(extent(anchor) + extent(group) + gap) * sin(Math.toRadians(DROP_DEGREES)).toFloat() + extent(group)
|
||||
|
||||
private fun besideBelow(group: String, anchor: String, inward: Float, gap: Float, margin: Float) {
|
||||
val (ax, ay) = centre(anchor)
|
||||
val reach = extent(anchor) + extent(group) + gap
|
||||
val floor = height - safe.bottom - margin - extent(group)
|
||||
val dy = min(reach * sin(Math.toRadians(DROP_DEGREES)).toFloat(), floor - ay)
|
||||
val dx = sqrt(max(0f, reach * reach - dy * dy))
|
||||
put(group, ax + inward * dx, ay + dy)
|
||||
}
|
||||
|
||||
private fun shoulders(anchor: String, bumper: String, trigger: String, inward: Float, gap: Float, y: Float) {
|
||||
val (ax, _) = centre(anchor)
|
||||
val spread = extent(bumper) + gap / 2f
|
||||
put(bumper, ax + inward * spread, y)
|
||||
put(trigger, ax - inward * spread, y)
|
||||
}
|
||||
|
||||
private fun above(group: String, anchor: String, gap: Float) {
|
||||
val (ax, ay) = centre(anchor)
|
||||
put(group, ax, ay - extent(anchor) - gap - extent(group))
|
||||
}
|
||||
|
||||
private fun crowded(group: String, gap: Float, space: Float = gap / 2f, except: String? = null): Boolean {
|
||||
val (x, y) = centre(group)
|
||||
return groups.any { other ->
|
||||
if (other == group || other == except) return@any false
|
||||
val (ox, oy) = centre(other)
|
||||
val dx = x - ox
|
||||
val dy = y - oy
|
||||
sqrt(dx * dx + dy * dy) < extent(group) + extent(other) + space
|
||||
}
|
||||
}
|
||||
|
||||
private fun members(group: String) = controls.filter { it.group == group }
|
||||
|
||||
private fun centre(group: String): Pair<Float, Float> {
|
||||
val first = members(group).first()
|
||||
return (first.cx - scaled(first.offsetXDp)) to (first.cy - scaled(first.offsetYDp))
|
||||
}
|
||||
|
||||
private fun extent(group: String): Float = members(group).maxOf { control ->
|
||||
sqrt(scaled(control.offsetXDp).let { it * it } + scaled(control.offsetYDp).let { it * it }) + control.halfW
|
||||
}
|
||||
|
||||
private fun halfH(group: String): Float = members(group).maxOf { abs(scaled(it.offsetYDp)) + it.halfH }
|
||||
|
||||
private fun put(group: String, x: Float, y: Float) {
|
||||
for (control in members(group)) {
|
||||
control.cx = x + scaled(control.offsetXDp)
|
||||
control.cy = y + scaled(control.offsetYDp)
|
||||
}
|
||||
}
|
||||
|
||||
private fun clamp(group: String) {
|
||||
val list = members(group)
|
||||
val margin = dp(4f)
|
||||
val minX = list.minOf { it.cx - it.halfW } - safe.left - margin
|
||||
val maxX = list.maxOf { it.cx + it.halfW } - (width - safe.right - margin)
|
||||
val minY = list.minOf { it.cy - it.halfH } - safe.top - margin
|
||||
val maxY = list.maxOf { it.cy + it.halfH } - (height - safe.bottom - margin)
|
||||
val dx = if (minX < 0) -minX else if (maxX > 0) -maxX else 0f
|
||||
val dy = if (minY < 0) -minY else if (maxY > 0) -maxY else 0f
|
||||
if (dx == 0f && dy == 0f) return
|
||||
for (control in list) { control.cx += dx; control.cy += dy }
|
||||
}
|
||||
|
||||
|
||||
fun elements(previousStickGeometry: Boolean = false): List<InputSurfaceElement> {
|
||||
fit = fitScale()
|
||||
controls.forEach { it.radius = scaled(it.radiusDp) }
|
||||
placeAuto(width.toFloat(), height.toFloat())
|
||||
for ((group, position) in ControllerPrefs.layout(context, width, height)) {
|
||||
if (group in groups && position.first.isFinite() && position.second.isFinite()) put(group, position.first * width, position.second * height)
|
||||
}
|
||||
groups.forEach(::clamp)
|
||||
val result = controls.filter {
|
||||
settings.mapping[it.id] != ControllerPrefs.OFF && (it.id != "guide" || settings.steamButton) && (it.id != "qam" || settings.qamButton)
|
||||
}.map { c ->
|
||||
InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height,
|
||||
2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks,
|
||||
buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded()
|
||||
}.toMutableList()
|
||||
if (settings.keyboardButton) result += keyboard()
|
||||
return result
|
||||
}
|
||||
|
||||
fun regenerate(stored: List<InputSurfaceElement>): List<InputSurfaceElement> = withGeometry(stored, elements())
|
||||
|
||||
fun rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> {
|
||||
val before = from.elements().associateBy { it.id }
|
||||
val after = elements().associateBy { it.id }
|
||||
return stored.map { e ->
|
||||
val b = before[e.id] ?: return@map e
|
||||
val a = after[e.id] ?: return@map e
|
||||
val w = (a.width * e.width / b.width).coerceIn(.03f, 1f)
|
||||
val h = (a.height * e.height / b.height).coerceIn(.03f, 1f)
|
||||
val cx = a.x + a.width / 2 + (e.x + e.width / 2 - b.x - b.width / 2)
|
||||
val cy = a.y + a.height / 2 + (e.y + e.height / 2 - b.y - b.height / 2)
|
||||
e.copy(x = (cx - w / 2).coerceIn(0f, 1f - w), y = (cy - h / 2).coerceIn(0f, 1f - h), width = w, height = h).bounded()
|
||||
}
|
||||
}
|
||||
|
||||
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
||||
val inset = dp(BUTTONS_ONLY_INSET_DP)
|
||||
val bottom = height - safe.bottom - inset
|
||||
val radius = dp(BUTTONS_ONLY_RADIUS_DP)
|
||||
fun pick(control: InputControl, shown: Boolean) = stored.firstOrNull { it.id == "legacy:${control.id}" }
|
||||
?: stored.firstOrNull { it.control == control && it.kind == InputElementKind.BUTTON }
|
||||
?: InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE).takeIf { shown }
|
||||
return listOfNotNull(
|
||||
pick(InputControl.GUIDE, settings.steamButton)?.let { circle(it, safe.left + inset, bottom, radius) },
|
||||
pick(InputControl.QAM, settings.qamButton)?.let { circle(it, width - safe.right - inset, bottom, radius) },
|
||||
stored.firstOrNull { it.id == KEYBOARD_ID }?.let { circle(it, width / 2f, bottom, dp(KEYBOARD_RADIUS_DP)) },
|
||||
)
|
||||
}
|
||||
|
||||
fun dock(stored: List<InputSurfaceElement>, portrait: Boolean, grips: Boolean, left: InputControl = InputControl.LS,
|
||||
right: InputControl = InputControl.RS): List<InputSurfaceElement> {
|
||||
val boxes = GamepadGeometry.layout(width.toFloat(), height.toFloat(), resources.displayMetrics.density, portrait)
|
||||
val placed = mutableListOf<InputSurfaceElement>()
|
||||
fun box(control: InputControl, slot: GamepadGeometry.Slot, shape: InputButtonShape) {
|
||||
val b = boxes[slot] ?: return
|
||||
placed += InputSurfaceElement(control, b.left / width, b.top / height, b.width / width, b.height / height,
|
||||
floating = false, buttonShape = shape).bounded()
|
||||
}
|
||||
fun cross(controls: List<InputControl>, slot: GamepadGeometry.Slot) {
|
||||
val b = boxes[slot] ?: return
|
||||
val side = min(b.width, b.height)
|
||||
val spread = side * CROSS_SPREAD
|
||||
val radius = side * CROSS_RADIUS
|
||||
controls.zip(listOf(0f to -1f, 1f to 0f, 0f to 1f, -1f to 0f)).forEach { (control, direction) ->
|
||||
placed += circle(InputSurfaceElement(control, 0f, 0f, 0f, 0f, buttonShape = InputButtonShape.CIRCLE),
|
||||
b.cx + direction.first * spread, b.cy + direction.second * spread, radius)
|
||||
}
|
||||
}
|
||||
box(left, GamepadGeometry.Slot.LEFT_MAIN, InputButtonShape.CIRCLE)
|
||||
cross(DPAD_ORDER, GamepadGeometry.Slot.LEFT_SECOND)
|
||||
box(right, GamepadGeometry.Slot.RIGHT_MAIN, InputButtonShape.CIRCLE)
|
||||
cross(FACE_ORDER, GamepadGeometry.Slot.RIGHT_SECOND)
|
||||
box(InputControl.LT, GamepadGeometry.Slot.LEFT_OUTER_SHOULDER, InputButtonShape.PILL)
|
||||
box(InputControl.LB, GamepadGeometry.Slot.LEFT_INNER_SHOULDER, InputButtonShape.PILL)
|
||||
box(InputControl.RB, GamepadGeometry.Slot.RIGHT_INNER_SHOULDER, InputButtonShape.PILL)
|
||||
box(InputControl.RT, GamepadGeometry.Slot.RIGHT_OUTER_SHOULDER, InputButtonShape.PILL)
|
||||
box(InputControl.SELECT, GamepadGeometry.Slot.VIEW, InputButtonShape.PILL)
|
||||
box(InputControl.START, GamepadGeometry.Slot.MENU, InputButtonShape.PILL)
|
||||
if (grips) GRIPS.forEach { (control, slot) -> box(control, slot, InputButtonShape.ROUNDED) }
|
||||
val surfaces = listOf(left, right).filter { it.isTrackpad }
|
||||
return withGeometry(stored, placed) + placed.filter { p -> (GRIPS.any { it.first == p.control } || p.control in surfaces) && stored.none { it.id == p.id } }
|
||||
}
|
||||
|
||||
private fun circle(e: InputSurfaceElement, cx: Float, cy: Float, radius: Float) =
|
||||
e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height).bounded()
|
||||
|
||||
private fun withGeometry(stored: List<InputSurfaceElement>, placed: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
||||
val byId = placed.associateBy { it.id }
|
||||
return stored.mapNotNull { e -> byId[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } }
|
||||
}
|
||||
|
||||
private fun keyboard(): InputSurfaceElement {
|
||||
val radius = dp(KEYBOARD_RADIUS_DP)
|
||||
val cx = safe.left + dp(KEYBOARD_X_DP)
|
||||
val cy = height - safe.bottom - dp(KEYBOARD_Y_DP)
|
||||
return InputSurfaceElement(InputControl.A, (cx - radius) / width, (cy - radius) / height, 2 * radius / width, 2 * radius / height,
|
||||
KEYBOARD_ID, name = "Keyboard", icon = InputButtonIcons.KEYBOARD, buttonShape = InputButtonShape.CIRCLE).bounded()
|
||||
}
|
||||
|
||||
fun restyle(elements: List<InputSurfaceElement>): List<InputSurfaceElement> {
|
||||
val dpad = elements.filter { it.id == "legacy:${it.control.id}" && it.control in DPAD && it.buttonShape == InputButtonShape.ROUNDED }
|
||||
val centreX = dpad.map { (it.x + it.width / 2f) * width }.average().toFloat()
|
||||
val centreY = dpad.map { (it.y + it.height / 2f) * height }.average().toFloat()
|
||||
val resize = untouchedDpad(dpad, centreX, centreY)
|
||||
return elements.map { e ->
|
||||
when {
|
||||
e.id == KEYBOARD_ID && e.icon == 0 && e.name == "Keyboard" && e.buttonShape == InputButtonShape.ROUNDED &&
|
||||
e.x == .02f && e.y == .9f && e.width == .12f && e.height == .08f -> keyboard()
|
||||
e.id == "legacy:${e.control.id}" && e.buttonShape == InputButtonShape.ROUNDED -> {
|
||||
val round = e.copy(buttonShape = if (e.control.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE)
|
||||
(if (resize && e.control in DPAD) resizeDpad(round, centreX, centreY) else widenStick(round)).bounded()
|
||||
}
|
||||
else -> e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun untouchedDpad(dpad: List<InputSurfaceElement>, centreX: Float, centreY: Float): Boolean {
|
||||
if (dpad.size != DPAD.size) return false
|
||||
val radius = dpad[0].width * width / 2f
|
||||
val tolerance = 1.5f
|
||||
val offset = radius * LEGACY_DPAD_OFFSET_DP / LEGACY_DPAD_RADIUS_DP
|
||||
return dpad.all { e ->
|
||||
val old = controls.first { it.id == e.control.id }
|
||||
val dx = (e.x + e.width / 2f) * width - centreX
|
||||
val dy = (e.y + e.height / 2f) * height - centreY
|
||||
abs(e.width * width / 2f - radius) <= tolerance && abs(e.height * height / 2f - radius) <= tolerance &&
|
||||
abs(dx - offset * sign(old.offsetXDp)) <= tolerance && abs(dy - offset * sign(old.offsetYDp)) <= tolerance
|
||||
}
|
||||
}
|
||||
|
||||
private fun resizeDpad(e: InputSurfaceElement, centreX: Float, centreY: Float): InputSurfaceElement {
|
||||
val old = controls.first { it.id == e.control.id }
|
||||
val radius = e.width * width / 2f * old.radiusDp / LEGACY_DPAD_RADIUS_DP
|
||||
val cx = centreX + ((e.x + e.width / 2f) * width - centreX) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
|
||||
val cy = centreY + ((e.y + e.height / 2f) * height - centreY) * abs(old.offsetXDp + old.offsetYDp) / LEGACY_DPAD_OFFSET_DP
|
||||
return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height)
|
||||
}
|
||||
|
||||
private fun widenStickPreviously(e: InputSurfaceElement): InputSurfaceElement {
|
||||
val extra = e.width * (STICK_REACH - 1f)
|
||||
return when (e.control) {
|
||||
InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) }
|
||||
InputControl.RS -> e.copy(width = (e.width + extra).coerceAtMost(1f - e.x))
|
||||
else -> e
|
||||
}
|
||||
}
|
||||
|
||||
private fun widenStick(e: InputSurfaceElement): InputSurfaceElement {
|
||||
val extra = e.width * (STICK_REACH - 1f)
|
||||
val width = e.width + extra
|
||||
return when (e.control) {
|
||||
InputControl.LS -> e.copy(x = (e.x - extra).coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width)
|
||||
InputControl.RS -> e.copy(x = e.x.coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width)
|
||||
else -> e
|
||||
}
|
||||
}
|
||||
private companion object {
|
||||
const val MIN_FACE_MM = 9.5f
|
||||
const val FULL_SIZE_HEIGHT_MM = 85f
|
||||
const val BOTTOM_MARGIN_MM = 5f
|
||||
const val DROP_DEGREES = 35.0
|
||||
const val PHONE_MAX_HEIGHT_MM = 90f
|
||||
const val SHOULDER_WIDTH = 1.45f
|
||||
const val SHOULDER_HEIGHT = 0.8f
|
||||
val shoulderIds = setOf("lb", "rb", "lt", "rt")
|
||||
const val STICK_REACH = 1.25f
|
||||
const val LEGACY_DPAD_RADIUS_DP = 26f
|
||||
const val LEGACY_DPAD_OFFSET_DP = 52f
|
||||
val DPAD = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
|
||||
const val KEYBOARD_ID = "builtin:keyboard"
|
||||
const val KEYBOARD_RADIUS_DP = 18f
|
||||
const val KEYBOARD_X_DP = 90f
|
||||
const val KEYBOARD_Y_DP = 34f
|
||||
const val BUTTONS_ONLY_RADIUS_DP = 30f
|
||||
const val BUTTONS_ONLY_INSET_DP = 44f
|
||||
const val CROSS_SPREAD = .30f
|
||||
const val CROSS_RADIUS = .16f
|
||||
val DPAD_ORDER = listOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
|
||||
val FACE_ORDER = listOf(InputControl.Y, InputControl.B, InputControl.A, InputControl.X)
|
||||
val GRIPS = listOf(InputControl.L4 to GamepadGeometry.Slot.L4, InputControl.L5 to GamepadGeometry.Slot.L5,
|
||||
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
|
||||
}
|
||||
}
|
||||
@@ -3,103 +3,77 @@ package com.droiddeck.launcher.input
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Rect
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.RectF
|
||||
import android.os.Build
|
||||
import android.view.Gravity
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.ViewConfiguration
|
||||
import android.view.WindowInsets
|
||||
import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.ui.InputSurfaceView
|
||||
import com.droiddeck.launcher.ui.PadArt
|
||||
|
||||
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
|
||||
/** Why the controls are hidden while the corner button stays. */
|
||||
enum class Hidden { BY_TAP, BY_CONTROLLER }
|
||||
|
||||
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
|
||||
private var layout: SavedInputLayout? = null
|
||||
private val safe = Rect()
|
||||
private var viewWidth = 0
|
||||
private var viewHeight = 0
|
||||
private val placements = object : LinkedHashMap<Placement, List<InputSurfaceElement>>(4, .75f, true) {
|
||||
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Placement, List<InputSurfaceElement>>) = size > PLACEMENT_CACHE
|
||||
}
|
||||
private val quickToggle = QuickToggle(context)
|
||||
var isButtonsOnly = false
|
||||
private val corner = CornerButton(context)
|
||||
var hidden: Hidden? = null
|
||||
private set
|
||||
var isQuickHidden = false
|
||||
private set
|
||||
var isPinnedOnly = false
|
||||
private set
|
||||
val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true
|
||||
val inputSurface: com.droiddeck.launcher.ui.InputSurfaceView get() = surface
|
||||
/** Holding the corner button opens DroidDeck's controller menu. */
|
||||
var onCornerHold: (() -> Unit)? = null
|
||||
/** The player tapped the corner button. */
|
||||
var onCornerTap: ((Hidden?) -> Unit)? = null
|
||||
val inputSurface: InputSurfaceView get() = surface
|
||||
var onTouchMiss: ((MotionEvent) -> Unit)?
|
||||
get() = surface.onTouchMiss
|
||||
set(value) { surface.onTouchMiss = value }
|
||||
|
||||
init {
|
||||
addView(surface, LayoutParams(-1, -1))
|
||||
val size = (QUICK_HIT_DP * 2 * resources.displayMetrics.density).toInt()
|
||||
addView(quickToggle, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
|
||||
val size = (CORNER_HIT_DP * resources.displayMetrics.density).toInt()
|
||||
addView(corner, LayoutParams(size, size, Gravity.START or Gravity.BOTTOM))
|
||||
}
|
||||
|
||||
fun updateLayout(value: SavedInputLayout?) {
|
||||
if (layout == value) return
|
||||
val kit = PadKit.current(context)
|
||||
if (layout == value && surface.kit == kit) return
|
||||
releaseAll()
|
||||
layout = value
|
||||
surface.kit = kit
|
||||
render()
|
||||
}
|
||||
|
||||
fun setButtonsOnly(enabled: Boolean) {
|
||||
if (isButtonsOnly == enabled) return
|
||||
fun setHidden(value: Hidden?) {
|
||||
if (hidden == value) return
|
||||
releaseAll()
|
||||
isButtonsOnly = enabled
|
||||
isQuickHidden = false
|
||||
hidden = value
|
||||
render()
|
||||
}
|
||||
|
||||
fun setQuickHidden(hidden: Boolean) {
|
||||
if (isButtonsOnly || isQuickHidden == hidden) return
|
||||
releaseAll()
|
||||
isQuickHidden = hidden
|
||||
render()
|
||||
}
|
||||
|
||||
fun setPinnedOnly(enabled: Boolean) {
|
||||
if (isPinnedOnly == enabled) return
|
||||
releaseAll()
|
||||
isPinnedOnly = enabled
|
||||
render()
|
||||
}
|
||||
|
||||
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
|
||||
|
||||
private fun placed(): List<InputSurfaceElement> {
|
||||
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
|
||||
return placements.getOrPut(key) {
|
||||
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock)
|
||||
}
|
||||
}
|
||||
|
||||
private fun render() {
|
||||
val elements = placed()
|
||||
surface.updateCustomLayout(when {
|
||||
isPinnedOnly -> elements.filter { it.alwaysShown }
|
||||
isQuickHidden -> elements.filter { it.id == "builtin:keyboard" || it.alwaysShown }
|
||||
else -> elements
|
||||
})
|
||||
val style = layout?.style ?: InputSurfaceStyle()
|
||||
surface.updateStyle(style)
|
||||
quickToggle.tint = style.tint
|
||||
quickToggle.alpha = style.opacity / 100f
|
||||
quickToggle.visibility = if (isButtonsOnly || isPinnedOnly || layout == null || dock != null) GONE else VISIBLE
|
||||
quickToggle.invalidate()
|
||||
surface.updateCustomLayout(if (hidden != null) emptyList() else OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock))
|
||||
surface.updateStyle(layout?.style ?: InputSurfaceStyle())
|
||||
corner.visibility = if (layout == null || dock != null) GONE else VISIBLE
|
||||
corner.alpha = (layout?.style?.opacity ?: 100) / 100f
|
||||
corner.invalidate()
|
||||
}
|
||||
|
||||
fun takesTouchAt(x: Float, y: Float) = surface.takesTouchAt(x, y) ||
|
||||
quickToggle.visibility == VISIBLE && x >= quickToggle.left && x < quickToggle.right && y >= quickToggle.top && y < quickToggle.bottom
|
||||
corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
|
||||
fun cornerTakes(x: Float, y: Float) = corner.visibility == VISIBLE && x >= corner.left && x < corner.right && y >= corner.top && y < corner.bottom
|
||||
fun releaseAll() = surface.releaseInputs()
|
||||
fun reload() { releaseAll(); placements.clear(); render() }
|
||||
fun reload() { releaseAll(); surface.kit = PadKit.current(context); render() }
|
||||
|
||||
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
|
||||
val w = MeasureSpec.getSize(widthMeasureSpec)
|
||||
@@ -116,14 +90,14 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
|
||||
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
|
||||
val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null
|
||||
val offset = ((QUICK_CENTER_DP - QUICK_HIT_DP) * resources.displayMetrics.density).toInt()
|
||||
val params = quickToggle.layoutParams as LayoutParams
|
||||
val left = (cutout?.safeInsetLeft ?: 0) + offset
|
||||
val bottom = (cutout?.safeInsetBottom ?: 0) + offset
|
||||
val margin = (CORNER_MARGIN_DP * resources.displayMetrics.density).toInt()
|
||||
val params = corner.layoutParams as LayoutParams
|
||||
val left = (cutout?.safeInsetLeft ?: 0) + margin
|
||||
val bottom = (cutout?.safeInsetBottom ?: 0) + margin
|
||||
if (params.leftMargin != left || params.bottomMargin != bottom) {
|
||||
params.leftMargin = left
|
||||
params.bottomMargin = bottom
|
||||
quickToggle.layoutParams = params
|
||||
corner.layoutParams = params
|
||||
}
|
||||
val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
|
||||
if (fresh != safe) {
|
||||
@@ -133,42 +107,45 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
return super.onApplyWindowInsets(insets)
|
||||
}
|
||||
|
||||
private inner class QuickToggle(context: Context) : View(context) {
|
||||
var tint: Int? = ControllerPrefs.STEAM_BLUE
|
||||
private val density = resources.displayMetrics.density
|
||||
private inner class CornerButton(context: Context) : View(context) {
|
||||
private val art = PadArt(context)
|
||||
private val badge = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private var armed = false
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeWidth = 1.5f * density }
|
||||
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
textAlign = Paint.Align.CENTER
|
||||
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
|
||||
textSize = 22 * density
|
||||
}
|
||||
private var held = false
|
||||
private val hold = Runnable { if (armed) { held = true; performHapticFeedback(HapticFeedbackConstants.LONG_PRESS) } }
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
val x = width / 2f
|
||||
val y = height / 2f
|
||||
val radius = QUICK_RADIUS_DP * density
|
||||
val color = tint
|
||||
fill.color = if (color != null) InputSurfaceView.shade(color, 190, 0.12f) else (InputSurfaceView.SURFACE and 0x00ffffff) or (190 shl 24)
|
||||
canvas.drawCircle(x, y, radius, fill)
|
||||
stroke.color = if (color != null) InputSurfaceView.light(color, 150, 0.25f) else InputSurfaceView.LINE
|
||||
canvas.drawCircle(x, y, radius, stroke)
|
||||
text.color = if (color != null) InputSurfaceView.light(color, 210, 0.75f) else InputSurfaceView.TEXT
|
||||
canvas.drawText(if (isQuickHidden) "+" else "−", x, y + text.textSize * 0.35f, text)
|
||||
val w = width.toFloat(); val h = height.toFloat()
|
||||
val dimmed = hidden != null && !armed
|
||||
if (dimmed) canvas.saveLayerAlpha(0f, 0f, w, h, 170)
|
||||
art.system(canvas, w, h, PadArt.Shape.ROUND, PadArt.Icon.MARK, armed)
|
||||
if (dimmed) canvas.restore()
|
||||
if (hidden == Hidden.BY_CONTROLLER) {
|
||||
val d = art.density
|
||||
val r = RectF(w - 15 * d, 3 * d, w - 2 * d, 12 * d)
|
||||
badge.style = Paint.Style.FILL; badge.color = Color.rgb(0x16, 0x19, 0x1E)
|
||||
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
|
||||
badge.style = Paint.Style.STROKE; badge.strokeWidth = 1.3f * d; badge.color = Color.rgb(0xFF, 0xB3, 0x47)
|
||||
canvas.drawRoundRect(r, 2.5f * d, 2.5f * d, badge)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("ClickableViewAccessibility")
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN -> armed = true
|
||||
MotionEvent.ACTION_CANCEL -> armed = false
|
||||
MotionEvent.ACTION_DOWN -> { armed = true; held = false; postDelayed(hold, ViewConfiguration.getLongPressTimeout().toLong()); invalidate() }
|
||||
MotionEvent.ACTION_CANCEL -> { armed = false; removeCallbacks(hold); invalidate() }
|
||||
MotionEvent.ACTION_UP -> {
|
||||
if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
|
||||
removeCallbacks(hold)
|
||||
if (armed && held) post { onCornerHold?.invoke() }
|
||||
else if (armed && event.x in 0f..width.toFloat() && event.y in 0f..height.toFloat()) {
|
||||
performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)
|
||||
setQuickHidden(!isQuickHidden)
|
||||
val next = if (hidden == null) Hidden.BY_TAP else null
|
||||
setHidden(next)
|
||||
onCornerTap?.invoke(next)
|
||||
}
|
||||
armed = false
|
||||
invalidate()
|
||||
}
|
||||
}
|
||||
return true
|
||||
@@ -176,9 +153,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val QUICK_CENTER_DP = 34f
|
||||
const val QUICK_HIT_DP = 26f
|
||||
const val QUICK_RADIUS_DP = 18f
|
||||
const val PLACEMENT_CACHE = 4
|
||||
const val CORNER_HIT_DP = 48f
|
||||
const val CORNER_MARGIN_DP = 4f
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,8 @@ package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Rect
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
object OnScreenLayout {
|
||||
data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) {
|
||||
@@ -21,25 +19,18 @@ object OnScreenLayout {
|
||||
}
|
||||
}
|
||||
|
||||
private const val TOLERANCE = .01f
|
||||
private const val KEYBOARD_ID = "builtin:keyboard"
|
||||
/** The built-in gamepad keeps no positions until it is edited; until then it follows the virtual controller's kit. */
|
||||
fun generated(layout: SavedInputLayout) = layout.elements.isEmpty() && (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY)
|
||||
|
||||
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
|
||||
buttonsOnly: Boolean = false, dock: Dock? = null): List<InputSurfaceElement> {
|
||||
val stored = layout?.elements ?: return emptyList()
|
||||
if (width <= 0 || height <= 0) return stored
|
||||
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
|
||||
val (reference, generated) = reference(context, layout, width, height)
|
||||
if (buttonsOnly && dock == null) return generator.buttonsOnly(stored) + fit(stored.filter { it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
||||
val gamepad = if (generated) stored.filter(::isGamepad) else emptyList()
|
||||
val others = fit(stored.filterNot { generated && isGamepad(it) || dock != null && it.alwaysShown }, reference.first, reference.second, width, height, safe)
|
||||
val placed = when {
|
||||
gamepad.isEmpty() -> emptyList()
|
||||
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
|
||||
else -> generator.regenerate(gamepad)
|
||||
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null): List<InputSurfaceElement> {
|
||||
layout ?: return emptyList()
|
||||
if (width <= 0 || height <= 0) return layout.elements
|
||||
if (generated(layout)) {
|
||||
val kit = PadKit.current(context)
|
||||
return if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right)
|
||||
else KitLayout.elements(context, kit, width, height, safe, layout.scale)
|
||||
}
|
||||
val byId = (placed + others).associateBy { it.id }
|
||||
return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
|
||||
return fit(layout.elements, aspect(context, layout), 1f, width, height, safe)
|
||||
}
|
||||
|
||||
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
|
||||
@@ -73,35 +64,8 @@ object OnScreenLayout {
|
||||
}
|
||||
}
|
||||
|
||||
private fun isGamepad(e: InputSurfaceElement) = e.id.startsWith("legacy:") || e.id == KEYBOARD_ID
|
||||
|
||||
fun generatedSize(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Int, Int>? =
|
||||
reference(context, layout, width, height).takeIf { it.second }?.first?.let { it.first.toInt() to it.second.toInt() }
|
||||
|
||||
private fun reference(context: Context, layout: SavedInputLayout, width: Int, height: Int): Pair<Pair<Float, Float>, Boolean> {
|
||||
val (display, metrics) = InputLibraries.primaryDisplay(context)
|
||||
val long = max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
|
||||
val short = min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
|
||||
val gamepad = layout.elements.filter(::isGamepad)
|
||||
if (gamepad.any { it.id.startsWith("legacy:") }) {
|
||||
val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() }
|
||||
?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] }
|
||||
val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f }
|
||||
?.let { (it * height).roundToInt().coerceAtLeast(1) to height }
|
||||
for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) {
|
||||
val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale)
|
||||
if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true))) return (w.toFloat() to h.toFloat()) to true
|
||||
}
|
||||
}
|
||||
val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short)
|
||||
return (aspect to 1f) to false
|
||||
}
|
||||
|
||||
private fun matches(stored: List<InputSurfaceElement>, generated: List<InputSurfaceElement>): Boolean {
|
||||
val byId = generated.associateBy { it.id }
|
||||
return stored.all { e ->
|
||||
val g = byId[e.id] ?: return@all false
|
||||
abs(e.x - g.x) <= TOLERANCE && abs(e.y - g.y) <= TOLERANCE && abs(e.width - g.width) <= TOLERANCE && abs(e.height - g.height) <= TOLERANCE
|
||||
}
|
||||
private fun aspect(context: Context, layout: SavedInputLayout): Float = layout.aspect.takeIf { it > 0f } ?: run {
|
||||
val metrics = InputLibraries.primaryDisplay(context).second
|
||||
max(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1).toFloat() / min(metrics.widthPixels, metrics.heightPixels).coerceAtLeast(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.droiddeck.launcher.input
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
|
||||
enum class DpadStyle { CROSS, DISC, ARROWS }
|
||||
enum class StickCap { RINGED, DISHED, KNURLED }
|
||||
|
||||
enum class PadKit(val face: FaceGlyphs, val dpad: DpadStyle, val stick: StickCap, private val xbox: Boolean = false) {
|
||||
STEAM_DECK(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
|
||||
STEAM_CONTROLLER(FaceGlyphs.MONO_LETTERS, DpadStyle.CROSS, StickCap.RINGED),
|
||||
XBOX(FaceGlyphs.COLOR_LETTERS, DpadStyle.DISC, StickCap.DISHED, xbox = true),
|
||||
DUALSHOCK(FaceGlyphs.COLOR_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED),
|
||||
DUALSENSE(FaceGlyphs.MONO_SYMBOLS, DpadStyle.ARROWS, StickCap.KNURLED);
|
||||
|
||||
val steam get() = this == STEAM_DECK || this == STEAM_CONTROLLER
|
||||
val playStation get() = this == DUALSHOCK || this == DUALSENSE
|
||||
|
||||
fun label(control: InputControl): String = when (control) {
|
||||
InputControl.LB -> if (xbox) "LB" else "L1"
|
||||
InputControl.RB -> if (xbox) "RB" else "R1"
|
||||
InputControl.LT -> if (xbox) "LT" else "L2"
|
||||
InputControl.RT -> if (xbox) "RT" else "R2"
|
||||
else -> control.label
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun of(type: String) = when (type) {
|
||||
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
|
||||
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
|
||||
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
|
||||
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
|
||||
else -> STEAM_DECK
|
||||
}
|
||||
|
||||
fun current(context: Context) = of(SessionPrefs.steamController(context))
|
||||
}
|
||||
}
|
||||
@@ -119,6 +119,7 @@ class SteamTouchControls(
|
||||
private var selectedArm = 0
|
||||
|
||||
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
private val art = com.droiddeck.launcher.ui.PadArt(context)
|
||||
private val stroke = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; isFakeBoldText = true }
|
||||
|
||||
@@ -281,56 +282,54 @@ class SteamTouchControls(
|
||||
val r = radius(e)
|
||||
val pressed = !editing && e.type in pressedTypes()
|
||||
val alpha = (255 * alphaScale * if (faded) FADED else 1f).toInt().coerceIn(30, 255)
|
||||
val ink = Color.argb(alpha, Color.red(tint), Color.green(tint), Color.blue(tint))
|
||||
stroke.color = if (isSelected) Color.rgb(26, 159, 255) else ink
|
||||
stroke.strokeWidth = if (isSelected) lineWidth() * 2f else lineWidth()
|
||||
fill.color = Color.argb((alpha * 0.85f).toInt(), 230, 233, 236)
|
||||
text.color = ink
|
||||
text.typeface = android.graphics.Typeface.DEFAULT_BOLD
|
||||
if (alpha < 255) canvas.saveLayerAlpha(x - r * 1.5f, y - r * 1.5f, x + r * 1.5f, y + r * 1.5f, alpha)
|
||||
when (e.type) {
|
||||
SteamTouchConfig.DPAD -> drawDpad(canvas, e, x, y, r)
|
||||
SteamTouchConfig.DPAD -> if (visuals[SteamTouchConfig.DPAD].orEmpty().any { it.binding?.hasIcon == true }) drawDpad(canvas, e, x, y, r) else {
|
||||
val bits = if (editing) 0L else dpadBits(e)
|
||||
val held = (if (bits and DPAD_UP != 0L) 1 else 0) or (if (bits and DPAD_RIGHT != 0L) 2 else 0) or
|
||||
(if (bits and DPAD_DOWN != 0L) 4 else 0) or (if (bits and DPAD_LEFT != 0L) 8 else 0)
|
||||
canvas.save(); canvas.translate(x - r, y - r)
|
||||
art.dpad(canvas, 2 * r, 2 * r, PadKit.STEAM_DECK, held)
|
||||
canvas.restore()
|
||||
}
|
||||
SteamTouchConfig.JOYSTICK_LEFT, SteamTouchConfig.JOYSTICK_RIGHT -> {
|
||||
canvas.drawCircle(x, y, r, stroke)
|
||||
val f = fingers.values.firstOrNull { it.element?.type == e.type }
|
||||
if (f != null && !editing) {
|
||||
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
|
||||
var kx = 0f; var ky = 0f
|
||||
if (f != null) {
|
||||
val d = hypot(f.x - x, f.y - y)
|
||||
val k = if (d > r) r / d else 1f
|
||||
val kx = x + (f.x - x) * k
|
||||
val ky = y + (f.y - y) * k
|
||||
canvas.drawCircle(kx, ky, r * 0.42f, fill)
|
||||
kx = (f.x - x) * k * .54f; ky = (f.y - y) * k * .54f
|
||||
}
|
||||
art.stick(canvas, x, y, r, PadKit.STEAM_DECK, kx, ky, f != null)
|
||||
}
|
||||
SteamTouchConfig.TRACKPAD_LEFT, SteamTouchConfig.TRACKPAD_RIGHT, SteamTouchConfig.TRACKPAD_CENTER -> {
|
||||
val rect = RectF(x - r * 1.3f, y - r * 0.85f, x + r * 1.3f, y + r * 0.85f)
|
||||
if (pressed) canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, fill)
|
||||
canvas.drawRoundRect(rect, r * 0.18f, r * 0.18f, stroke)
|
||||
if (editing) {
|
||||
text.textSize = r * 0.3f
|
||||
text.color = Color.argb(alpha / 2, 255, 255, 255)
|
||||
canvas.drawText(context.getString(R.string.deck_surface_trackpad), x, y - (text.descent() + text.ascent()) / 2, text)
|
||||
}
|
||||
}
|
||||
SteamTouchConfig.STEAM -> {
|
||||
if (isSelected) canvas.drawCircle(x, y, r, stroke)
|
||||
drawMark(canvas, x, y, r * 0.5f, if (pressed) accent else ink, alpha)
|
||||
val f = fingers.values.firstOrNull { it.element?.type == e.type }.takeIf { !editing }
|
||||
canvas.save(); canvas.translate(x - r * 1.3f, y - r * .85f)
|
||||
art.trackpad(canvas, r * 2.6f, r * 1.7f, f != null, (f?.x ?: x) - x + r * 1.3f, (f?.y ?: y) - y + r * .85f)
|
||||
canvas.restore()
|
||||
if (editing) art.text(canvas, context.getString(R.string.deck_surface_trackpad), x, y, r * .3f, Color.argb(128, 255, 255, 255))
|
||||
}
|
||||
SteamTouchConfig.STEAM -> systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.PILL, com.droiddeck.launcher.ui.PadArt.Icon.STEAM, pressed)
|
||||
SteamTouchConfig.SELECT, SteamTouchConfig.START -> {
|
||||
val binding = visuals[e.type]?.firstOrNull()?.binding
|
||||
if (binding?.hasIcon == true) {
|
||||
drawFace(canvas, e.type, binding, x, y, r, alpha, pressed); return
|
||||
}
|
||||
val rect = RectF(x - r * 1.08f, y - r * 0.55f, x + r * 1.08f, y + r * 0.55f)
|
||||
if (pressed) canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, fill)
|
||||
canvas.drawRoundRect(rect, r * 0.5f, r * 0.5f, stroke)
|
||||
val t = r * 0.26f
|
||||
val dir = if (e.type == SteamTouchConfig.START) 1f else -1f
|
||||
val tri = Path().apply {
|
||||
moveTo(x + dir * t, y); lineTo(x - dir * t * 0.75f, y - t); lineTo(x - dir * t * 0.75f, y + t); close()
|
||||
}
|
||||
canvas.drawPath(tri, Paint(Paint.ANTI_ALIAS_FLAG).apply { color = if (pressed) Color.argb(alpha, 23, 26, 33) else ink })
|
||||
if (binding?.hasIcon == true) drawFace(canvas, e.type, binding, x, y, r, pressed)
|
||||
else systemButton(canvas, x, y, r, com.droiddeck.launcher.ui.PadArt.Shape.CHIP,
|
||||
if (e.type == SteamTouchConfig.START) com.droiddeck.launcher.ui.PadArt.Icon.MENU else com.droiddeck.launcher.ui.PadArt.Icon.VIEW, pressed)
|
||||
}
|
||||
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, alpha, pressed)
|
||||
else -> drawFace(canvas, e.type, visuals[e.type]?.firstOrNull()?.binding, x, y, r, pressed)
|
||||
}
|
||||
if (alpha < 255) canvas.restore()
|
||||
if (isSelected) {
|
||||
stroke.color = accent; stroke.strokeWidth = lineWidth() * 2f
|
||||
if (isSquare(e.type)) canvas.drawRoundRect(RectF(x - r, y - r, x + r, y + r), r * .3f, r * .3f, stroke) else canvas.drawCircle(x, y, r, stroke)
|
||||
}
|
||||
}
|
||||
|
||||
private fun systemButton(canvas: Canvas, x: Float, y: Float, r: Float, shape: com.droiddeck.launcher.ui.PadArt.Shape,
|
||||
icon: com.droiddeck.launcher.ui.PadArt.Icon, pressed: Boolean) {
|
||||
canvas.save(); canvas.translate(x - r * 1.4f, y - r * 1.4f)
|
||||
art.system(canvas, r * 2.8f, r * 2.8f, shape, icon, pressed)
|
||||
canvas.restore()
|
||||
}
|
||||
|
||||
private fun isSquare(type: Int) = type in setOf(SteamTouchConfig.BUMPER_LEFT, SteamTouchConfig.BUMPER_RIGHT,
|
||||
@@ -350,53 +349,29 @@ class SteamTouchControls(
|
||||
canvas.restore()
|
||||
}
|
||||
|
||||
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
|
||||
alpha: Int, pressed: Boolean) {
|
||||
val square = isSquare(type)
|
||||
val rect = RectF(x - r, y - r, x + r, y + r)
|
||||
val corner = r * 0.3f
|
||||
fun shape(paint: Paint) = if (square) canvas.drawRoundRect(rect, corner, corner, paint) else canvas.drawCircle(x, y, r, paint)
|
||||
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float, pressed: Boolean) {
|
||||
val shape = if (isSquare(type)) art.roundRect(x - r, y - r, x + r, y + r, r * .3f) else art.circle(x, y, r)
|
||||
val icon = binding?.icon?.takeIf { it.isNotEmpty() }?.let(::iconOrLoad)
|
||||
val custom = binding != null && binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
|
||||
art.glass(canvas, shape, pressed && !custom, if (custom) parseColor(binding!!.background, SteamTouchBindings.DEFAULT_BACKGROUND) else 0x850E1014.toInt())
|
||||
val ink = if (pressed && !custom) com.droiddeck.launcher.ui.PadArt.ON_ACCENT else com.droiddeck.launcher.ui.PadArt.INK
|
||||
if (icon != null) {
|
||||
val s = r * 0.62f
|
||||
val custom = binding.background.isNotEmpty() && !binding.background.equals(SteamTouchBindings.DEFAULT_BACKGROUND, true)
|
||||
if (custom) {
|
||||
shape(Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = parseColor(binding.background, SteamTouchBindings.DEFAULT_BACKGROUND)
|
||||
this.alpha = if (pressed) alpha else (alpha * 0.85f).toInt()
|
||||
})
|
||||
canvas.drawBitmap(tinted(binding.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s),
|
||||
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { this.alpha = alpha })
|
||||
} else {
|
||||
if (pressed) shape(fill)
|
||||
val ink = if (pressed) Color.argb(alpha, 23, 26, 33) else stroke.color
|
||||
canvas.drawBitmap(inked(binding.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
|
||||
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply {
|
||||
colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN)
|
||||
})
|
||||
}
|
||||
shape(stroke)
|
||||
if (custom) canvas.drawBitmap(tinted(binding!!.icon, icon, binding.foreground), null, RectF(x - s, y - s, x + s, y + s), Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
|
||||
else canvas.drawBitmap(inked(binding!!.icon, icon), null, RectF(x - s, y - s, x + s, y + s),
|
||||
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { colorFilter = android.graphics.PorterDuffColorFilter(ink, android.graphics.PorterDuff.Mode.SRC_IN) })
|
||||
return
|
||||
}
|
||||
if (pressed) shape(fill)
|
||||
shape(stroke)
|
||||
if (type == SteamTouchConfig.THUMB) { drawDots(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
|
||||
if (type == SteamTouchConfig.KEYBOARD) { drawKeyboardGlyph(canvas, x, y, r, if (pressed) Color.argb(alpha, 23, 26, 33) else text.color); return }
|
||||
val own = label(type)
|
||||
val shown = own
|
||||
text.textSize = when {
|
||||
if (type == SteamTouchConfig.THUMB) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.QAM, ink); return }
|
||||
if (type == SteamTouchConfig.KEYBOARD) { art.icon(canvas, x, y, r * 1.1f, com.droiddeck.launcher.ui.PadArt.Icon.KEYBOARD, ink); return }
|
||||
val shown = label(type)
|
||||
val size = when {
|
||||
shown.length <= 1 -> r * 0.9f
|
||||
shown.length <= 2 -> r * 0.66f
|
||||
shown.length <= 5 -> r * 0.4f
|
||||
else -> r * 0.3f
|
||||
}
|
||||
text.color = when {
|
||||
pressed -> Color.argb(alpha, 23, 26, 33)
|
||||
shown == own -> LABEL_COLORS[type]?.let { Color.argb(alpha, Color.red(it), Color.green(it), Color.blue(it)) } ?: text.color
|
||||
else -> text.color
|
||||
}
|
||||
val line = if (shown.length > 10) shown.take(9) + "…" else shown
|
||||
canvas.drawText(line, x, y - (text.descent() + text.ascent()) / 2, text)
|
||||
art.text(canvas, if (shown.length > 10) shown.take(9) + "…" else shown, x, y, size, ink, r * 1.8f)
|
||||
}
|
||||
|
||||
private fun drawDots(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
|
||||
|
||||
Reference in new issue
Block a user