feat(input): controller-specific on-screen controls with editor, rotation and tablet fixes (#2988)

* feat(input): restore controller-specific overlay designs

* fix(input): restore portrait controller layouts

* fix(input): fix duplicates, rotation and tablet placement in the controller overlays

- Hide the below-game controls while the layout editor is open, and give the
  editor the same cutout insets and optional Steam controls as the game view,
  so the editor never shows a second copy of a control.
- Keep a separate portrait frame for layouts edited in portrait. A layout
  edited in one orientation keeps the stock kit positions in the other instead
  of being stretched across.
- Anchor the overlay to the bottom of the screen and cap the portrait panel's
  physical size, so tablets keep the controls in the lower half.
- Put L2/L1 and R1/R2 side by side in every kit.
- List deleted stock controls in the editor's Add dialog so they can be
  restored, and keep removed rear buttons and trackpads removed.

* fix(input): scale edited overlay layouts around the controller artwork positions

* fix(input): keep stock landscape controls, color setting, keyboard action and displayed frame edits consistent

* fix(input): draw the layout editor with the kit artwork at the size it will be saved

The editor placed its controls in onSizeChanged, which runs during layout, so
the preview canvas was rebuilt or remeasured too late: new controls were laid
out at 0x0 and existing ones kept stale sizes, losing the kit D-pad artwork.
Placement now happens in onMeasure, before the canvas measures its children.

The editor preview used the saved button size instead of the slider value, so
the slider showed a different layout from the one Done saved.

D-pad pieces that joined or left the kit cross were never redrawn, so moving
one piece hid all four.

* fix(input): keep portrait rear buttons and trackpads where they were saved

A portrait save stores the rear buttons and trackpads only in the rotated
frame, but loading that frame only moved controls that already existed in the
main frame, so they were regenerated at the screen edges.

* fix(input): adopt the displayed portrait frame for layouts edited only in landscape

Button size and reset positions now switch to the frame on screen whenever the edited layout's
orientation differs from the editor, not only when a rotated frame exists, so a portrait change
is saved as the portrait frame instead of overwriting the landscape edits. The tools panel stays
open while that happens.

* fix(input): keep a separate button size for the rotated frame

* fix(input): take the shown frame's button size whenever editing switches orientation

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
This commit is contained in:
MaxsTechReviewandKurt Himebauch authored and GitHub committed 2026-11-21 20:11:21 -05:00
1 parent 183cbd9351
commit 378175c6ac
22 files changed
+1345 -426

No files matched your search

@@ -1752,6 +1752,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id))
padType = id
onScreenControls?.reload()
applyUnfoldedControls()
unfoldedPanel?.reload()
bottomInputControls?.reload()
},
backHold = backHold,
@@ -4629,7 +4631,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
else "unfolded controls: game full screen")
}
val portrait = !com.droiddeck.launcher.session.SessionDisplay.foldable(this)
val dock = if (SessionState.deckPad) com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD])
val kit = com.droiddeck.launcher.input.PadKit.forOverlay(this, primaryInputLayout)
val dock = if (SessionState.deckPad && kit?.steam != false)
com.droiddeck.launcher.input.OnScreenLayout.Dock.deck(portrait, deckPanelLayouts[com.droiddeck.launcher.input.DeckPanel.GAMEPAD])
else com.droiddeck.launcher.input.OnScreenLayout.Dock(portrait, false)
var panel = unfoldedPanel
if (panel != null && (!wanted || panel.dock != dock)) {
@@ -5510,6 +5514,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
.takeIf { it.isFile }
?.let { FileUtils.readString(it)?.trim()?.lowercase() }
?: SessionPrefs.oscMode(this, SessionState.mode == SessionService.MODE_STEAM)
unfoldedColumn?.let { column ->
val shown = if (inputSettingsOpen) View.INVISIBLE else View.VISIBLE
if (column.visibility != shown) { unfoldedPanel?.releaseAll(); unfoldedDeckSurface?.releaseInputs(); column.visibility = shown }
}
val controls = onScreenControls ?: return
fun showPinned() {
controls.setPinnedOnly(true)
@@ -5,7 +5,7 @@ import android.util.DisplayMetrics
import kotlin.math.max
import kotlin.math.min
internal class SteamDeckOverlayGeometry(
internal class ControllerOverlayGeometry(
width: Int, height: Int, private val safe: Rect, metrics: DisplayMetrics, scale: Float,
) {
private val w = width.toFloat()
@@ -29,9 +29,12 @@ internal class SteamDeckOverlayGeometry(
}
}
fun place(elements: List<InputSurfaceElement>, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
val x = { ref: Float -> anchor(ref, 1600f, w, safe.left, safe.right) }
val y = { ref: Float -> anchor(ref, 900f, h, safe.top, safe.bottom) }
private fun x(ref: Float) = anchor(ref, 1600f, w, safe.left, safe.right)
private fun y(ref: Float) = max(safe.top + ref * unit, h - safe.bottom - (900f - ref) * unit)
fun place(elements: List<InputSurfaceElement>, kit: PadKit, rearButtons: Boolean, trackpads: Boolean): List<InputSurfaceElement> {
if (!kit.steam) return placeStandardPad(elements, kit)
val leftEdge = safe.left + 52f * density
val middle = (w + safe.left - safe.right) / 2f
val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
@@ -41,15 +44,7 @@ internal class SteamDeckOverlayGeometry(
Box(middle + 140f * unit, y(850f), 46f, 26f),
Box(x(1230f), y(852f), 66f, 30f)), leftEdge)
val (guide, select, start, qam) = row.takeLast(4)
val positions = mapOf(
InputControl.LT to Box(x(140f), y(66f), 88f, 34f),
InputControl.LB to Box(x(140f), y(148f), 88f, 30f),
InputControl.RT to Box(x(1460f), y(66f), 88f, 34f),
InputControl.RB to Box(x(1460f), y(148f), 88f, 30f),
InputControl.Y to Box(x(1375f), y(345f) - 96f * unit, 58f),
InputControl.X to Box(x(1375f) - 96f * unit, y(345f), 58f),
InputControl.B to Box(x(1375f) + 96f * unit, y(345f), 58f),
InputControl.A to Box(x(1375f), y(345f) + 96f * unit, 58f),
val positions = shoulders() + face(1375f, 345f, 96f) + mapOf(
InputControl.UP to Box(x(220f), y(345f) - 102.5f * unit, 55.5f, 47.5f),
InputControl.RIGHT to Box(x(220f) + 102.5f * unit, y(345f), 47.5f, 55.5f),
InputControl.DOWN to Box(x(220f), y(345f) + 102.5f * unit, 55.5f, 47.5f),
@@ -80,12 +75,81 @@ internal class SteamDeckOverlayGeometry(
else -> positions[element.control]?.place(element) ?: element
}
}
val chosen = placed.filter { it.id == "legacy:${it.control.id}" }.map { it.control }
return placed + optional.mapNotNull { (control, box) ->
if (placed.any { it.id == "legacy:${control.id}" }) null else box.place(InputSurfaceElement(control,
if (chosen.any { if (control in rear) it in rear else it in pads }) null else box.place(InputSurfaceElement(control,
0f, 0f, 0f, 0f, floating = false, buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad))
}
}
private fun placeStandardPad(elements: List<InputSurfaceElement>, kit: PadKit): List<InputSurfaceElement> {
val leftEdge = safe.left + 52f * density
val middle = (w + safe.left - safe.right) / 2f
val keyboard = Box(max(x(136f), leftEdge + 46f * unit), y(848f), 46f).takeIf { elements.any { it.id == KEYBOARD } }
val controls = if (kit.playStation) listOf(
InputControl.QAM to Box(x(220f), y(848f), 46f),
InputControl.SELECT to Box(middle - 160f * unit, y(850f), 50f, 30f),
InputControl.GUIDE to Box(middle, y(850f), 46f),
InputControl.START to Box(middle + 160f * unit, y(850f), 50f, 30f),
) else listOf(
InputControl.QAM to Box(x(220f), y(848f), 46f),
InputControl.SELECT to Box(middle - 110f * unit, y(850f), 38f),
InputControl.GUIDE to Box(middle, y(850f), 46f),
InputControl.START to Box(middle + 110f * unit, y(850f), 38f),
)
val row = fitRow(listOfNotNull(keyboard) + controls.map { it.second }, leftEdge)
val positions = controls.map { it.first }.zip(row.takeLast(controls.size)).toMap() + shoulders() +
if (kit.playStation) {
face(1350f, 395f, 96f) + dpad(250f, 395f, 125f, kit.dpad) + mapOf(
InputControl.LS to Box(x(565f), y(690f), 100f),
InputControl.RS to Box(x(1035f), y(690f), 100f),
InputControl.L3 to Box(x(565f) - 135f * unit, y(690f) - 100f * unit, 42f),
InputControl.R3 to Box(x(1035f) + 135f * unit, y(690f) - 100f * unit, 42f),
)
} else {
face(1375f, 400f, 94f) + dpad(470f, 675f, 118f, kit.dpad) + mapOf(
InputControl.LS to Box(x(235f), y(400f), 104f),
InputControl.RS to Box(x(1130f), y(690f), 104f),
InputControl.L3 to Box(x(235f) + 150f * unit, y(400f) - 110f * unit, 42f),
InputControl.R3 to Box(x(1130f) + 160f * unit, y(690f) + 100f * unit, 42f),
)
}
return elements.map { element ->
when (element.id) {
KEYBOARD -> row.first().place(element)
"legacy:${element.control.id}" -> positions[element.control]?.place(element) ?: element
else -> element
}
}
}
private fun shoulders() = mapOf(
InputControl.LT to Box(x(120f), y(96f), 80f, 34f),
InputControl.LB to Box(x(310f), y(96f), 80f, 34f),
InputControl.RB to Box(x(1290f), y(96f), 80f, 34f),
InputControl.RT to Box(x(1480f), y(96f), 80f, 34f),
)
private fun face(cx: Float, cy: Float, offset: Float) = mapOf(
InputControl.Y to Box(x(cx), y(cy) - offset * unit, 58f),
InputControl.X to Box(x(cx) - offset * unit, y(cy), 58f),
InputControl.B to Box(x(cx) + offset * unit, y(cy), 58f),
InputControl.A to Box(x(cx), y(cy) + offset * unit, 58f),
)
private fun dpad(cx: Float, cy: Float, radius: Float, style: DpadStyle): Map<InputControl, Box> {
val inner = radius * if (style == DpadStyle.DISC) .25f else .14f
val depth = (radius - inner) / 2f
val offset = (radius - depth) * unit
val side = radius * .25f
return mapOf(
InputControl.UP to Box(x(cx), y(cy) - offset, side, depth),
InputControl.RIGHT to Box(x(cx) + offset, y(cy), depth, side),
InputControl.DOWN to Box(x(cx), y(cy) + offset, side, depth),
InputControl.LEFT to Box(x(cx) - offset, y(cy), depth, side),
)
}
private fun fitRow(row: List<Box>, start: Float): List<Box> {
val end = w - safe.right
val gap = ((end - start - row.fold(0f) { sum, box -> sum + box.width }) / (row.size - 1)).coerceIn(0f, 8f * density)
@@ -0,0 +1,127 @@
package com.droiddeck.launcher.input
import android.graphics.Rect
import com.droiddeck.launcher.input.GamepadGeometry.Box
import kotlin.math.min
internal class ControllerPortraitGeometry(
private val width: Float,
private val height: Float,
private val safe: Rect,
private val density: Float,
) {
fun place(
elements: List<InputSurfaceElement>, kit: PadKit, docked: Boolean, scale: Float,
rearButtons: Boolean, trackpads: Boolean,
): List<InputSurfaceElement> {
val w = width - safe.left - safe.right
val h = height - safe.top - safe.bottom
if (w <= 0 || h <= 0) return elements
val presented = elements.toMutableList()
val buttons = mutableMapOf<String, Box>()
val rear = presented.filter { it.control in REAR && isStock(it) }
val pads = presented.filter { it.control.isTrackpad && isStock(it) }
if (!docked && kit.steam) {
if (!rearButtons) presented.removeAll(rear) else if (rear.isEmpty()) REAR.forEach { addOptional(presented, it) }
if (!trackpads) presented.removeAll(pads) else if (pads.isEmpty()) {
addOptional(presented, InputControl.LEFT_PAD)
addOptional(presented, InputControl.RIGHT_PAD)
}
}
fun put(control: InputControl, box: Box) { buttons["legacy:${control.id}"] = box }
val reserve = if (docked) 0f else min(60f * density, h * .15f)
val panel = if (docked) h else min(minOf(h * .60f, w * 1.15f, PANEL_DP * density) * scale, h - reserve)
val top = height - safe.bottom - reserve - panel
val unit = min(density, min(w / 275f, panel / 300f))
val pad = 8f * unit
val gap = 8f * unit
val buttonHeight = 44f * unit
val shoulders = if (docked) listOf(InputControl.LT, InputControl.LB, InputControl.SELECT, InputControl.START, InputControl.RB, InputControl.RT)
else listOf(InputControl.LT, InputControl.LB, InputControl.RB, InputControl.RT)
fun row(controls: List<InputControl>, y: Float, rowHeight: Float, spacing: Float) {
val cell = (w - 2f * pad - (controls.size - 1) * spacing) / controls.size
controls.forEachIndexed { index, control ->
put(control, Box(safe.left + pad + cell / 2f + index * (cell + spacing), y, cell, rowHeight))
}
}
row(shoulders, top + pad + buttonHeight / 2f, buttonHeight, 4f * unit)
var bodyTop = top + pad + buttonHeight + gap
if (presented.any { it.control in REAR && isStock(it) }) {
val rearHeight = min(56f * unit, (panel - bodyTop + top) * .12f).coerceAtLeast(buttonHeight)
row(REAR, bodyTop + rearHeight / 2f, rearHeight, gap)
bodyTop += rearHeight + gap
}
val floor = height - safe.bottom - reserve - pad
val bodyHeight = floor - bodyTop - gap
if (bodyHeight <= 0f) return elements
val hasLeftPad = presented.any { it.control == InputControl.LEFT_PAD && isStock(it) }
val hasRightPad = presented.any { it.control == InputControl.RIGHT_PAD && isStock(it) }
val hasLeftStick = presented.any { it.control == InputControl.LS && isStock(it) }
val hasRightStick = presented.any { it.control == InputControl.RS && isStock(it) }
val four = hasLeftPad && hasLeftStick || hasRightPad && hasRightStick
val main = min(w * .46f, bodyHeight * .53f)
val second = min(w * .42f, bodyHeight - main)
val mainY = floor - main / 2f
val secondY = bodyTop + second / 2f
val left = safe.left + w * .25f
val right = safe.left + w * .75f
if (four) {
val col = (w - 2f * pad - 3f * gap) / 4f
val stick = min(col, main)
put(InputControl.LEFT_PAD, Box(safe.left + pad + col * .5f, mainY, col, main))
put(InputControl.LS, Box(safe.left + pad + col * 1.5f + gap, mainY, stick, stick))
put(InputControl.RS, Box(safe.left + w - pad - col * 1.5f - gap, mainY, stick, stick))
put(InputControl.RIGHT_PAD, Box(safe.left + w - pad - col * .5f, mainY, col, main))
} else {
put(if (hasLeftPad) InputControl.LEFT_PAD else InputControl.LS, Box(left, mainY, main, main))
put(if (hasRightPad) InputControl.RIGHT_PAD else InputControl.RS, Box(right, mainY, main, main))
}
val radius = second / 2f
val armWidth = radius * if (kit.dpad == DpadStyle.CROSS) .37f else .25f
val inner = if (kit.dpad == DpadStyle.ARROWS) radius * .14f else armWidth
val depth = radius - inner
val distance = (radius + inner) / 2f
put(InputControl.UP, Box(left, secondY - distance, armWidth * 2f, depth))
put(InputControl.RIGHT, Box(left + distance, secondY, depth, armWidth * 2f))
put(InputControl.DOWN, Box(left, secondY + distance, armWidth * 2f, depth))
put(InputControl.LEFT, Box(left - distance, secondY, depth, armWidth * 2f))
val face = second * .34f
val spread = second * .30f
put(InputControl.Y, Box(right, secondY - spread, face, face))
put(InputControl.X, Box(right - spread, secondY, face, face))
put(InputControl.B, Box(right + spread, secondY, face, face))
put(InputControl.A, Box(right, secondY + spread, face, face))
if (!docked) {
val ids = listOf(KEYBOARD, "legacy:guide", "legacy:select", "legacy:start", "legacy:qam")
.filter { id -> presented.any { it.id == id } }
val inset = min(52f * density, w * .17f)
val rowWidth = (w - inset - pad - gap * (ids.size - 1)) / ids.size.coerceAtLeast(1)
val rowHeight = min(reserve * .8f, 44f * unit)
ids.forEachIndexed { i, id ->
val center = safe.left + inset + rowWidth / 2f + i * (rowWidth + gap)
buttons[id] = Box(center, height - safe.bottom - reserve / 2f, rowWidth, rowHeight)
}
}
return presented.map { element ->
val box = buttons[element.id]
if (box == null) element else element.copy(
x = box.left / width, y = box.top / height, width = box.width / width, height = box.height / height,
).bounded()
}
}
private fun isStock(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}"
private fun addOptional(elements: MutableList<InputSurfaceElement>, control: InputControl) {
if (elements.none { it.control == control && isStock(it) }) {
elements += InputSurfaceElement(control, 0f, 0f, 0f, 0f, floating = false,
buttonShape = InputButtonShape.PILL, showLabel = !control.isTrackpad)
}
}
private companion object {
const val KEYBOARD = "builtin:keyboard"
const val PANEL_DP = 504f
val REAR = listOf(InputControl.L4, InputControl.L5, InputControl.R5, InputControl.R4)
}
}
@@ -27,8 +27,9 @@ internal class FloatingSteamOverlay(width: Int, height: Int, safe: Rect, density
val lowered = if (lowerShortcuts) lower(visible) else visible
if (rearButtons != true && trackpads != true) return lowered
val placed = lowered.toMutableList()
val chosen = lowered.filter(::isStock).map { it.control }
fun add(control: InputControl, x: Float, y: List<Float>, widthDp: Int, heightDp: Int, shape: InputButtonShape) {
if (placed.any { it.id == "legacy:${control.id}" }) return
if (chosen.any { if (control in rear) it in rear else it.isTrackpad }) return
val element = InputSurfaceElement(control, 0f, 0f, (widthDp * dp / w).coerceAtLeast(.03f),
(heightDp * dp / h).coerceAtLeast(.03f), floating = false, buttonShape = shape, showLabel = !control.isTrackpad)
findSpace(element, x, y, placed)?.let(placed::add)
@@ -324,15 +324,27 @@ object InputLibraries {
layout.copy(screen = screen)
})
private fun encodeElements(list: List<InputSurfaceElement>) = JSONArray().also { elements ->
for (e in list) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
}
private fun decodeElements(array: JSONArray) = array.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))
}
internal fun encode(library: InputLibrary): String {
val layouts = JSONArray()
for (layout in library.layouts) {
val elements = JSONArray()
for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
val encoded = JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", encodeElements(layout.elements))
if (layout.rotated.isNotEmpty()) encoded.put("rotated", encodeElements(layout.rotated)).put("rotatedAspect", layout.rotatedAspect.toDouble()).put("rotatedScale", layout.rotatedScale.toDouble())
layouts.put(encoded
.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))
}
@@ -371,13 +383,7 @@ object InputLibraries {
require(version in 2..VERSION || restore)
val generated = mutableSetOf<String>()
val layouts = doc.getJSONArray("layouts").objects(256).map { layout ->
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))
}
val stored = decodeElements(layout.getJSONArray("elements"))
val id = layout.getString("id")
val origin = layout.optionalString("origin")
val followsGamepad = restore && !layout.optBoolean("kitless") &&
@@ -388,7 +394,8 @@ object InputLibraries {
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(), origin,
layout.optDouble("scale", 1.0).toFloat())
layout.optDouble("scale", 1.0).toFloat(), layout.optJSONArray("rotated")?.let(::decodeElements).orEmpty(),
layout.optDouble("rotatedAspect", 0.0).toFloat(), layout.optDouble("rotatedScale", 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)) }
@@ -22,6 +22,9 @@ data class SavedInputLayout(
val aspect: Float = 0f,
val origin: String? = null,
val scale: Float = 1f,
val rotated: List<InputSurfaceElement> = emptyList(),
val rotatedAspect: Float = 0f,
val rotatedScale: Float = 1f,
) {
val editable get() = template == InputLayoutTemplate.CUSTOM
val quickButtons get() = QUICK_BUTTONS.filter { button -> elements.any { it.quickButton == button } }
@@ -249,6 +252,8 @@ data class InputLibrary(
for (layout in layouts) {
require(layout.style.opacity in 1..100 && layout.style.hidden.all { it in QUICK_BUTTONS })
require(layout.aspect == 0f || layout.aspect.isFinite() && layout.aspect in .05f..20f)
require(layout.rotated.isEmpty() || layout.rotatedAspect.isFinite() && layout.rotatedAspect in .05f..20f && layout.rotatedScale.isFinite() && layout.rotatedScale in .5f..2f)
require(layout.rotated.size <= 64 && layout.rotated.all { r -> listOf(r.x, r.y, r.width, r.height).all { it.isFinite() } })
require(layout.scale.isFinite() && layout.scale in .5f..2f)
inputName(layout.name); require(layout.elements.size <= 64); unique(layout.elements.map { it.id })
for (e in layout.elements) {
@@ -197,19 +197,8 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
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 rescale(stored: List<InputSurfaceElement>, from: LegacyGamepadLayout): List<InputSurfaceElement> =
rescaleBetween(stored, from.elements(), elements())
fun buttonsOnly(stored: List<InputSurfaceElement>): List<InputSurfaceElement> {
val inset = dp(BUTTONS_ONLY_INSET_DP)
@@ -360,3 +349,22 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid
InputControl.R5 to GamepadGeometry.Slot.R5, InputControl.R4 to GamepadGeometry.Slot.R4)
}
}
internal fun rescaleBetween(stored: List<InputSurfaceElement>, from: List<InputSurfaceElement>, to: List<InputSurfaceElement>,
sizeFrom: List<InputSurfaceElement> = from, sizeTo: List<InputSurfaceElement> = to): List<InputSurfaceElement> {
val before = from.associateBy { it.id }
val after = to.associateBy { it.id }
val smaller = sizeFrom.associateBy { it.id }
val larger = sizeTo.associateBy { it.id }
return stored.map { e ->
val b = before[e.id] ?: return@map e
val a = after[e.id] ?: return@map e
val sb = smaller[e.id] ?: b
val sa = larger[e.id] ?: a
val w = (sa.width * e.width / sb.width).coerceIn(.03f, 1f)
val h = (sa.height * e.height / sb.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()
}
}
@@ -14,9 +14,6 @@ import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.ui.InputSurfaceView
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayout.Dock? = null) : FrameLayout(context) {
private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null)
@@ -75,15 +72,15 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
render()
}
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean)
private data class Placement(val layout: SavedInputLayout?, val width: Int, val height: Int, val safe: Rect, val buttonsOnly: Boolean,
val kit: PadKit?, val optional: Pair<Boolean?, Boolean?>)
private fun placed(): List<InputSurfaceElement> {
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly)
val optional = OnScreenLayout.optionalControls(context)
val key = Placement(layout, viewWidth, viewHeight, Rect(safe), isButtonsOnly, PadKit.forOverlay(context, layout), optional)
return placements.getOrPut(key) {
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, isButtonsOnly, dock,
rearButtons = SessionPrefs.oscRearButtons(context).takeIf { steam },
trackpads = SessionPrefs.oscTrackpads(context).takeIf { steam })
rearButtons = optional.first, trackpads = optional.second)
}
}
@@ -100,9 +97,9 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
private fun refreshAppearance() {
val style = layout?.style ?: InputSurfaceStyle()
val deck = dock == null && OnScreenLayout.usesSteamDeckButtons(context, layout)
surface.updateStyle(style, steamDeckButtons = deck)
quickToggle.tint = style.tint.takeUnless { deck }
val artwork = PadKit.forOverlay(context, layout)
surface.updateStyle(style, artwork)
quickToggle.tint = style.tint.takeUnless { artwork != null }
quickToggle.alpha = style.opacity / 100f
quickToggle.invalidate()
}
@@ -136,7 +133,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo
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 fresh = OnScreenLayout.safeInsets(insets, dock != null)
if (fresh != safe) {
safe.set(fresh)
render()
@@ -3,15 +3,14 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
object OnScreenLayout {
internal fun usesSteamDeckButtons(context: Context, layout: SavedInputLayout?) =
layout?.id == InputLibraries.OVERLAY && SessionPrefs.steamController(context) == SessionPrefs.CONTROLLER_DECK
internal fun supportsFloatingSteamControls(controller: String, layout: SavedInputLayout?) =
layout?.id == InputLibraries.OVERLAY &&
(controller == SessionPrefs.CONTROLLER_DECK || controller == SessionPrefs.CONTROLLER_STEAM)
@@ -31,41 +30,92 @@ object OnScreenLayout {
private const val TOLERANCE = .01f
private const val KEYBOARD_ID = "builtin:keyboard"
private val REAR = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)
fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect,
fun elements(context: Context, saved: SavedInputLayout?, width: Int, height: Int, safe: Rect,
buttonsOnly: Boolean = false, dock: Dock? = null, rearButtons: Boolean? = null,
trackpads: Boolean? = null): List<InputSurfaceElement> {
val stored = layout?.elements ?: return emptyList()
if (width <= 0 || height <= 0) return stored
if (saved == null) return emptyList()
if (width <= 0 || height <= 0) return saved.elements
val layout = oriented(saved, width, height)
val stored = layout.elements
val generator = LegacyGamepadLayout(context, width, height, safe, layout.scale)
val (reference, generated) = reference(context, layout, width, height)
val (reference, matched) = 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 generated = matched || PadKit.forOverlay(context, layout) != null && stored.any(::isGamepad) &&
(dock != null || height > width && layout.aspect >= 1f || height <= width && layout.aspect > 0f && layout.aspect < 1f)
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 {
val regenerated = when {
gamepad.isEmpty() -> emptyList()
dock != null -> generator.dock(gamepad, dock.portrait, dock.grips, dock.left, dock.right)
else -> generator.regenerate(gamepad)
}
val placed = regenerated + gamepad.filter { g -> dock == null && optional(g) && regenerated.none { it.id == g.id } }
val byId = (placed + others).associateBy { it.id }
val ordered = stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } }
if (dock != null || !supportsFloatingSteamControls(SessionPrefs.steamController(context), layout)) return ordered
if (generated && width >= height && usesSteamDeckButtons(context, layout) &&
val kit = PadKit.forOverlay(context, layout) ?: return ordered
if (generated &&
ControllerPrefs.layout(context, reference.first.toInt(), reference.second.toInt()).isEmpty() &&
ControllerPrefs.layout(context, width, height).isEmpty()) {
return SteamDeckOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
.place(ordered, rearButtons == true, trackpads == true)
if (dock != null || height > width) {
return ControllerPortraitGeometry(width.toFloat(), height.toFloat(), safe, context.resources.displayMetrics.density)
.place(ordered, kit, dock != null, layout.scale, rearButtons == true, trackpads == true)
}
return ControllerOverlayGeometry(width, height, safe, context.resources.displayMetrics, layout.scale)
.place(ordered, kit, rearButtons == true, trackpads == true)
}
if (dock != null || !kit.steam) return ordered
return FloatingSteamOverlay(width, height, safe, context.resources.displayMetrics.density)
.place(ordered, lowerShortcuts = generated, rearButtons = rearButtons, trackpads = trackpads)
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List<InputSurfaceElement> =
elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect())
fun oriented(layout: SavedInputLayout, width: Int, height: Int): SavedInputLayout {
val portrait = height > width
if (layout.rotated.isEmpty() || layout.aspect <= 0f || (layout.aspect < 1f) == portrait || (layout.rotatedAspect < 1f) != portrait) return layout
val rotated = layout.rotated.associateBy { it.id }
return layout.copy(elements = layout.elements.map { e -> rotated[e.id]?.let { e.copy(x = it.x, y = it.y, width = it.width, height = it.height) } ?: e } +
layout.rotated.filter { r -> optional(r) && layout.elements.none { it.id == r.id } },
aspect = layout.rotatedAspect, scale = layout.rotatedScale, rotated = emptyList(), rotatedAspect = 0f, rotatedScale = 1f)
}
fun withFrame(context: Context, saved: SavedInputLayout, elements: List<InputSurfaceElement>, aspect: Float, scale: Float = saved.scale): SavedInputLayout {
val (_, metrics) = InputLibraries.primaryDisplay(context)
val generated = generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels) != null
val portraitMain = saved.aspect > 0f && saved.aspect < 1f
if (aspect <= 0f || aspect >= 1f || portraitMain && !generated) {
val rotated = if (aspect >= 1f && portraitMain && !generated) Triple(saved.elements, saved.aspect, saved.scale) else Triple(saved.rotated, saved.rotatedAspect, saved.rotatedScale)
return saved.copy(elements = elements, aspect = aspect, scale = scale, rotated = rotated.first,
rotatedAspect = if (rotated.first.isEmpty()) 0f else rotated.second, rotatedScale = if (rotated.first.isEmpty()) 1f else rotated.third)
}
val main = if (portraitMain) 1f / saved.aspect else saved.aspect.takeIf { it > 0f } ?: (1f / aspect)
val ids = elements.associateBy { it.id }
val kept = saved.elements.mapNotNull { e -> ids[e.id]?.copy(x = e.x, y = e.y, width = e.width, height = e.height) }
val added = fit(elements.filter { d -> !optional(d) && saved.elements.none { it.id == d.id } }, aspect, 1f, (main * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
return saved.copy(elements = kept + added, aspect = main, rotated = elements, rotatedAspect = aspect, rotatedScale = scale)
}
fun optionalControls(context: Context): Pair<Boolean?, Boolean?> {
val steam = SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad
return SessionPrefs.oscRearButtons(context).takeIf { steam } to SessionPrefs.oscTrackpads(context).takeIf { steam }
}
fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false, safe: Rect = Rect()): List<InputSurfaceElement> {
val (rear, pads) = optionalControls(context)
return elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, safe,
rearButtons = rear, trackpads = pads)
}
fun editorFrame(layout: SavedInputLayout, displayed: List<InputSurfaceElement>): List<InputSurfaceElement> {
val byId = displayed.associateBy { it.id }
return layout.elements.map { byId[it.id] ?: it }
return layout.elements.map { byId[it.id] ?: it } + displayed.filter { d ->
optional(d) && layout.elements.none { it.id == d.id }
}
}
fun safeInsets(insets: android.view.WindowInsets?, docked: Boolean): Rect {
val cutout = if (android.os.Build.VERSION.SDK_INT >= 28) insets?.displayCutout else null
return Rect(cutout?.safeInsetLeft ?: 0, if (docked) 0 else cutout?.safeInsetTop ?: 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0)
}
fun fit(elements: List<InputSurfaceElement>, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List<InputSurfaceElement> {
@@ -91,6 +141,8 @@ object OnScreenLayout {
}
}
private fun optional(e: InputSurfaceElement) = e.id == "legacy:${e.control.id}" && (e.control.isTrackpad || e.control in REAR)
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>? =
@@ -0,0 +1,54 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
internal enum class FaceGlyphs { MONO_LETTERS, COLOR_LETTERS, COLOR_SYMBOLS, MONO_SYMBOLS }
internal enum class DpadStyle { CROSS, DISC, ARROWS }
internal enum class StickCap { RINGED, DISHED, KNURLED }
internal 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)
}
fun native(element: InputSurfaceElement) = element.id == "legacy:${element.control.id}" && element.icon == 0 &&
(element.name == element.control.label || element.name == name(element.control))
fun artwork(element: InputSurfaceElement) = element.image.isEmpty() && element.showLabel &&
(native(element) || element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD)
companion object {
fun forOverlay(context: Context, layout: SavedInputLayout?): PadKit? =
if (layout?.id != InputLibraries.OVERLAY) null else when (SessionPrefs.steamController(context)) {
SessionPrefs.CONTROLLER_DECK -> STEAM_DECK
SessionPrefs.CONTROLLER_STEAM -> STEAM_CONTROLLER
SessionPrefs.CONTROLLER_XBOX360 -> XBOX
SessionPrefs.CONTROLLER_DS4 -> DUALSHOCK
SessionPrefs.CONTROLLER_DUALSENSE -> DUALSENSE
else -> null
}
}
}
@@ -18,7 +18,6 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.session.SessionPrefs
@Composable
internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: String?, onManage: () -> Unit, onPick: () -> Unit) {
@@ -48,11 +47,10 @@ internal class InputLayoutPreviewView(context: Context) : View(context) {
fun update(layout: SavedInputLayout, role: InputRole) {
sourceHeight = if (role == InputRole.PRIMARY) 563 else 870
val primary = role == InputRole.PRIMARY
val steamOverlay = primary && OnScreenLayout.supportsFloatingSteamControls(SessionPrefs.steamController(context), layout)
val elements = if (steamOverlay) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements
val artwork = if (primary) PadKit.forOverlay(context, layout) else null
val elements = if (artwork != null) OnScreenLayout.editorElements(context, layout, 1000, sourceHeight) else layout.elements
renderer.updateCustomLayout(elements)
renderer.updateStyle(layout.style.copy(opacity = 100),
steamDeckButtons = primary && OnScreenLayout.usesSteamDeckButtons(context, layout))
renderer.updateStyle(layout.style.copy(opacity = 100), artwork)
renderer.measure(MeasureSpec.makeMeasureSpec(1000, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(sourceHeight, MeasureSpec.EXACTLY))
renderer.layout(0, 0, 1000, sourceHeight)
contentDescription = layout.name
@@ -278,7 +278,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
else InputHint(layout.name)
InputNavigationRow(stringResource(R.string.input_saved_layouts), stringResource(R.string.input_saved_layouts_hint)) { go(InputPage.LAYOUTS) }
if (layout.editable) {
if (!OnScreenLayout.usesSteamDeckButtons(context, layout)) {
if (PadKit.forOverlay(context, layout).let { kit -> role != InputRole.PRIMARY || kit == null || layout.elements.any { !kit.artwork(it) } }) {
InputColorRow(host, layout.style.tint) { color -> update { it.withLayout(layout.copy(style = layout.style.copy(tint = color))) } }
}
SliderRow(stringResource(R.string.ctrl_opacity), null, layout.style.opacity, 1..100, step = 1,
@@ -63,10 +63,17 @@ import com.droiddeck.launcher.session.SessionState
private data class SurfaceSnapshot(val elements: List<InputSurfaceElement>, val actions: Map<String, InputAction>,
val clicks: Map<String, InputAction>, val scale: Float, val aspect: Float)
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) {
private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int,
private val layout: SavedInputLayout) {
private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale)
val ids = generator(1f).elements().map { it.id }.toSet()
fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) = generator(to).rescale(stored, generator(from))
fun stock(scale: Float) = generator(scale).elements()
private fun placed(scale: Float) = OnScreenLayout.editorElements(context,
layout.copy(elements = stock(scale), aspect = 0f, rotated = emptyList(), scale = scale), width, height)
fun rescale(stored: List<InputSurfaceElement>, from: Float, to: Float) =
if (PadKit.forOverlay(context, layout) == null || OnScreenLayout.generatedSize(context, layout.copy(elements = stored, scale = from), width, height) != null)
generator(to).rescale(stored, generator(from))
else rescaleBetween(stored, placed(from), placed(to), stock(from), stock(to))
fun reset(stored: List<InputSurfaceElement>) = generator(1f).regenerate(stored).associateBy { it.id }.let { placed -> stored.map { placed[it.id] ?: it } }
}
@@ -78,13 +85,14 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
var clicks by mutableStateOf(preset.clicks)
var selected by mutableStateOf<String?>(null)
var toolsExpanded by mutableStateOf(false)
var toolsX by mutableFloatStateOf(.02f)
var toolsX by mutableFloatStateOf(-1f)
var toolsY by mutableFloatStateOf(.02f)
var snap by mutableStateOf(snap)
var adding by mutableStateOf(false)
var properties by mutableStateOf(false)
var clickProperties by mutableStateOf(false)
var history by mutableStateOf<List<SurfaceSnapshot>>(emptyList())
var canvas by mutableStateOf(IntSize.Zero)
var layoutScale by mutableFloatStateOf(layout.scale)
var aspect by mutableFloatStateOf(layout.aspect)
private var scaleBase by mutableStateOf<Triple<List<InputSurfaceElement>, List<InputSurfaceElement>, Float>?>(null)
@@ -92,7 +100,8 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true
val scale get() = when {
scaleBase?.second == elements -> scaleValue
rescales -> (layoutScale * 100).roundToInt()
rescales -> ((if (canvas.width > 0 && canvas.height > 0 && aspect > 0f && (aspect < 1f) != (canvasAspect < 1f))
OnScreenLayout.oriented(layout, canvas.width, canvas.height).scale else layoutScale) * 100).roundToInt()
else -> 100
}
val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) })
@@ -102,18 +111,29 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed
return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect())
}
val element get() = elements.firstOrNull { it.id == selected }
val element get() = elements.firstOrNull { it.id == selected } ?: shown.firstOrNull { it.id == selected }
val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect
fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) }
fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } }
private fun adoptDisplayedFrame(context: android.content.Context): Boolean {
if (canvas.width <= 0 || canvas.height <= 0 || shown.isEmpty() || aspect <= 0f || (aspect < 1f) == (canvasAspect < 1f)) return false
val open = toolsExpanded
beginEdit(shown, canvasAspect, gamepad?.let { GamepadScaler(context, canvas.width, canvas.height, layout) })
toolsExpanded = open
return true
}
fun beginEdit(displayed: List<InputSurfaceElement>, aspect: Float, scaler: GamepadScaler? = gamepad) {
checkpoint()
toolsExpanded = false
elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed)
if (this.aspect > 0f && aspect > 0f && (this.aspect < 1f) != (aspect < 1f)) layoutScale = OnScreenLayout.oriented(layout, (aspect * 1000).roundToInt(), 1000).scale
this.aspect = aspect
scaler?.let { gamepad = it }
}
fun scaleAll(percent: Int) {
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() }
fun scaleAll(context: android.content.Context, percent: Int) {
val adopted = adoptDisplayedFrame(context)
val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { if (!adopted) checkpoint() }
val factor = percent / 100f
val pad = gamepad
elements = if (base.third > 0f && pad != null) {
@@ -123,7 +143,47 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB
} else base.first.scaled(factor)
scaleValue = percent; scaleBase = Triple(base.first, elements, base.third)
}
fun resetPositions() { positioned?.let { checkpoint(); elements = it; if (rescales) layoutScale = 1f } }
var shown by mutableStateOf<List<InputSurfaceElement>>(emptyList())
private val canvasAspect get() = canvas.width.toFloat() / canvas.height.coerceAtLeast(1)
private fun stored(id: String): Boolean {
if (elements.any { it.id == id }) return true
if (shown.none { it.id == id }) return false
beginEdit(shown, canvasAspect)
return true
}
fun missing(context: android.content.Context): List<InputSurfaceElement> {
val pad = gamepad ?: return emptyList()
if (canvas.width <= 0 || canvas.height <= 0) return emptyList()
val ids = shown.map { it.id }.toSet()
return OnScreenLayout.editorElements(context, layout.copy(elements = pad.stock(layoutScale), aspect = 0f, rotated = emptyList(), scale = layoutScale),
canvas.width, canvas.height).filter { it.id !in ids }
}
fun restore(context: android.content.Context, element: InputSurfaceElement) {
val legacy = gamepad?.stock(layoutScale)?.firstOrNull { it.id == element.id }
val generated = OnScreenLayout.generatedSize(context, layout.copy(elements = elements), canvas.width, canvas.height) != null
if (generated && legacy != null) { checkpoint(); elements = elements + legacy }
else { beginEdit(shown, canvasAspect); elements = elements + element }
if (element.id == "builtin:keyboard" && actions[element.id] == null) actions = actions + (element.id to InputAction.Command(InputCommand.KEYBOARD))
selected = element.id
}
fun remove(id: String) {
if (elements.any { it.id == id }) checkpoint() else stored(id)
elements = elements.filterNot { it.id == id }; actions = actions - id; clicks = clicks - id; selected = null
}
fun update(element: InputSurfaceElement) {
stored(element.id)
elements = elements.map { if (it.id == element.id) element else it }
}
fun resetPositions(context: android.content.Context) {
val adopted = adoptDisplayedFrame(context)
positioned?.let { if (!adopted) checkpoint(); elements = it; if (rescales) layoutScale = 1f }
}
fun action(e: InputSurfaceElement) = preset.copy(elements = actions).action(e)
fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e)
}
@@ -142,7 +202,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val (display, metrics) = InputLibraries.primaryDisplay(context)
val gamepad = savedLayout.elements.takeIf { e -> e.any { it.id.startsWith("legacy:") } }?.let {
val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels)
GamepadScaler(display, w, h)
GamepadScaler(display, w, h, savedLayout)
}
val defaults = InputLibraries.defaultPositions(context, library, savedLayout)
SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context))
@@ -166,7 +226,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
InputLibraries.update(context) { latest ->
val l = latest.layouts.first { it.id == savedLayout.id }
val p = latest.preset(savedBindings.id)
latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
latest.withLayout(OnScreenLayout.withFrame(context, l, draft.elements, draft.aspect, draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } },
clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } }))
}
}.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
@@ -225,7 +285,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
else "${library.profile(profile).name} · ${roleLabel(role)}", onSave = { action ->
draft.checkpoint()
if (draft.clickProperties) draft.clicks = draft.clicks + (element.id to action) else draft.actions = draft.actions + (element.id to action)
draft.elements = draft.elements.map { if (it.id == element.id) properties.copy(name = properties.name.trim().ifBlank { element.name }) else it }
draft.update(properties.copy(name = properties.name.trim().ifBlank { element.name }))
draft.properties = false
})
}
@@ -245,7 +305,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
}
}
}
if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column {
if (draft.adding) AlertDialog(onDismissRequest = { draft.adding = false }, title = { Text(stringResource(R.string.input_add_element)) }, confirmButton = {}, text = { Column(Modifier.verticalScroll(rememberScrollState())) {
for (kind in InputElementKind.entries) PadTextButton(onClick = { draft.checkpoint()
val w = if (kind.control.dimensions == 2) .4f else .2f
val h = .3f
@@ -253,6 +313,11 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () ->
val element = InputSurfaceElement(kind.control, (1f - w) / 2, (1f - h) / 2, w, h, newInputId(), kind, name)
draft.elements = draft.elements + element; draft.selected = element.id
draft.adding = false; draft.toolsExpanded = false }) { Text(stringResource(kind.label())) }
val missing = remember(draft.elements, draft.canvas) { draft.missing(context) }
if (missing.isNotEmpty()) HorizontalDivider()
for (element in missing) PadTextButton(onClick = { draft.restore(context, element); draft.adding = false; draft.toolsExpanded = false }) {
Text(PadKit.forOverlay(context, savedLayout)?.name(element.control)?.takeIf { element.name == element.control.label } ?: element.name)
}
} })
if (discard) AlertDialog(onDismissRequest = { discard = false }, title = { Text(stringResource(R.string.input_editor_discard)) },
confirmButton = { PadTextButton(onClick = onDismiss) { Text(stringResource(R.string.common_ok)) } },
@@ -266,10 +331,12 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) {
AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"),
update = { view ->
view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13))
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout.copy(scale = draft.layoutScale); view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap
view.isEnabled = !draft.properties && !draft.adding
view.onSelect = { if (!draft.properties) draft.selected = it }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) }
view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h, draft.layout) else null) }
view.onResize = { w, h -> draft.canvas = IntSize(w, h) }
view.onDisplayed = { draft.shown = it }
view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } }
})
@@ -283,7 +350,8 @@ private fun FloatingSurfaceTools(draft: SurfaceDraft, onSave: () -> Unit, onLeav
val screenHeight = with(density) { maxHeight.toPx() }
val margin = with(density) { 8.dp.toPx() }
var panelSize by remember { mutableStateOf(IntSize.Zero) }
val x = (draft.toolsX * screenWidth).coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin))
val x = (if (draft.toolsX < 0f) (screenWidth - panelSize.width) / 2f else draft.toolsX * screenWidth)
.coerceIn(margin, (screenWidth - panelSize.width - margin).coerceAtLeast(margin))
val y = (draft.toolsY * screenHeight).coerceIn(margin, (screenHeight - panelSize.height - margin).coerceAtLeast(margin))
val position by rememberUpdatedState(Offset(x, y))
val expandedWidth = minOf(420.dp, maxWidth - 16.dp)
@@ -332,7 +400,7 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: ()
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = onLeave)
SecondaryButton(stringResource(R.string.input_editor_add), enabled = draft.elements.size < 64, compact = true) { draft.adding = true }
SecondaryButton(stringResource(R.string.input_editor_undo), enabled = draft.history.isNotEmpty(), compact = true) { draft.undo() }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions() }
if (draft.defaults != null) SecondaryButton(stringResource(R.string.input_reset_positions), enabled = draft.positioned != null, compact = true) { draft.resetPositions(context) }
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(draft.snap, { draft.snap = it; ControllerPrefs.setSnap(context, it) })
Text(stringResource(R.string.ctrl_editor_snap))
@@ -340,7 +408,7 @@ private fun SurfaceToolbar(draft: SurfaceDraft, onSave: () -> Unit, onLeave: ()
PrimaryButton(stringResource(R.string.input_editor_done), compact = true, onClick = onSave)
}
if (draft.elements.isNotEmpty()) SliderRow(stringResource(R.string.ctrl_size), null, draft.scale, 80..125, step = 5,
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(it) }
format = { "$it%" }, modifier = Modifier.testTag("input-editor-scale")) { draft.scaleAll(context, it) }
}
@OptIn(ExperimentalLayoutApi::class)
@@ -352,9 +420,7 @@ private fun SurfaceSelection(draft: SurfaceDraft) {
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
PrimaryButton(stringResource(R.string.input_properties), compact = true) { draft.clickProperties = false; draft.properties = true }
if (e.hasClick) SecondaryButton(stringResource(R.string.input_click_properties), compact = true) { draft.clickProperties = true; draft.properties = true }
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) {
draft.checkpoint(); draft.elements = draft.elements.filterNot { it.id == e.id }; draft.actions = draft.actions - e.id; draft.clicks = draft.clicks - e.id; draft.selected = null
}
SecondaryButton(stringResource(R.string.input_remove_element), compact = true) { draft.remove(e.id) }
}
} ?: Text(stringResource(R.string.input_editor_hint))
}
@@ -5,11 +5,14 @@ import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.widget.FrameLayout
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.SavedInputLayout
import com.droiddeck.launcher.input.InputSurfaceElement
import com.droiddeck.launcher.input.InputSurfaceStyle
@@ -39,6 +42,8 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
var onSelect: (String?) -> Unit = {}
var onBeginEdit: (List<InputSurfaceElement>, Int, Int) -> Unit = { _, _, _ -> }
var onChange: (InputSurfaceElement) -> Unit = {}
var onResize: (Int, Int) -> Unit = { _, _ -> }
var onDisplayed: (List<InputSurfaceElement>) -> Unit = {}
private val preview = InputSurfaceView(context)
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density }
private val radius = 14 * resources.displayMetrics.density
@@ -56,19 +61,38 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) {
}
private fun updatePreviewStyle() {
preview.updateStyle(style, steamDeckButtons = OnScreenLayout.usesSteamDeckButtons(context, sourceLayout))
preview.updateStyle(style, PadKit.forOverlay(context, sourceLayout))
}
private var safe = Rect()
private var frameWidth = 0
private var frameHeight = 0
private fun refreshElements() {
visibleElements = sourceLayout?.let { layout ->
OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height)
OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), frameWidth, frameHeight, safe = safe)
} ?: elements
preview.updateCustomLayout(visibleElements)
onDisplayed(visibleElements)
}
override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets {
val fresh = OnScreenLayout.safeInsets(insets, false)
if (fresh != safe) { safe = fresh; refreshElements(); invalidate() }
return super.onApplyWindowInsets(insets)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (measuredWidth == frameWidth && measuredHeight == frameHeight) return
frameWidth = measuredWidth; frameHeight = measuredHeight
refreshElements()
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
refreshElements()
onResize(w, h)
}
override fun dispatchDraw(canvas: Canvas) {
@@ -37,6 +37,7 @@ import com.droiddeck.launcher.input.InputButtonIcons
import com.droiddeck.launcher.input.InputButtonShape
import com.droiddeck.launcher.input.InputButtonImages
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.pcKeyLabel
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.atan2
@@ -56,10 +57,10 @@ class InputSurfaceView(
private val elementSources = ArrayList<InputSurfaceSource>()
private var customCanvas: ViewGroup? = null
private val owners = HashMap<Int, View>()
private var steamDeckButtons = false
private val deckArt by lazy(LazyThreadSafetyMode.NONE) { SteamDeckButtonArt(context) }
private var deckDpad = emptyList<HoldButton>()
private val deckDpadBounds = RectF()
private var artwork: PadKit? = null
private val art by lazy(LazyThreadSafetyMode.NONE) { PadArt(context) }
private var artworkDpad = emptyList<HoldButton>()
private val artworkDpadBounds = RectF()
private var requestedLayout = customLayout
init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) }
@@ -138,11 +139,11 @@ class InputSurfaceView(
}
}
fun updateStyle(style: InputSurfaceStyle, steamDeckButtons: Boolean = false) {
if (surfaceStyle == style && this.steamDeckButtons == steamDeckButtons) return
internal fun updateStyle(style: InputSurfaceStyle, artwork: PadKit? = null) {
if (surfaceStyle == style && this.artwork == artwork) return
val relayout = surfaceStyle.hidden != style.hidden
surfaceStyle = style
this.steamDeckButtons = steamDeckButtons
this.artwork = artwork
if (relayout) updateCustomLayout(requestedLayout)
customCanvas?.let { canvas ->
for (i in 0 until canvas.childCount) styleElement(canvas.getChildAt(i))
@@ -181,7 +182,7 @@ class InputSurfaceView(
}
private fun renderCustom(pad: PadBridge?) {
deckDpad = emptyList()
artworkDpad = emptyList()
val canvas = object : ViewGroup(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val layout = customLayout
@@ -199,17 +200,18 @@ class InputSurfaceView(
val x = (width * e.x).toInt(); val y = (height * e.y).toInt()
child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight)
}
updateDeckDpad(this)
updateArtworkDpad(this)
}
override fun dispatchDraw(canvas: Canvas) {
if (steamDeckButtons && deckDpad.isNotEmpty()) {
val alpha = (deckDpad.first().alpha * 255f).toInt()
val kit = artwork
if (kit != null && artworkDpad.isNotEmpty()) {
val alpha = (artworkDpad.first().alpha * 255f).toInt()
val saved = if (alpha == 255) canvas.save()
else canvas.saveLayerAlpha(deckDpadBounds, alpha)
canvas.translate(deckDpadBounds.left, deckDpadBounds.top)
val held = deckDpad.foldIndexed(0) { i, bits, button -> if (button.highlighted) bits or (1 shl i) else bits }
deckArt.dpad(canvas, deckDpadBounds.width(), deckDpadBounds.height(), held)
else canvas.saveLayerAlpha(artworkDpadBounds, alpha)
canvas.translate(artworkDpadBounds.left, artworkDpadBounds.top)
val held = artworkDpad.foldIndexed(0) { i, bits, button -> if (button.highlighted) bits or (1 shl i) else bits }
art.dpad(canvas, artworkDpadBounds.width(), artworkDpadBounds.height(), kit, held)
canvas.restoreToCount(saved)
}
super.dispatchDraw(canvas)
@@ -220,7 +222,8 @@ class InputSurfaceView(
val source = pad?.let { InputSurfaceSource(it, inputRole, element).also { s -> elementSources += s } }
canvas.addView(when (element.kind) {
InputElementKind.STICK -> StickView(context, element, source, element.floating, element.hideWhenIdle && pad != null)
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel, source = source)
InputElementKind.TRACKPAD -> TrackpadView(context, element.control == InputControl.RIGHT_PAD, captioned = element.showLabel,
stock = element.id == "legacy:${element.control.id}", source = source)
InputElementKind.DPAD -> DirectionPad(context, element, source)
else -> HoldButton(context, element, source)
}.apply { tag = element; contentDescription = element.name; styleElement(this); source?.onStateChanged = { postInvalidate() } })
@@ -229,7 +232,7 @@ class InputSurfaceView(
customCanvas = canvas
}
private fun updateDeckDpad(canvas: ViewGroup) {
private fun updateArtworkDpad(canvas: ViewGroup) {
val buttons = DIRECTIONS.mapNotNull { direction ->
val index = customLayout.indexOfFirst { element ->
element.control == direction && classic(element) && element.buttonShape == InputButtonShape.CIRCLE &&
@@ -238,8 +241,13 @@ class InputSurfaceView(
}
canvas.getChildAt(index) as? HoldButton
}
deckDpad = emptyList()
if (buttons.size != DIRECTIONS.size) return
val previous = artworkDpad
artworkDpad = if (crossed(buttons)) buttons else emptyList()
if (artworkDpad != previous) (previous + artworkDpad).forEach { it.invalidate() }
}
private fun crossed(buttons: List<HoldButton>): Boolean {
if (buttons.size != DIRECTIONS.size) return false
val (up, right, down, left) = buttons
val centerX = (left.left + right.right) / 2f
val centerY = (up.top + down.bottom) / 2f
@@ -247,9 +255,9 @@ class InputSurfaceView(
kotlin.math.abs((down.left + down.right) / 2f - centerX) > 2f ||
kotlin.math.abs((left.top + left.bottom) / 2f - centerY) > 2f ||
kotlin.math.abs((right.top + right.bottom) / 2f - centerY) > 2f ||
up.bottom >= down.top || left.right >= right.left) return
deckDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
deckDpad = buttons
up.bottom >= down.top || left.right >= right.left) return false
artworkDpadBounds.set(left.left.toFloat(), up.top.toFloat(), right.right.toFloat(), down.bottom.toFloat())
return true
}
override fun onAttachedToWindow() {
@@ -395,14 +403,14 @@ class InputSurfaceView(
override fun onDraw(canvas: Canvas) {
val lit = highlighted
val classic = classic(element)
if (steamDeckButtons && element.image.isEmpty() && element.showLabel) {
if (this in deckDpad) return
val kit = artwork
if (kit != null && element.image.isEmpty() && element.showLabel) {
if (this in artworkDpad) return
if (element.id == "builtin:keyboard" && element.icon == InputButtonIcons.KEYBOARD) {
deckArt.keyboard(canvas, width, height, lit)
art.system(canvas, width.toFloat(), height.toFloat(), PadArt.Shape.ROUND, PadArt.Icon.KEYBOARD, lit)
return
}
val native = element.id == "legacy:${element.control.id}" && element.name == element.control.label && element.icon == 0
if (native && deckArt.button(canvas, width, height, element.control, lit)) return
if (kit.native(element) && art.button(canvas, width, height, element.control, kit, lit)) return
}
drawSurface(canvas, lit, element.buttonShape, classic)
val cx = width / 2f
@@ -452,11 +460,12 @@ class InputSurfaceView(
if (pressed) feedback(this, HapticFeedbackConstants.VIRTUAL_KEY)
if (!pressed && cancelled) source?.cancel() else source?.update(if (pressed) 1f else 0f)
invalidate()
if (steamDeckButtons && this in deckDpad) customCanvas?.invalidate()
if (artwork != null && this in artworkDpad) customCanvas?.invalidate()
}
}
private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean = true,
private inner class TrackpadView(context: Context, private val right: Boolean, private val captioned: Boolean,
private val stock: Boolean,
private val source: InputSurfaceSource? = null) : Surface(context) {
private var gestureX = 0f
private var gestureY = 0f
@@ -479,8 +488,8 @@ class InputSurfaceView(
private val glow = Paint(Paint.ANTI_ALIAS_FLAG)
override fun onDraw(canvas: Canvas) {
if (!captioned) {
deckArt.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY)
if (!captioned || stock && artwork?.steam == true) {
art.trackpad(canvas, width.toFloat(), height.toFloat(), touching || clicked, fingerX, fingerY)
return
}
drawSurface(canvas, clicked)
@@ -596,10 +605,11 @@ class InputSurfaceView(
if (hideWhenIdle && !touching) return
val cx = if (touching) originX else centreX()
val cy = if (touching) originY else height / 2f
if (steamDeckButtons && classic(element)) {
val kit = artwork
if (kit != null && classic(element)) {
val radius = min(width, height) / 2f - 2f * density
if (radius > 0f) {
deckArt.stick(canvas, cx, cy, radius, knobX, knobY, touching || clicking)
art.stick(canvas, cx, cy, radius, kit, knobX, knobY, touching || clicking)
if (element.showLabel) {
labelPaint.color = TEXT
drawDirectionLabels(canvas, source, false, cx, cy, radius * .66f, radius * .34f, labelPaint)
@@ -0,0 +1,378 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.DashPathEffect
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RadialGradient
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import com.droiddeck.launcher.input.DpadStyle
import com.droiddeck.launcher.input.FaceGlyphs
import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.StickCap
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
/** The on-screen controls' shared drawing: one glass material, shaped per virtual controller. */
internal class PadArt(context: Context) {
private val density = context.resources.displayMetrics.density
private val body = Paint(Paint.ANTI_ALIAS_FLAG)
private val shine = Paint(Paint.ANTI_ALIAS_FLAG)
private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) }
private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val path = Path()
private val arm = Path()
private val bar = Path()
private val rect = RectF()
private var shineTop = Float.NaN
private var shineHeight = Float.NaN
private fun dp(value: Float) = value * density
fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, kit: PadKit, pressed: Boolean): Boolean {
val w = width.toFloat()
val h = height.toFloat()
if (min(w, h) <= dp(4f)) return false
when (control) {
InputControl.A, InputControl.B, InputControl.X, InputControl.Y ->
face(canvas, w / 2f, h / 2f, min(w, h) / 2f - dp(2f), control, kit, pressed)
InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, kit, pressed)
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed)
InputControl.L3, InputControl.R3 -> small(canvas, w, h, control.label, pressed)
InputControl.SELECT, InputControl.START, InputControl.GUIDE, InputControl.QAM -> {
val (shape, icon) = systemLook(kit, control)
system(canvas, w, h, shape, icon, pressed)
}
else -> return false
}
return true
}
private fun systemLook(kit: PadKit, control: InputControl): Pair<Shape, Icon> = when {
kit.steam -> when (control) {
InputControl.SELECT -> Shape.CHIP to Icon.VIEW
InputControl.START -> Shape.CHIP to Icon.MENU
InputControl.GUIDE -> Shape.PILL to Icon.STEAM
else -> Shape.PILL to Icon.QAM
}
kit.playStation -> when (control) {
InputControl.SELECT -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.SHARE else Icon.CREATE
InputControl.START -> Shape.PILL to if (kit == PadKit.DUALSHOCK) Icon.OPTIONS else Icon.MENU
InputControl.GUIDE -> Shape.ROUND to Icon.HOME
else -> Shape.ROUND to Icon.QAM
}
else -> Shape.ROUND to when (control) {
InputControl.SELECT -> Icon.BACK
InputControl.START -> Icon.START
InputControl.GUIDE -> Icon.HOME
else -> Icon.QAM
}
}
fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) {
shape.computeBounds(rect, false)
body.color = if (pressed) PRESSED else tint
body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawPath(shape, body)
body.clearShadowLayer()
if (!pressed) {
if (rect.top != shineTop || rect.height() != shineHeight) {
shineTop = rect.top; shineHeight = rect.height()
shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP)
}
canvas.drawPath(shape, shine)
}
edge.color = if (pressed) EDGE_PRESSED else EDGE
edge.strokeWidth = dp(1.25f)
canvas.drawPath(shape, edge)
}
fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) }
fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW)
}
private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW)
}
fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) {
ink.textSize = size
val measured = ink.measureText(value)
if (measured > maxWidth) ink.textSize = size * maxWidth / measured
ink.color = color
canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink)
}
fun face(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, kit: PadKit, pressed: Boolean) {
glass(canvas, circle(cx, cy, r), pressed)
when (kit.face) {
FaceGlyphs.COLOR_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else SYMBOL_COLORS[control] ?: INK)
FaceGlyphs.MONO_SYMBOLS -> symbol(canvas, cx, cy, r, control, if (pressed) ON_ACCENT else INK_SOFT)
FaceGlyphs.COLOR_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else LETTER_COLORS[control] ?: INK)
FaceGlyphs.MONO_LETTERS -> text(canvas, control.label, cx, cy, r * .95f, if (pressed) ON_ACCENT else INK)
}
}
private fun symbol(canvas: Canvas, cx: Float, cy: Float, r: Float, control: InputControl, color: Int) {
val s = r * .4f
line.color = color; line.strokeWidth = r * .12f
when (control) {
InputControl.A -> { canvas.drawLine(cx - s, cy - s, cx + s, cy + s, line); canvas.drawLine(cx + s, cy - s, cx - s, cy + s, line) }
InputControl.B -> canvas.drawCircle(cx, cy, s * 1.05f, line)
InputControl.X -> canvas.drawRoundRect(RectF(cx - s * .95f, cy - s * .95f, cx + s * .95f, cy + s * .95f), s * .18f, s * .18f, line)
else -> canvas.drawPath(path.apply { reset(); moveTo(cx, cy - s * 1.1f); lineTo(cx + s * 1.1f, cy + s * .85f); lineTo(cx - s * 1.1f, cy + s * .85f); close() }, line)
}
}
fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, kit: PadKit, pressed: Boolean) {
val inset = dp(2f)
val l = inset; val t = inset; val r = w - inset; val b = h - inset
val trigger = control == InputControl.LT || control == InputControl.RT
val big = (b - t) * if (trigger) .9f else .62f
val small = dp(5f)
val left = control == InputControl.LT || control == InputControl.LB
glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed)
text(canvas, kit.label(control), w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f)
}
/** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */
fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val inset = dp(3f)
val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f)
val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f)
val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long
val cx = w / 2f; val cy = h / 2f
glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed)
text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT)
}
fun small(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val r = min(w, h) / 2f * VISUAL
glass(canvas, circle(w / 2f, h / 2f, r), pressed)
text(canvas, label, w / 2f, h / 2f, r * .62f, if (pressed) ON_ACCENT else INK)
}
enum class Shape { ROUND, PILL, CHIP }
enum class Icon { VIEW, MENU, QAM, KEYBOARD, BACK, START, CREATE, HOME, STEAM, SHARE, OPTIONS }
fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) {
val cx = w / 2f; val cy = h / 2f
val size = when (shape) {
Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f }
Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f }
Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f }
}
icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink)
}
fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) {
val u = size / 28f
line.color = color; line.strokeWidth = 3.2f * u
fill.color = color; fill.shader = null
when (icon) {
Icon.VIEW -> {
canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line)
fill.color = Color.argb(230, 14, 16, 20)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line)
}
Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line)
Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill)
Icon.KEYBOARD -> {
canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line)
for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill)
line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line)
}
Icon.BACK, Icon.START -> {
val f = if (icon == Icon.START) 1f else -1f
line.strokeWidth = 2.6f * u
canvas.drawPath(path.apply { reset(); moveTo(cx - 6 * f * u, cy - 8 * u); lineTo(cx + 7 * f * u, cy); lineTo(cx - 6 * f * u, cy + 8 * u); close() }, line)
}
Icon.CREATE -> {
line.strokeWidth = 2.8f * u
canvas.drawLine(cx - 8 * u, cy + 8 * u, cx - 2 * u, cy - 8 * u, line)
canvas.drawLine(cx + u, cy + 8 * u, cx + 4 * u, cy - 2 * u, line)
canvas.drawLine(cx + 8 * u, cy + 8 * u, cx + 9 * u, cy + 3 * u, line)
}
Icon.HOME -> canvas.drawPath(path.apply {
reset(); moveTo(cx - 13 * u, cy - u); lineTo(cx, cy - 13 * u); lineTo(cx + 13 * u, cy - u)
moveTo(cx - 9 * u, cy - 4 * u); lineTo(cx - 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy + 11 * u); lineTo(cx + 9 * u, cy - 4 * u)
}, line)
Icon.STEAM, Icon.SHARE, Icon.OPTIONS -> {
ink.letterSpacing = .12f
text(canvas, when (icon) { Icon.STEAM -> "STEAM"; Icon.SHARE -> "SHARE"; else -> "OPTIONS" }, cx, cy, 14 * u, color, size * 1.9f)
ink.letterSpacing = 0f
}
}
}
private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) {
val px = -dy; val py = dx
line.color = color; line.strokeWidth = width
canvas.drawPath(path.apply {
reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f)
lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k)
}, line)
}
private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply {
reset()
addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW)
bar.reset()
bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW)
op(bar, Path.Op.UNION)
}
/** [held] bits: up 1, right 2, down 4, left 8. */
fun dpad(canvas: Canvas, w: Float, h: Float, kit: PadKit, held: Int, chevrons: Boolean = true, ink: Int = INK) {
val cx = w / 2f; val cy = h / 2f
val s = min(w, h) / 2f - dp(3f)
if (s <= 0f) return
val dirs = arrayOf(floatArrayOf(0f, -1f), floatArrayOf(1f, 0f), floatArrayOf(0f, 1f), floatArrayOf(-1f, 0f))
when (kit.dpad) {
DpadStyle.CROSS, DpadStyle.DISC -> {
val disc = kit.dpad == DpadStyle.DISC
val arms = if (disc) s * .78f else s
val half = if (disc) s * .25f else s * .37f
if (disc) {
glass(canvas, circle(cx, cy, s), false)
fill.shader = null; fill.color = Color.argb(18, 255, 255, 255)
canvas.drawPath(cross(arm, cx, cy, arms, half, half * .5f), fill)
edge.color = Color.argb(56, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawPath(arm, edge)
} else glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false)
for (i in 0..3) {
val dx = dirs[i][0]; val dy = dirs[i][1]
val on = held and (1 shl i) != 0
if (on && half > dp(2f)) {
fill.shader = null; fill.color = PRESSED
val near = half + dp(1f); val far = arms - dp(2f); val side = half - dp(2f)
rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far, if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far,
if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near, if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near)
canvas.drawRoundRect(rect, half * .4f, half * .4f, fill)
}
val m = (arms + half) / 2f
if (chevrons) chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else ink, half * .17f)
}
if (!disc) { fill.shader = null; fill.color = Color.argb(18, 255, 255, 255); canvas.drawCircle(cx, cy, half * .36f, fill) }
}
DpadStyle.ARROWS -> {
fill.shader = null; fill.color = Color.argb(56, 0, 0, 0)
canvas.drawCircle(cx, cy, s, fill)
edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawCircle(cx, cy, s, edge)
val bw = s * .5f; val tip = s * .14f; val base = s * .38f; val top = s * .9f; val rc = s * .11f
for (i in 0..3) {
canvas.save()
canvas.rotate(i * 90f, cx, cy)
arm.reset()
arm.moveTo(cx, cy - tip); arm.lineTo(cx - bw / 2, cy - base); arm.lineTo(cx - bw / 2, cy - top + rc)
arm.quadTo(cx - bw / 2, cy - top, cx - bw / 2 + rc, cy - top); arm.lineTo(cx + bw / 2 - rc, cy - top)
arm.quadTo(cx + bw / 2, cy - top, cx + bw / 2, cy - top + rc); arm.lineTo(cx + bw / 2, cy - base); arm.close()
val on = held and (1 shl i) != 0
glass(canvas, arm, on)
val ty = cy - (base + top) / 2f; val ts = s * .07f
fill.shader = null; fill.color = if (on) ON_ACCENT else INK_SOFT
if (chevrons) canvas.drawPath(path.apply { reset(); moveTo(cx, ty - ts); lineTo(cx + ts, ty + ts * .7f); lineTo(cx - ts, ty + ts * .7f); close() }, fill)
canvas.restore()
}
}
}
}
fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kit: PadKit, kx: Float, ky: Float, active: Boolean) {
fill.alpha = 255
fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP)
fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawCircle(cx, cy, radius, fill)
fill.clearShadowLayer(); fill.shader = null
edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f)
canvas.drawCircle(cx, cy, radius, edge)
line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f)
for (i in 0 until 8) {
val a = i * Math.PI / 4
val c = cos(a).toFloat(); val n = sin(a).toFloat()
canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line)
}
if (active && (kx != 0f || ky != 0f)) {
val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat()
line.color = ACCENT; line.strokeWidth = dp(3f)
val r = radius - dp(2f)
canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line)
}
val k = radius * .46f
val x = cx + kx; val y = cy + ky
if (kit.stick == StickCap.RINGED) {
line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240); line.strokeWidth = dp(2.8f)
canvas.drawCircle(x, y, k * 1.14f, line)
}
glass(canvas, circle(x, y, k), false)
when (kit.stick) {
StickCap.DISHED -> {
fill.shader = RadialGradient(x, y - k * .1f, k * .74f, Color.argb(107, 0, 0, 0), Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(x, y, k * .74f, fill); fill.shader = null
edge.color = if (active) ACCENT else Color.argb(51, 255, 255, 255); edge.strokeWidth = dp(1f)
canvas.drawCircle(x, y, k * .74f, edge)
}
StickCap.KNURLED -> {
line.color = if (active) ACCENT else Color.argb(66, 255, 255, 255); line.strokeWidth = dp(2.3f)
line.pathEffect = DashPathEffect(floatArrayOf(dp(1.2f), dp(1.9f)), 0f)
canvas.drawCircle(x, y, k * .9f, line); line.pathEffect = null
fill.color = Color.argb(56, 0, 0, 0); canvas.drawCircle(x, y, k * .6f, fill)
}
StickCap.RINGED -> { edge.color = Color.argb(36, 255, 255, 255); edge.strokeWidth = dp(1f); canvas.drawCircle(x, y, k * .66f, edge) }
}
}
fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) {
val inset = dp(1.5f)
val radius = min(w, h) * .14f
fill.shader = null; fill.color = Color.argb(51, 14, 16, 20)
rect.set(inset, inset, w - inset, h - inset)
canvas.drawRoundRect(rect, radius, radius, fill)
edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255)
edge.strokeWidth = dp(if (touching) 1.5f else 1f)
canvas.drawRoundRect(rect, radius, radius, edge)
if (!touching) return
val glow = min(w, h) * .3f
fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(fx, fy, glow, fill); fill.shader = null
fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill)
}
companion object {
const val VISUAL = .72f
val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF)
val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F)
val INK = Color.rgb(0xF4, 0xF7, 0xFB)
val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB)
private val BODY = Color.argb(133, 14, 16, 20)
private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF)
private val SHINE = Color.argb(43, 255, 255, 255)
private val EDGE = Color.argb(77, 255, 255, 255)
private val EDGE_PRESSED = Color.argb(140, 255, 255, 255)
private val SHADOW = Color.argb(97, 0, 0, 0)
private val WELL_IN = Color.argb(140, 5, 7, 10)
private val WELL_OUT = Color.argb(71, 14, 16, 20)
private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF)
private val LETTER_COLORS = mapOf(InputControl.A to Color.rgb(0x5C, 0xCB, 0x5F), InputControl.B to Color.rgb(0xF0, 0x50, 0x4A),
InputControl.X to Color.rgb(0x4C, 0x9B, 0xF0), InputControl.Y to Color.rgb(0xF5, 0xC0, 0x2E))
private val SYMBOL_COLORS = mapOf(InputControl.A to Color.rgb(0x8D, 0xB4, 0xF2), InputControl.B to Color.rgb(0xF2, 0x61, 0x6B),
InputControl.X to Color.rgb(0xEE, 0x93, 0xD6), InputControl.Y to Color.rgb(0x45, 0xCB, 0xAA))
}
}
@@ -1,277 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RadialGradient
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import com.droiddeck.launcher.input.InputControl
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
internal class SteamDeckButtonArt(context: Context) {
private val density = context.resources.displayMetrics.density
private val body = Paint(Paint.ANTI_ALIAS_FLAG)
private val shine = Paint(Paint.ANTI_ALIAS_FLAG)
private val edge = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val ink = Paint(Paint.ANTI_ALIAS_FLAG).apply { textAlign = Paint.Align.CENTER; typeface = Typeface.create("sans-serif-medium", Typeface.BOLD) }
private val line = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
private val fill = Paint(Paint.ANTI_ALIAS_FLAG)
private val path = Path()
private val arm = Path()
private val bar = Path()
private val rect = RectF()
private var shineTop = Float.NaN
private var shineHeight = Float.NaN
private fun dp(value: Float) = value * density
private fun glass(canvas: Canvas, shape: Path, pressed: Boolean, tint: Int = BODY) {
shape.computeBounds(rect, false)
body.color = if (pressed) PRESSED else tint
body.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawPath(shape, body)
body.clearShadowLayer()
if (!pressed) {
if (rect.top != shineTop || rect.height() != shineHeight) {
shineTop = rect.top; shineHeight = rect.height()
shine.shader = LinearGradient(0f, rect.top, 0f, rect.top + rect.height() * .55f, SHINE, Color.TRANSPARENT, Shader.TileMode.CLAMP)
}
canvas.drawPath(shape, shine)
}
edge.color = if (pressed) EDGE_PRESSED else EDGE
edge.strokeWidth = dp(1.25f)
canvas.drawPath(shape, edge)
}
private fun circle(cx: Float, cy: Float, r: Float): Path = path.apply { reset(); addCircle(cx, cy, r, Path.Direction.CW) }
private fun roundRect(l: Float, t: Float, r: Float, b: Float, radius: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), radius, radius, Path.Direction.CW)
}
private fun corners(l: Float, t: Float, r: Float, b: Float, tl: Float, tr: Float, br: Float, bl: Float): Path = path.apply {
reset(); addRoundRect(RectF(l, t, r, b), floatArrayOf(tl, tl, tr, tr, br, br, bl, bl), Path.Direction.CW)
}
private fun text(canvas: Canvas, value: String, cx: Float, cy: Float, size: Float, color: Int, maxWidth: Float = Float.MAX_VALUE) {
ink.textSize = size
val measured = ink.measureText(value)
if (measured > maxWidth) ink.textSize = size * maxWidth / measured
ink.color = color
canvas.drawText(value, cx, cy - (ink.ascent() + ink.descent()) / 2f, ink)
}
fun button(canvas: Canvas, width: Int, height: Int, control: InputControl, pressed: Boolean): Boolean {
val w = width.toFloat()
val h = height.toFloat()
if (min(w, h) <= dp(4f)) return false
when (control) {
InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> {
val radius = min(w, h) / 2f - dp(2f)
glass(canvas, circle(w / 2f, h / 2f, radius), pressed)
text(canvas, control.label, w / 2f, h / 2f, radius * .95f, if (pressed) ON_ACCENT else INK)
}
InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT -> shoulder(canvas, w, h, control, pressed)
InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> grip(canvas, w, h, control.label, pressed)
InputControl.SELECT -> system(canvas, w, h, Shape.CHIP, Icon.VIEW, pressed)
InputControl.START -> system(canvas, w, h, Shape.CHIP, Icon.MENU, pressed)
InputControl.GUIDE -> system(canvas, w, h, Shape.PILL, Icon.STEAM, pressed)
InputControl.QAM -> system(canvas, w, h, Shape.PILL, Icon.QAM, pressed)
else -> return false
}
return true
}
fun keyboard(canvas: Canvas, w: Int, h: Int, pressed: Boolean) =
system(canvas, w.toFloat(), h.toFloat(), Shape.ROUND, Icon.KEYBOARD, pressed)
private fun shoulder(canvas: Canvas, w: Float, h: Float, control: InputControl, pressed: Boolean) {
val inset = dp(2f)
val l = inset; val t = inset; val r = w - inset; val b = h - inset
val trigger = control == InputControl.LT || control == InputControl.RT
val big = (b - t) * if (trigger) .9f else .62f
val small = dp(5f)
val left = control == InputControl.LT || control == InputControl.LB
glass(canvas, if (left) corners(l, t, r, b, big, small, small, small) else corners(l, t, r, b, small, big, small, small), pressed)
text(canvas, when (control) {
InputControl.LB -> "L1"
InputControl.RB -> "R1"
InputControl.LT -> "L2"
else -> "R2"
}, w / 2f, h / 2f, (b - t) * .46f, if (pressed) ON_ACCENT else INK, (r - l) * .8f)
}
/** A back grip: a capsule along the long side of its box, at most 2.2 times as long as it is thick. */
private fun grip(canvas: Canvas, w: Float, h: Float, label: String, pressed: Boolean) {
val inset = dp(3f)
val thick = (min(w, h) - 2 * inset).coerceAtLeast(1f)
val long = (max(w, h) - 2 * inset).coerceAtMost(thick * 2.2f)
val bw = if (w >= h) long else thick; val bh = if (w >= h) thick else long
val cx = w / 2f; val cy = h / 2f
glass(canvas, roundRect(cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2, thick / 2), pressed)
text(canvas, label, cx, cy, thick * .42f, if (pressed) ON_ACCENT else INK_SOFT)
}
private enum class Shape { ROUND, PILL, CHIP }
private enum class Icon { VIEW, MENU, QAM, KEYBOARD, STEAM }
private fun system(canvas: Canvas, w: Float, h: Float, shape: Shape, icon: Icon, pressed: Boolean, ink: Int = INK) {
val cx = w / 2f; val cy = h / 2f
val size = when (shape) {
Shape.ROUND -> { val r = min(w, h) / 2f * VISUAL; glass(canvas, circle(cx, cy, r), pressed); r * 1.2f }
Shape.PILL -> { val vh = min(h * VISUAL, w * VISUAL / 2.3f); val vw = vh * 2.3f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh / 2), pressed); vh * 1.1f }
Shape.CHIP -> { val vh = min(h * VISUAL, w * VISUAL / 1.9f); val vw = vh * 1.9f
glass(canvas, roundRect(cx - vw / 2, cy - vh / 2, cx + vw / 2, cy + vh / 2, vh * .32f), pressed); vh * 1.05f }
}
icon(canvas, cx, cy, size, icon, if (pressed) ON_ACCENT else ink)
}
private fun icon(canvas: Canvas, cx: Float, cy: Float, size: Float, icon: Icon, color: Int) {
val u = size / 28f
line.color = color; line.strokeWidth = 3.2f * u
fill.color = color; fill.shader = null
when (icon) {
Icon.VIEW -> {
canvas.drawRoundRect(RectF(cx - 12 * u, cy - 9 * u, cx + 3 * u, cy + 3 * u), 3 * u, 3 * u, line)
fill.color = Color.argb(230, 14, 16, 20)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, fill)
canvas.drawRoundRect(RectF(cx - 4 * u, cy - 3 * u, cx + 11 * u, cy + 9 * u), 3 * u, 3 * u, line)
}
Icon.MENU -> for (dy in intArrayOf(-7, 0, 7)) canvas.drawLine(cx - 11 * u, cy + dy * u, cx + 11 * u, cy + dy * u, line)
Icon.QAM -> for (dx in intArrayOf(-10, 0, 10)) canvas.drawCircle(cx + dx * u, cy, 3.4f * u, fill)
Icon.KEYBOARD -> {
canvas.drawRoundRect(RectF(cx - 16 * u, cy - 11 * u, cx + 16 * u, cy + 11 * u), 4.5f * u, 4.5f * u, line)
for (row in 0..1) for (col in 0..3) canvas.drawCircle(cx + (-9 + col * 6) * u, cy + (-4 + row * 5) * u, 1.7f * u, fill)
line.strokeWidth = 2.6f * u; canvas.drawLine(cx - 6 * u, cy + 6 * u, cx + 6 * u, cy + 6 * u, line)
}
Icon.STEAM -> {
ink.letterSpacing = .12f
text(canvas, "STEAM", cx, cy, 14 * u, color, size * 1.9f)
ink.letterSpacing = 0f
}
}
}
private fun chevron(canvas: Canvas, ax: Float, ay: Float, dx: Float, dy: Float, k: Float, color: Int, width: Float) {
val px = -dy; val py = dx
line.color = color; line.strokeWidth = width
canvas.drawPath(path.apply {
reset(); moveTo(ax - dx * k * .5f + px * k, ay - dy * k * .5f + py * k); lineTo(ax + dx * k * .6f, ay + dy * k * .6f)
lineTo(ax - dx * k * .5f - px * k, ay - dy * k * .5f - py * k)
}, line)
}
private fun cross(target: Path, cx: Float, cy: Float, s: Float, h: Float, rc: Float) = target.apply {
reset()
addRoundRect(RectF(cx - h, cy - s, cx + h, cy + s), rc, rc, Path.Direction.CW)
bar.reset()
bar.addRoundRect(RectF(cx - s, cy - h, cx + s, cy + h), rc, rc, Path.Direction.CW)
op(bar, Path.Op.UNION)
}
fun dpad(canvas: Canvas, w: Float, h: Float, held: Int) {
val cx = w / 2f
val cy = h / 2f
val arms = min(w, h) / 2f - dp(3f)
if (arms <= 0f) return
val half = arms * .37f
glass(canvas, cross(arm, cx, cy, arms, half, half * .43f), false)
for (i in 0..3) {
val dx = when (i) { 1 -> 1f; 3 -> -1f; else -> 0f }
val dy = when (i) { 0 -> -1f; 2 -> 1f; else -> 0f }
val on = held and (1 shl i) != 0
if (on && half > dp(2f)) {
fill.shader = null
fill.color = PRESSED
val near = half + dp(1f)
val far = arms - dp(2f)
val side = half - dp(2f)
rect.set(if (dx == 0f) cx - side else if (dx > 0) cx + near else cx - far,
if (dy == 0f) cy - side else if (dy > 0) cy + near else cy - far,
if (dx == 0f) cx + side else if (dx > 0) cx + far else cx - near,
if (dy == 0f) cy + side else if (dy > 0) cy + far else cy - near)
canvas.drawRoundRect(rect, half * .4f, half * .4f, fill)
}
val m = (arms + half) / 2f
chevron(canvas, cx + dx * m, cy + dy * m, dx, dy, half * .32f, if (on) ON_ACCENT else INK, half * .17f)
}
fill.shader = null
fill.color = Color.argb(18, 255, 255, 255)
canvas.drawCircle(cx, cy, half * .36f, fill)
}
fun stick(canvas: Canvas, cx: Float, cy: Float, radius: Float, kx: Float, ky: Float, active: Boolean) {
fill.alpha = 255
fill.shader = RadialGradient(cx, cy, radius, WELL_IN, WELL_OUT, Shader.TileMode.CLAMP)
fill.setShadowLayer(dp(2.5f), 0f, dp(1.5f), SHADOW)
canvas.drawCircle(cx, cy, radius, fill)
fill.clearShadowLayer(); fill.shader = null
edge.color = Color.argb(61, 255, 255, 255); edge.strokeWidth = dp(1.25f)
canvas.drawCircle(cx, cy, radius, edge)
line.color = Color.argb(71, 255, 255, 255); line.strokeWidth = dp(1.4f)
for (i in 0 until 8) {
val a = i * Math.PI / 4
val c = cos(a).toFloat(); val n = sin(a).toFloat()
canvas.drawLine(cx + c * (radius - dp(7f)), cy + n * (radius - dp(7f)), cx + c * (radius - dp(3.5f)), cy + n * (radius - dp(3.5f)), line)
}
if (active && (kx != 0f || ky != 0f)) {
val angle = Math.toDegrees(atan2(ky, kx).toDouble()).toFloat()
line.color = ACCENT; line.strokeWidth = dp(3f)
val r = radius - dp(2f)
canvas.drawArc(RectF(cx - r, cy - r, cx + r, cy + r), angle - 35f, 70f, false, line)
}
val k = radius * .46f
val x = cx + kx; val y = cy + ky
line.color = if (active) ACCENT else Color.argb(140, 226, 232, 240)
line.strokeWidth = dp(2.8f)
canvas.drawCircle(x, y, k * 1.14f, line)
glass(canvas, circle(x, y, k), false)
edge.color = Color.argb(36, 255, 255, 255)
edge.strokeWidth = dp(1f)
canvas.drawCircle(x, y, k * .66f, edge)
}
fun trackpad(canvas: Canvas, w: Float, h: Float, touching: Boolean, fx: Float, fy: Float) {
if (w <= 0f || h <= 0f) return
val inset = dp(1.5f)
val radius = min(w, h) * .14f
fill.shader = null; fill.color = Color.argb(51, 14, 16, 20)
rect.set(inset, inset, w - inset, h - inset)
canvas.drawRoundRect(rect, radius, radius, fill)
edge.color = if (touching) Color.argb(191, 0x1A, 0x9F, 0xFF) else Color.argb(51, 255, 255, 255)
edge.strokeWidth = dp(if (touching) 1.5f else 1f)
canvas.drawRoundRect(rect, radius, radius, edge)
if (!touching) return
val glow = min(w, h) * .3f
fill.shader = RadialGradient(fx, fy, glow, GLOW, Color.TRANSPARENT, Shader.TileMode.CLAMP)
canvas.drawCircle(fx, fy, glow, fill); fill.shader = null
fill.color = ACCENT; canvas.drawCircle(fx, fy, dp(5f), fill)
}
companion object {
private const val VISUAL = .72f
private val ACCENT = Color.rgb(0x1A, 0x9F, 0xFF)
private val ON_ACCENT = Color.rgb(0x03, 0x11, 0x1F)
val INK = Color.rgb(0xF4, 0xF7, 0xFB)
private val INK_SOFT = Color.argb(209, 0xF4, 0xF7, 0xFB)
private val BODY = Color.argb(133, 14, 16, 20)
private val PRESSED = Color.argb(235, 0x1A, 0x9F, 0xFF)
private val SHINE = Color.argb(43, 255, 255, 255)
private val EDGE = Color.argb(77, 255, 255, 255)
private val EDGE_PRESSED = Color.argb(140, 255, 255, 255)
private val SHADOW = Color.argb(97, 0, 0, 0)
private val WELL_IN = Color.argb(140, 5, 7, 10)
private val WELL_OUT = Color.argb(71, 14, 16, 20)
private val GLOW = Color.argb(140, 0x1A, 0x9F, 0xFF)
}
}
@@ -132,6 +132,7 @@ class InputLayoutToolsTest {
}
@Test fun aScaledGamepadStaysGeneratedAndRegeneratesOnRotation() {
com.droiddeck.launcher.session.SessionPrefs.setSteamController(context, com.droiddeck.launcher.session.SessionPrefs.CONTROLLER_NONE)
val (display, metrics) = InputLibraries.primaryDisplay(context)
val long = maxOf(metrics.widthPixels, metrics.heightPixels)
val short = minOf(metrics.widthPixels, metrics.heightPixels)
@@ -76,20 +76,21 @@ class OnScreenLayoutTest {
assertEquals(base, both.filter { it.control in standard })
}
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360)
assertEquals(original, placed(true, true))
assertEquals(original.map { it.id }, placed(true, true).map { it.id })
assertEquals(placed(false, false), placed(true, true))
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val edited = layout.copy(elements = layout.elements.map { e -> if (e.control == InputControl.START) e.copy(y = .3f) else e })
val edited = layout.copy(elements = layout.elements.map { e -> if (e.control == InputControl.START) e.copy(y = .3f) else e }, aspect = w.toFloat() / h)
val fitted = OnScreenLayout.elements(context, edited, w, h, safe)
assertTrue(fitted.single { it.control == InputControl.START }.y < .5f)
}
@Test fun theBuiltInGamepadIsRegeneratedForEverySizeWithoutStretching() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM)
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
val layout = gamepad()
for ((w, h) in listOf(1200 to 540, 540 to 1200, 900 to 850)) {
val placed = OnScreenLayout.elements(context, layout, w, h, Rect())
assertEquals(layout.elements.map { it.id }, placed.map { it.id })
assertOnlyShortcutPositionsChanged(LegacyGamepadLayout(context, w, h).regenerate(layout.elements), placed)
assertEquals(LegacyGamepadLayout(context, w, h).regenerate(layout.elements), placed)
for (id in listOf("legacy:a", "legacy:up", "legacy:guide")) assertSquare(placed.first { it.id == id }, w, h)
assertInside(placed, w, h)
}
@@ -97,10 +98,10 @@ class OnScreenLayoutTest {
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM)
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
val saved = gamepad().copy(elements = LegacyGamepadLayout(context, 2608, 1200).elements(), aspect = 2608f / 1200)
val placed = OnScreenLayout.elements(context, saved, 2048, 1200, Rect())
assertOnlyShortcutPositionsChanged(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed)
assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed)
}
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
@@ -175,7 +176,7 @@ class OnScreenLayoutTest {
}
@Test fun regenerationKeepsTheUsersButtonStylesAndRemovedButtons() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_STEAM)
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
val layout = gamepad().let { g -> g.copy(elements = g.elements.filterNot { it.id == "legacy:y" }.map { if (it.id == "legacy:a") it.copy(opacity = .4f, icon = 0, name = "Jump") else it }) }
val placed = OnScreenLayout.elements(context, layout, 2000, 1000, Rect())
assertNull(placed.firstOrNull { it.id == "legacy:y" })
@@ -196,8 +197,10 @@ class OnScreenLayoutTest {
assertEquals(control.id, x, cx, .01f)
assertEquals(control.id, y, cy, .01f)
}
assertCenter(InputControl.LT, 140f, 66f)
assertCenter(InputControl.LB, 140f, 148f)
assertCenter(InputControl.LT, 120f, 96f)
assertCenter(InputControl.LB, 310f, 96f)
assertCenter(InputControl.RB, 1290f, 96f)
assertCenter(InputControl.RT, 1480f, 96f)
assertCenter(InputControl.UP, 220f, 242.5f)
assertCenter(InputControl.RIGHT, 322.5f, 345f)
assertCenter(InputControl.LS, 290f, 640f)
@@ -276,6 +279,7 @@ class OnScreenLayoutTest {
}
@Test fun theUnfoldedStripUsesTheDockGeometryInLandscapeAndPortrait() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
for ((size, portrait) in listOf((2208 to 800) to false, (1080 to 1300) to true)) {
val (w, h) = size
val placed = OnScreenLayout.elements(context, gamepad(), w, h, Rect(), dock = OnScreenLayout.Dock(portrait, grips = true))
@@ -303,6 +307,41 @@ class OnScreenLayoutTest {
assertEquals(.1f * 2208f / 1768 / .2f, fitted.width * 2208 / (fitted.height * 800), .01f)
}
@Test fun thePortraitAndBelowGameKitsKeepDirectionalArtClearOfTheSticksAndFaceButtons() {
val directions = setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT)
val face = setOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y)
val types = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360,
SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE)
val layout = gamepad()
val w = 1080
for (type in types) {
SessionPrefs.setSteamController(context, type)
val steam = type == SessionPrefs.CONTROLLER_DECK || type == SessionPrefs.CONTROLLER_STEAM
val deckDock = if (steam) OnScreenLayout.Dock.deck(true, null) else OnScreenLayout.Dock(true, false)
for ((h, dock) in listOf(1920 to null, 1300 to deckDock, 385 to deckDock)) {
val placed = OnScreenLayout.elements(context, layout, w, h, Rect(), dock = dock,
rearButtons = true, trackpads = true)
assertInside(placed, w, h)
val dpad = placed.filter { it.control in directions }
assertEquals(4, dpad.size)
val rightEdge = dpad.maxOf { it.x + it.width }
val bottomEdge = dpad.maxOf { it.y + it.height }
assertTrue(type, placed.filter { it.control in face && it.id != "builtin:keyboard" }.all { it.x > rightEdge })
assertTrue(type, placed.filter { it.kind == InputElementKind.STICK || it.kind == InputElementKind.TRACKPAD }.all { it.y > bottomEdge })
if (dock == null) {
val row = placed.filter { it.control in shortcuts || it.id == "builtin:keyboard" }
assertEquals(5, row.size)
assertTrue(row.all { it.y > bottomEdge })
assertEquals(steam, placed.any { it.kind == InputElementKind.TRACKPAD })
} else {
assertFalse(placed.any { it.control == InputControl.GUIDE || it.control == InputControl.QAM })
assertEquals(steam, placed.any { it.kind == InputElementKind.TRACKPAD })
assertEquals(!steam, placed.any { it.control == InputControl.RS })
}
}
}
}
private val legacyKeys = "29+33:0.3,0.7,44::Find::0.6:1:1:1"
private fun importedOn(library: InputLibrary) = library.activeLayout(false, InputRole.PRIMARY)!!.elements.filter { it.id.startsWith("imported:") }
@@ -398,6 +437,7 @@ class OnScreenLayoutTest {
}
@Test fun aDeckStripPutsTheDeckGamepadSurfacesInTheStickSlotsAndOtherPadsKeepSticks() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_NONE)
val stock = InputStockLayouts.layouts().first { it.id == DeckPanel.GAMEPAD.layout }
val deck = OnScreenLayout.Dock.deck(false, stock)
assertEquals(OnScreenLayout.Dock(false, true, InputControl.LS, InputControl.RIGHT_PAD), deck)
@@ -454,4 +494,138 @@ class OnScreenLayoutTest {
assertEquals(InputStockLayouts.layouts().filter { it.id != DeckPanel.GAMEPAD.layout }.map { it.elements },
others.filter { l -> InputStockLayouts.layouts().any { it.id == l.id } }.map { it.elements })
}
private val kits = listOf(SessionPrefs.CONTROLLER_DECK, SessionPrefs.CONTROLLER_STEAM, SessionPrefs.CONTROLLER_XBOX360,
SessionPrefs.CONTROLLER_DS4, SessionPrefs.CONTROLLER_DUALSENSE)
private fun List<InputSurfaceElement>.at(control: InputControl) = single { it.id == "legacy:${control.id}" }
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun everyKitPutsTriggersBesideTheirBumpers() {
for (kit in kits) {
SessionPrefs.setSteamController(context, kit)
val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect(), rearButtons = true, trackpads = true)
val lt = placed.at(InputControl.LT); val lb = placed.at(InputControl.LB)
val rb = placed.at(InputControl.RB); val rt = placed.at(InputControl.RT)
for ((outer, inner) in listOf(lt to lb, rt to rb)) assertEquals(kit, outer.y + outer.height / 2f, inner.y + inner.height / 2f, .001f)
assertTrue(kit, lt.x + lt.width <= lb.x)
assertTrue(kit, rb.x + rb.width <= rt.x)
assertInside(placed, 1600, 900)
}
}
@Test @Config(qualifiers = "w1280dp-h800dp-land-mdpi")
fun tabletOverlaysStayInTheLowerHalfOfTheScreen() {
for (kit in kits) {
SessionPrefs.setSteamController(context, kit)
val placed = OnScreenLayout.elements(context, gamepad(), 1280, 800, Rect(), rearButtons = true, trackpads = true)
for (e in placed) assertTrue("$kit ${e.id}", e.y >= .45f)
assertInside(placed, 1280, 800)
}
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun phoneOverlaysStillUseTheFullHeight() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val placed = OnScreenLayout.elements(context, gamepad(), 1600, 900, Rect())
assertTrue(placed.at(InputControl.LT).y < .15f)
assertTrue(placed.at(InputControl.START).let { it.y + it.height } > .9f)
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun aLayoutEditedInOneOrientationKeepsTheKitInTheOther() {
for (kit in kits) {
SessionPrefs.setSteamController(context, kit)
val layout = gamepad()
val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect())
val moved = landscape.map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it }
val edited = layout.copy(elements = moved, aspect = 1600f / 900f)
assertEquals(kit, .5f, OnScreenLayout.elements(context, edited, 1600, 900, Rect()).at(InputControl.A).x, .001f)
val kitPortrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect())
val editedPortrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect())
for (control in listOf(InputControl.A, InputControl.LT, InputControl.RB, InputControl.LS, InputControl.UP))
assertEquals("$kit ${control.id}", kitPortrait.at(control), editedPortrait.at(control))
}
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun eachOrientationKeepsItsOwnEdits() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360)
val layout = gamepad()
val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect()).map { if (it.control == InputControl.A) it.copy(x = .5f, y = .5f) else it }
val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f)
val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect()).map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it }
val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f)
assertEquals(landscape.map { it.id to floatArrayOf(it.x, it.y).toList() }, both.elements.map { it.id to floatArrayOf(it.x, it.y).toList() })
val wide = OnScreenLayout.elements(context, both, 1600, 900, Rect())
val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect())
assertEquals(.5f, wide.at(InputControl.A).x, .001f)
assertEquals(.1f, tall.at(InputControl.B).x, .001f)
assertEquals(.2f, tall.at(InputControl.B).y, .001f)
val renamed = OnScreenLayout.withFrame(context, both, both.elements.map { if (it.control == InputControl.A) it.copy(name = "Jump") else it }, both.aspect)
assertEquals("Jump", OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.A).name)
assertEquals(.1f, OnScreenLayout.elements(context, renamed, 900, 1600, Rect()).at(InputControl.B).x, .001f)
val library = InputLibraries.read(context).withLayout(both)
assertEquals(both, InputLibraries.decode(InputLibraries.encode(library))!!.layouts.first { it.id == both.id })
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun aRemovedRearButtonStaysRemovedWhileTheOthersRemain() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val layout = gamepad()
val displayed = OnScreenLayout.elements(context, layout, 1600, 900, Rect(), rearButtons = true, trackpads = true)
val frozen = OnScreenLayout.editorFrame(layout, displayed).filterNot { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD }
val edited = layout.copy(elements = frozen, aspect = 1600f / 900f)
for ((w, h) in listOf(1600 to 900, 900 to 1600)) {
val placed = OnScreenLayout.elements(context, edited, w, h, Rect(), rearButtons = true, trackpads = true).map { it.control }
assertFalse(InputControl.L4 in placed)
assertFalse(InputControl.LEFT_PAD in placed)
assertTrue(InputControl.R5 in placed)
assertTrue(InputControl.RIGHT_PAD in placed)
}
val hidden = OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = false, trackpads = false).map { it.control }
assertFalse(InputControl.R5 in hidden)
assertFalse(InputControl.RIGHT_PAD in hidden)
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun aPortraitMainLayoutUsesTheStockControlsInLandscape() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360)
val layout = gamepad()
val portrait = OnScreenLayout.elements(context, layout, 900, 1600, Rect()).map { if (it.control == InputControl.A) it.copy(x = .1f, y = .1f) else it }
val edited = layout.copy(elements = portrait, aspect = 900f / 1600f)
assertEquals(OnScreenLayout.elements(context, layout, 1600, 900, Rect()), OnScreenLayout.elements(context, edited, 1600, 900, Rect()))
assertEquals(.1f, OnScreenLayout.elements(context, edited, 900, 1600, Rect()).at(InputControl.A).x, .001f)
}
@Test @Config(qualifiers = "w800dp-h450dp-land-320dpi")
fun aPortraitSaveKeepsOptionalControlsInThePortraitFrameOnly() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
val layout = gamepad()
val landscape = OnScreenLayout.elements(context, layout, 1600, 900, Rect())
val edited = OnScreenLayout.withFrame(context, layout, landscape, 1600f / 900f)
val portrait = OnScreenLayout.elements(context, edited, 900, 1600, Rect(), rearButtons = true, trackpads = true)
.map { if (it.control == InputControl.B) it.copy(x = .1f, y = .2f) else it }
assertTrue(portrait.any { it.control == InputControl.L4 })
val both = OnScreenLayout.withFrame(context, edited, portrait, 900f / 1600f)
assertTrue(both.elements.none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD })
assertTrue(both.rotated.any { it.control == InputControl.L4 })
assertEquals(OnScreenLayout.elements(context, edited, 1600, 900, Rect(), rearButtons = true, trackpads = true),
OnScreenLayout.elements(context, both, 1600, 900, Rect(), rearButtons = true, trackpads = true))
val tall = OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = true, trackpads = true)
for (control in listOf(InputControl.L4, InputControl.LEFT_PAD, InputControl.B)) assertEquals(control.id, portrait.at(control), tall.at(control))
assertTrue(OnScreenLayout.elements(context, both, 900, 1600, Rect(), rearButtons = false, trackpads = false)
.none { it.control == InputControl.L4 || it.control == InputControl.LEFT_PAD })
}
@Test fun stockControlsUseTheKitArtworkWhileAddedAndTrackpadControlsStillUseTheTint() {
for (kit in listOf(PadKit.XBOX, PadKit.DUALSENSE)) {
SessionPrefs.setSteamController(context, if (kit == PadKit.XBOX) SessionPrefs.CONTROLLER_XBOX360 else SessionPrefs.CONTROLLER_DUALSENSE)
val layout = gamepad()
assertTrue(kit.name, layout.elements.all { kit.artwork(it) })
val added = InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, "custom", name = "Fire")
assertFalse(kit.artwork(added))
assertFalse(kit.artwork(layout.elements.first { it.control == InputControl.A }.copy(image = "picture")))
}
}
}
@@ -522,6 +522,64 @@ class InputSettingsTest {
}
}
@Test fun buttonSizeShowsTheGamepadWhereItWillBeSaved() {
val library = InputLibraries.read(context)
val layout = library.layout("game", InputRole.PRIMARY)!!
assertEquals(InputLibraries.OVERLAY, layout.id)
val round = mutableStateOf(0)
compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } }
fun editor() = generateSequence(listOf<android.view.View>(ShadowDialog.getLatestDialog().window!!.decorView)) { views ->
views.filterIsInstance<android.view.ViewGroup>().flatMap { g -> (0 until g.childCount).map(g::getChildAt) }.ifEmpty { null }
}.flatten().filterIsInstance<InputSurfaceEditorView>().first()
val stock = compose.runOnIdle { editor().rendered() }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(95f) }
val scaled = compose.runOnIdle { editor().rendered() }
assertNotEquals(stock, scaled)
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle { assertEquals(.95f, InputLibraries.read(context).layouts.first { it.id == layout.id }.scale) }
compose.runOnIdle { round.value = 1 }
compose.runOnIdle { assertEquals(scaled, editor().rendered()) }
}
@Test @Config(qualifiers = "w468dp-h833dp-port-369dpi")
fun buttonSizeInPortraitKeepsLandscapeEditsWithoutARotatedFrame() {
val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y")
val gamepad = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!
val landscape = gamepad.copy(elements = gamepad.elements.map { if (it.id in face) it.copy(x = it.x + .012f, y = it.y + .017f) else it },
aspect = 1600f / 900f, rotated = emptyList(), rotatedAspect = 0f)
InputLibraries.update(context) { it.withLayout(landscape) }
val library = InputLibraries.read(context)
val round = mutableStateOf(0)
compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = landscape.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } } }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(90f) }
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle {
val saved = InputLibraries.read(context).layouts.first { it.id == landscape.id }
assertEquals(landscape.aspect, saved.aspect)
for (id in face) assertEquals(landscape.elements.first { it.id == id }.let { it.x to it.y }, saved.elements.first { it.id == id }.let { it.x to it.y })
assertTrue(saved.rotated.isNotEmpty() && saved.rotatedAspect < 1f)
assertEquals(landscape.scale, saved.scale)
assertEquals(.9f, saved.rotatedScale)
assertEquals(.9f, OnScreenLayout.oriented(saved, 900, 1600).scale)
assertEquals(landscape.scale, OnScreenLayout.oriented(saved, 1600, 900).scale)
}
compose.runOnIdle { round.value = 1 }
compose.onNodeWithTag("input-editor-tools").performClick()
val slider = compose.onNodeWithTag("input-editor-scale").performScrollTo()
assertEquals(90f, slider.fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsProperties.ProgressBarRangeInfo].current, .5f)
slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(80f) }
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle {
val saved = InputLibraries.read(context).layouts.first { it.id == landscape.id }
assertEquals(landscape.scale, saved.scale)
assertEquals(.8f, saved.rotatedScale)
}
}
@Test @Config(qualifiers = "w833dp-h468dp-land-369dpi")
fun buttonSizeKeepsMovedGamepadGroupsInShape() {
val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y")
@@ -1,15 +1,29 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.view.InputDevice
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.InputLibraries
import com.droiddeck.launcher.input.InputSurfaceElement
import com.droiddeck.launcher.input.OnScreenLayout
import com.droiddeck.launcher.input.PadKit
import com.droiddeck.launcher.input.SavedInputLayout
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@@ -18,8 +32,17 @@ class InputSurfaceEditorViewTest {
private val context get() = RuntimeEnvironment.getApplication()
private val layout = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .1f, .2f, .2f, .2f)), aspect = 2f)
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller", "session")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@After fun restoreSession() {
SessionState.deckPad = false
SessionState.mode = SessionService.MODE_STEAM
}
private fun view() = InputSurfaceEditorView(context).apply {
layout(0, 0, 1000, 1000)
place(1000, 1000)
sourceLayout = layout
aspect = layout.aspect
elements = layout.elements
@@ -27,13 +50,47 @@ class InputSurfaceEditorViewTest {
}
private fun center() = OnScreenLayout.editorElements(context, layout, 1000, 1000).first().let { (it.x + it.width / 2) * 1000 to (it.y + it.height / 2) * 1000 }
@Suppress("UNCHECKED_CAST")
private fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List<InputSurfaceElement>
private fun overlay() = InputLibraries.read(context).layouts.first { it.id == InputLibraries.OVERLAY }
private fun editor(layout: SavedInputLayout, w: Int, h: Int) = InputSurfaceEditorView(context).apply {
sourceLayout = layout
aspect = layout.aspect
elements = layout.elements
snap = false
place(w, h)
}
private fun field(target: Any, name: String) = target.javaClass.getDeclaredField(name).also { it.isAccessible = true }.get(target)
private fun InputSurfaceEditorView.controls() = (field(field(this, "preview")!!, "customCanvas") as ViewGroup).let { canvas -> (0 until canvas.childCount).map(canvas::getChildAt) }
private fun InputSurfaceEditorView.artworkDpad() = field(field(this, "preview")!!, "artworkDpad") as List<*>
private fun InputSurfaceEditorView.rects() = controls().map { listOf(it.left, it.top, it.width, it.height) }
private fun InputSurfaceEditorView.assertControlsDrawnWhereDisplayed() {
val shown = rendered()
val views = controls()
assertEquals(shown.size, views.size)
for ((e, v) in shown.zip(views)) {
assertEquals(e.id, e.x * width, v.left.toFloat(), 1f)
assertEquals(e.id, e.y * height, v.top.toFloat(), 1f)
assertEquals(e.id, e.width * width, v.width.toFloat(), 1f)
assertEquals(e.id, e.height * height, v.height.toFloat(), 1f)
}
}
private fun InputSurfaceEditorView.touch(action: Int, x: Float, y: Float) {
MotionEvent.obtain(0, 10, action, x, y, 0).also { onTouchEvent(it); it.recycle() }
}
private fun InputSurfaceEditorView.mouse(action: Int, x: Float, y: Float) {
val properties = MotionEvent.PointerProperties().apply { id = 0; toolType = MotionEvent.TOOL_TYPE_MOUSE }
val coords = MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f }
val buttons = if (action == MotionEvent.ACTION_UP) 0 else MotionEvent.BUTTON_PRIMARY
MotionEvent.obtain(0, 10, action, 1, arrayOf(properties), arrayOf(coords), 0, buttons, 1f, 1f, 0, 0, InputDevice.SOURCE_MOUSE, 0)
.also { dispatchTouchEvent(it); it.recycle() }
}
private fun InputSurfaceEditorView.centre(id: String) = rendered().first { it.id == id }.let { (it.x + it.width / 2) * width to (it.y + it.height / 2) * height }
@Test fun editingStartsInTheDisplayedFrame() {
val view = view()
var started: Pair<List<InputSurfaceElement>, Float>? = null
@@ -70,7 +127,112 @@ class InputSurfaceEditorViewTest {
view.elements = renamed
view.aspect = 2f
assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 1000, 1000), view.rendered())
view.layout(0, 0, 800, 1000)
view.place(800, 1000)
assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 800, 1000), view.rendered())
}
@Test fun theOverlayEditorDrawsTheKitArtworkWhereTheSessionPlacesIt() {
val layout = overlay()
assertNotNull(PadKit.forOverlay(context, layout))
val view = editor(layout, 2400, 1504)
assertEquals(OnScreenLayout.editorElements(context, layout, 2400, 1504), view.rendered())
view.assertControlsDrawnWhereDisplayed()
assertEquals(4, view.artworkDpad().size)
}
@Config(qualifiers = "xhdpi")
@Test fun controlsAddedForTheScreenAreDrawnOnTheFirstFrameInBothOrientations() {
SessionState.mode = SessionService.MODE_STEAM
SessionState.deckPad = true
SessionPrefs.setOscRearButtons(context, true)
SessionPrefs.setOscTrackpads(context, true)
val layout = overlay()
for ((w, h) in listOf(2400 to 1504, 1504 to 2400)) {
val view = editor(layout, w, h)
assertTrue(view.rendered().size > layout.elements.size)
view.assertControlsDrawnWhereDisplayed()
assertEquals(4, view.artworkDpad().size)
}
}
@Test fun displayedControlsStayPutAcrossRepeatedRefreshesAndResizes() {
val view = editor(overlay(), 2400, 1504)
val first = view.rendered()
val drawn = view.rects()
repeat(3) {
view.elements = view.elements
view.aspect = view.aspect
view.sourceLayout = view.sourceLayout
view.place(1504, 2400)
view.assertControlsDrawnWhereDisplayed()
view.place(2400, 1504)
assertEquals(first, view.rendered())
assertEquals(drawn, view.rects())
assertEquals(4, view.artworkDpad().size)
}
}
@Test fun dpadPiecesRedrawWhenTheyLeaveOrRejoinTheKitCross() {
val view = editor(overlay(), 2400, 1504)
val stock = view.rendered()
view.aspect = 2400f / 1504
val pieces = view.controls().filter { (it.tag as InputSurfaceElement).id in setOf("legacy:up", "legacy:right", "legacy:down", "legacy:left") }
assertEquals(4, pieces.size)
for ((moved, expected) in listOf(stock.map { if (it.id == "legacy:up") it.copy(y = it.y - .2f) else it } to 0, stock to 4)) {
pieces.forEach { shadowOf(it).clearWasInvalidated() }
view.elements = moved
view.place(2400, 1504)
assertEquals(expected, view.artworkDpad().size)
pieces.forEach { assertTrue((it.tag as InputSurfaceElement).id, shadowOf(it).wasInvalidated()) }
}
}
@Test fun draggingMovesTheTouchedControlByTheDragDistance() {
val view = editor(overlay(), 2400, 1504)
val a = view.rendered().first { it.id == "legacy:a" }
val changes = mutableListOf<InputSurfaceElement>()
view.onChange = { changes += it }
val (x, y) = view.centre(a.id)
view.touch(MotionEvent.ACTION_DOWN, x, y)
view.touch(MotionEvent.ACTION_MOVE, x - 240f, y - 150f)
view.touch(MotionEvent.ACTION_UP, x - 240f, y - 150f)
val moved = changes.last()
assertEquals(a.id, moved.id)
assertEquals(a.x - 240f / 2400, moved.x, .0001f)
assertEquals(a.y - 150f / 1504, moved.y, .0001f)
assertEquals(a.width, moved.width, .0001f)
}
@Test fun aMouseSelectsDragsAndResizesLikeATouch() {
val view = editor(overlay(), 2400, 1504)
val a = view.rendered().first { it.id == "legacy:a" }
val changes = mutableListOf<InputSurfaceElement>()
var selection: String? = null
view.onSelect = { selection = it }
view.onChange = { changes += it }
val (x, y) = view.centre(a.id)
view.mouse(MotionEvent.ACTION_DOWN, x, y)
view.mouse(MotionEvent.ACTION_UP, x, y)
assertEquals(a.id, selection)
view.mouse(MotionEvent.ACTION_DOWN, x, y)
view.mouse(MotionEvent.ACTION_MOVE, x - 240f, y)
view.mouse(MotionEvent.ACTION_UP, x - 240f, y)
assertEquals(a.x - 240f / 2400, changes.last().x, .0001f)
val right = (a.x + a.width) * 2400; val bottom = (a.y + a.height) * 1504
view.mouse(MotionEvent.ACTION_DOWN, right, bottom)
view.mouse(MotionEvent.ACTION_MOVE, right + 60f, bottom + 60f)
view.mouse(MotionEvent.ACTION_UP, right + 60f, bottom + 60f)
val resized = changes.last()
assertEquals(a.id, resized.id)
assertEquals(a.width + 60f / 2400, resized.width, .0001f)
assertEquals(a.height + 60f / 1504, resized.height, .0001f)
}
}
internal fun InputSurfaceEditorView.place(w: Int, h: Int) {
measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY))
layout(0, 0, w, h)
}
@Suppress("UNCHECKED_CAST")
internal fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List<InputSurfaceElement>
@@ -85,10 +85,12 @@ class InputSurfaceTouchTest {
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f))
assertTrue(state().isDown(PadState.A))
surface.updateStyle(InputSurfaceStyle(), steamDeckButtons = true)
assertEquals(shown, surface.shownElements)
assertTrue(surface.takesTouchAt(800f, 240f))
assertTrue(state().isDown(PadState.A))
for (artwork in PadKit.entries) {
surface.updateStyle(InputSurfaceStyle(), artwork)
assertEquals(shown, surface.shownElements)
assertTrue(surface.takesTouchAt(800f, 240f))
assertTrue(state().isDown(PadState.A))
}
touch(MotionEvent.ACTION_UP, 1 to (800f to 240f))
assertFalse(state().isDown(PadState.A))