feat(input): portrait pad under the game, kit-aware editor reset and leaner controller settings

This commit is contained in:
Kurt Himebauch committed 2026-11-18 19:06:54 -05:00
1 parent 0fba656ee2
commit 40665bbb1a
140 files changed
+1059 -2321

No files matched your search

@@ -0,0 +1,66 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.input.ControlsPresenter.Place
import com.droiddeck.launcher.input.ControlsPresenter.State
import com.droiddeck.launcher.input.OnScreenControls.Hidden
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.*
import org.junit.Test
class ControlsPresenterTest {
private val modes = listOf(SessionPrefs.OSC_AUTO, SessionPrefs.OSC_ALWAYS, SessionPrefs.OSC_NEVER)
private fun states() = sequence {
for (mode in modes) for (bits in 0 until 128) {
fun bit(i: Int) = bits and (1 shl i) != 0
yield(State(mode, desktop = bit(0), virtualPad = bit(1), covered = bit(2), controllerInUse = bit(3), hiddenByTap = bit(4),
steamLayout = bit(5), bottomScreen = bit(6)))
}
}
@Test fun everyStateGetsThePlanTheRulesDescribe() {
for (state in states()) {
val plan = ControlsPresenter.plan(state)
val off = state.covered || !state.virtualPad || state.mode == SessionPrefs.OSC_NEVER || state.mode == SessionPrefs.OSC_AUTO && state.desktop
if (off) {
assertEquals(state.toString(), ControlsPresenter.Plan(Place.NONE), plan)
assertFalse(plan.shown)
continue
}
val place = if (state.steamLayout) Place.STEAM else if (state.bottomScreen) Place.BOTTOM else Place.MAIN
val hidden = if (state.hiddenByTap) Hidden.BY_TAP else if (state.mode == SessionPrefs.OSC_AUTO && state.controllerInUse) Hidden.BY_CONTROLLER else null
assertEquals(state.toString(), ControlsPresenter.Plan(place, hidden), plan)
assertEquals(state.toString(), hidden == null, plan.shown)
}
}
private val playing = State(SessionPrefs.OSC_AUTO, desktop = false, virtualPad = true, covered = false, controllerInUse = false,
hiddenByTap = false, steamLayout = false, bottomScreen = false)
@Test fun autoHidesForAControllerButAlwaysKeepsTheControls() {
assertEquals(ControlsPresenter.Plan(Place.MAIN), ControlsPresenter.plan(playing))
assertEquals(Hidden.BY_CONTROLLER, ControlsPresenter.plan(playing.copy(controllerInUse = true)).hidden)
assertNull(ControlsPresenter.plan(playing.copy(mode = SessionPrefs.OSC_ALWAYS, controllerInUse = true)).hidden)
}
@Test fun aTapHideWinsOverAControllerHide() {
assertEquals(Hidden.BY_TAP, ControlsPresenter.plan(playing.copy(controllerInUse = true, hiddenByTap = true)).hidden)
assertEquals(Hidden.BY_TAP, ControlsPresenter.plan(playing.copy(mode = SessionPrefs.OSC_ALWAYS, hiddenByTap = true)).hidden)
}
@Test fun theSteamLayoutWinsOverTheBottomScreen() {
assertEquals(Place.STEAM, ControlsPresenter.plan(playing.copy(steamLayout = true, bottomScreen = true)).place)
assertEquals(Place.BOTTOM, ControlsPresenter.plan(playing.copy(bottomScreen = true)).place)
}
@Test fun theDesktopShowsControlsOnlyWhenAlwaysIsChosen() {
assertEquals(Place.NONE, ControlsPresenter.plan(playing.copy(desktop = true)).place)
assertEquals(Place.MAIN, ControlsPresenter.plan(playing.copy(desktop = true, mode = SessionPrefs.OSC_ALWAYS)).place)
}
@Test fun aCoveringPanelOrNoVirtualPadRemovesTheControls() {
assertEquals(Place.NONE, ControlsPresenter.plan(playing.copy(covered = true)).place)
assertEquals(Place.NONE, ControlsPresenter.plan(playing.copy(virtualPad = false, mode = SessionPrefs.OSC_ALWAYS)).place)
assertEquals(Place.NONE, ControlsPresenter.plan(playing.copy(mode = SessionPrefs.OSC_NEVER, steamLayout = true)).place)
}
}
@@ -58,25 +58,17 @@ class InputLayoutToolsTest {
@Test fun builtInGamepadDefaultsComeFromTheGamepadGenerator() {
val library = InputLibraries.read(context)
val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY }
val defaults = InputLibraries.defaultPositions(context, library, gamepad)!!.first
assertEquals(gamepad.elements.map { it.id }.toSet(), defaults.map { it.id }.toSet())
val (defaults, aspect) = InputLibraries.defaultPositions(context, library, gamepad)!!
assertTrue(gamepad.elements.isEmpty())
val (display, metrics) = InputLibraries.primaryDisplay(context)
val w = maxOf(metrics.widthPixels, metrics.heightPixels); val h = minOf(metrics.widthPixels, metrics.heightPixels)
assertEquals(KitLayout.elements(display, PadKit.current(context), w, h), defaults)
assertEquals(w.toFloat() / h, aspect, .0001f)
val copy = SavedInputLayout("mine", "Mine", origin = InputLibraries.OVERLAY)
assertEquals(defaults, InputLibraries.defaultPositions(context, library, copy)!!.first)
assertNull(InputLibraries.defaultPositions(context, library, SavedInputLayout("new", "New")))
}
@Test fun quickButtonsHideWithoutRemovingElementsAndPersist() {
val library = InputLibraries.read(context)
val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY }
assertTrue(InputCommand.KEYBOARD in gamepad.quickButtons)
assertTrue(InputLibraries.setQuickButton(context, gamepad.id, InputCommand.KEYBOARD, false))
val hidden = InputLibraries.read(context).layouts.first { it.id == gamepad.id }
assertEquals(gamepad.elements, hidden.elements)
assertEquals(setOf(InputCommand.KEYBOARD), hidden.style.hidden)
val shown = hidden.style.shown(hidden.elements)
assertEquals(gamepad.elements.filterNot { it.id == "builtin:keyboard" }, shown)
assertTrue(InputLibraries.setQuickButton(context, gamepad.id, InputCommand.KEYBOARD, true))
assertEquals(gamepad, InputLibraries.read(context).layouts.first { it.id == gamepad.id })
}
@Test fun onlySteamQuickAccessAndKeyboardCanBeHidden() {
val library = InputLibraries.read(context)
val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY }
@@ -87,35 +79,6 @@ class InputLayoutToolsTest {
assertFalse(InputSurfaceStyle(hidden = QUICK_BUTTONS.toSet()).hides(custom))
}
private fun overlapping(elements: List<InputSurfaceElement>, width: Int, height: Int): List<Pair<String, String>> {
fun round(e: InputSurfaceElement) = e.buttonShape == InputButtonShape.CIRCLE && e.kind != InputElementKind.STICK
val result = mutableListOf<Pair<String, String>>()
for ((i, a) in elements.withIndex()) for (b in elements.drop(i + 1)) {
val ax = (a.x + a.width / 2) * width; val ay = (a.y + a.height / 2) * height
val bx = (b.x + b.width / 2) * width; val by = (b.y + b.height / 2) * height
val hit = if (round(a) && round(b)) {
val ra = minOf(a.width * width, a.height * height) / 2; val rb = minOf(b.width * width, b.height * height) / 2
kotlin.math.hypot(ax - bx, ay - by) < ra + rb - .5f
} else kotlin.math.abs(ax - bx) < (a.width + b.width) * width / 2 - .5f && kotlin.math.abs(ay - by) < (a.height + b.height) * height / 2 - .5f
if (hit) result += a.id to b.id
}
return result
}
@Test fun generatedGamepadSpacingFollowsButtonSize() {
for ((w, h) in listOf(1920 to 1080, 1280 to 960)) {
val normal = LegacyGamepadLayout(context, w, h).elements()
for (scale in listOf(.8f, 1.25f)) {
val elements = LegacyGamepadLayout(context, w, h, scale = scale).elements()
assertEquals("$w x $h at $scale", emptyList<Pair<String, String>>(), overlapping(elements, w, h))
val face = listOf("legacy:a", "legacy:y").map { id -> elements.first { it.id == id } }
val faceNormal = listOf("legacy:a", "legacy:y").map { id -> normal.first { it.id == id } }
val gap = (face[0].y - face[1].y) / (faceNormal[0].y - faceNormal[1].y)
if (scale > 1f) assertTrue(gap > 1f) else assertTrue(gap < 1f)
}
}
}
@Test fun scalingACustomLayoutScalesTheGapsBetweenNeighbours() {
val left = listOf(InputSurfaceElement(InputControl.A, .05f, .5f, .08f, .1f, "one", name = "One"),
InputSurfaceElement(InputControl.A, .16f, .5f, .08f, .1f, "two", name = "Two"))
@@ -131,87 +94,4 @@ class InputLayoutToolsTest {
}
}
@Test fun aScaledGamepadStaysGeneratedAndRegeneratesOnRotation() {
val (display, metrics) = InputLibraries.primaryDisplay(context)
val long = maxOf(metrics.widthPixels, metrics.heightPixels)
val short = minOf(metrics.widthPixels, metrics.heightPixels)
val gamepad = InputLibraries.read(context).layouts.first { it.id == InputLibraries.OVERLAY }
val scaled = gamepad.copy(scale = 1.25f, elements = LegacyGamepadLayout(display, long, short, scale = 1.25f).regenerate(gamepad.elements))
assertEquals(long to short, OnScreenLayout.generatedSize(context, scaled, long, short))
val rotated = OnScreenLayout.elements(context, scaled, short, long, android.graphics.Rect())
assertEquals(LegacyGamepadLayout(context, short, long, scale = 1.25f).regenerate(scaled.elements), rotated)
assertNull(OnScreenLayout.generatedSize(context, scaled.copy(scale = 1f), long, short))
InputLibraries.update(context) { it.withLayout(scaled) }
assertEquals(1.25f, InputLibraries.read(context).layouts.first { it.id == gamepad.id }.scale)
}
private fun assertCross(elements: List<InputSurfaceElement>, width: Int, height: Int, ids: List<String>) {
val (up, right, down, left) = ids.map { id -> elements.first { it.id == id }.let { (it.x + it.width / 2) * width to (it.y + it.height / 2) * height } }
val cx = (up.first + right.first + down.first + left.first) / 4
val cy = (up.second + right.second + down.second + left.second) / 4
assertEquals(up.first, down.first, 1f)
assertEquals(left.second, right.second, 1f)
assertTrue(up.second < down.second && left.first < right.first)
val reach = listOf(up, right, down, left).map { kotlin.math.hypot(it.first - cx, it.second - cy) }
reach.forEach { assertEquals(reach[0], it, 1f) }
}
private fun assertGamepadShape(elements: List<InputSurfaceElement>, width: Int, height: Int, label: String) {
assertCross(elements, width, height, listOf("legacy:y", "legacy:b", "legacy:a", "legacy:x"))
assertCross(elements, width, height, listOf("legacy:up", "legacy:right", "legacy:down", "legacy:left"))
assertEquals(label, emptyList<Pair<String, String>>(), overlapping(elements, width, height))
}
private fun assertStickView(elements: List<InputSurfaceElement>, width: Int, height: Int, label: String) {
for (control in listOf(InputControl.LS, InputControl.RS)) {
val stick = elements.first { it.control == control }
assertTrue("$label ${stick.id} keeps its widened travel width", stick.width * width >= stick.height * height * 1.25f - 1f)
assertTrue("$label ${stick.id} stays on screen", stick.x >= 0f && stick.x + stick.width <= 1.0001f)
}
}
@Test fun sticksKeepTheirFullViewAtSurfaceEdges() {
for ((width, height) in listOf(2608 to 1200, 1920 to 1080, 1280 to 960)) {
ControllerPrefs.setLayout(context, width, height, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f)))
val elements = LegacyGamepadLayout(context, width, height).elements()
assertStickView(elements, width, height, "$width x $height")
ControllerPrefs.resetLayout(context, width, height)
}
}
@Test @Config(qualifiers = "w833dp-h468dp-land-369dpi")
fun buttonSizeKeepsTheGamepadShapeAtHandheldDensity() {
for ((w, h) in listOf(1920 to 1080, 1920 to 1200)) {
val normal = LegacyGamepadLayout(context, w, h).elements()
assertGamepadShape(normal, w, h, "$w x $h")
val right = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y", "legacy:rs", "legacy:rb", "legacy:rt", "legacy:start")
val left = setOf("legacy:up", "legacy:right", "legacy:down", "legacy:left", "legacy:ls", "legacy:lb", "legacy:lt", "legacy:select")
val moved = normal.map { e ->
when (e.id) {
in right -> e.copy(x = e.x + 21f / w, y = e.y + 18f / h)
in left -> e.copy(x = e.x - 20f / w, y = e.y + 15f / h)
else -> e
}
}
for (scale in listOf(.8f, 1.25f)) {
val generator = LegacyGamepadLayout(context, w, h, scale = scale)
assertGamepadShape(generator.elements(), w, h, "$w x $h generated at $scale")
val rescaled = generator.rescale(moved, LegacyGamepadLayout(context, w, h))
assertGamepadShape(rescaled, w, h, "$w x $h moved at $scale")
val a = rescaled.first { it.id == "legacy:a" }
val generatedA = generator.elements().first { it.id == "legacy:a" }
assertEquals(generatedA.x + 21f / w, a.x, .001f)
assertEquals(generatedA.y + 18f / h, a.y, .001f)
assertEquals(moved, LegacyGamepadLayout(context, w, h).rescale(rescaled, generator).let { back ->
back.zip(moved).map { (b, m) -> if (kotlin.math.abs(b.x - m.x) < .001f && kotlin.math.abs(b.y - m.y) < .001f && kotlin.math.abs(b.width - m.width) < .001f) m else b }
})
}
}
}
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
fun wideHighDensityGamepadKeepsItsShape() {
val elements = LegacyGamepadLayout(context, 2608, 1200).elements()
assertGamepadShape(elements, 2608, 1200, "2608 x 1200")
}
}
@@ -237,144 +237,22 @@ class InputLibraryTest {
bindings = original.bindings.map { if (it.layoutId == InputLibraries.OVERLAY) it.copy(layoutId = null, elements = emptyMap(), clicks = emptyMap()) else it })
val raw = org.json.JSONObject(InputLibraries.encode(fixed)).put("version", 2).toString()
prefs.edit().putString("library", raw).commit()
ControllerPrefs.setStickClick(context, false)
ControllerPrefs.setKeyboardButton(context, true)
val size = context.resources.displayMetrics
ControllerPrefs.setLayout(context, size.widthPixels, size.heightPixels, mapOf("a" to (.5f to .5f), "ls" to (.3f to .4f)))
ControllerPrefs.setLayout(context, 1600, 900, mapOf("ls" to (.3f to .4f)))
LegacyControllerPrefs.setOpacity(context, 60)
val migrated = InputLibraries.read(context)
val saved = prefs.getString("library", null)
assertEquals(migrated, InputLibraries.read(context))
assertEquals(saved, prefs.getString("library", null))
assertFalse(migrated.layouts.any { it.template == InputLayoutTemplate.OVERLAY })
assertTrue(migrated.layouts.any { it.id == "migrated.layout.1600x900" })
assertEquals(original.layout("game", InputRole.SECONDARY), migrated.layout("game", InputRole.SECONDARY))
assertEquals(original.preset(original.profile("game").binding(InputRole.PHYSICAL)), migrated.preset(migrated.profile("game").binding(InputRole.PHYSICAL)))
val layout = migrated.layout("game", InputRole.PRIMARY)!!
val preset = migrated.preset(migrated.profile("game").binding(InputRole.PRIMARY))
assertTrue(layout.editable)
assertEquals(InputAction.Command(InputCommand.KEYBOARD), preset.elements["builtin:keyboard"])
assertEquals(InputAction.Disabled, preset.clickAction(layout.elements.first { it.control == InputControl.LS }))
}
@Test fun oldGamepadPlacementAndVisibilityBecomeEditableElements() {
ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (.4f to .5f)))
ControllerPrefs.setSteamButton(context, false)
ControllerPrefs.setTarget(context, "b", ControllerPrefs.OFF)
val elements = LegacyGamepadLayout(context, 1200, 800).elements()
val stick = elements.first { it.control == InputControl.LS }
assertEquals(.4f, stick.x + stick.width - stick.height * 800f / 1200f / 2f, .0001f)
assertEquals(.5f, stick.y + stick.height / 2f, .0001f)
assertFalse(elements.any { it.control == InputControl.GUIDE || it.control == InputControl.B })
assertTrue(elements.all { it == it.bounded() })
}
@Test fun gamepadControlsAreRoundWithShoulderPillsAndACompactKeyboard() {
val elements = LegacyGamepadLayout(context, 1200, 800).elements()
val density = context.resources.displayMetrics.density
for (element in elements.filter { it.id.startsWith("legacy:") }) {
val shoulder = element.control in setOf(InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT)
assertEquals(element.control.id, if (shoulder) InputButtonShape.PILL else InputButtonShape.CIRCLE, element.buttonShape)
}
val keyboard = elements.single { it.id == "builtin:keyboard" }
assertEquals(InputButtonIcons.KEYBOARD, keyboard.icon)
assertEquals(InputButtonShape.CIRCLE, keyboard.buttonShape)
assertEquals(36 * density / 1200f, keyboard.width, .0001f)
assertEquals(90 * density / 1200f, keyboard.x + keyboard.width / 2f, .0001f)
assertEquals(1f - 34 * density / 800f, keyboard.y + keyboard.height / 2f, .0001f)
}
@Test fun dpadButtonsMatchTheFaceButtonsInSizeAndSpacing() {
val elements = LegacyGamepadLayout(context, 1200, 800).elements()
fun centre(c: InputControl) = elements.single { it.id == "legacy:${c.id}" }.let { (it.x + it.width / 2f) * 1200 to (it.y + it.height / 2f) * 800 }
fun size(c: InputControl) = elements.single { it.id == "legacy:${c.id}" }.width * 1200
assertEquals(size(InputControl.A), size(InputControl.UP), .01f)
assertEquals(centre(InputControl.A).second - centre(InputControl.Y).second, centre(InputControl.DOWN).second - centre(InputControl.UP).second, .01f)
assertEquals(centre(InputControl.B).first - centre(InputControl.X).first, centre(InputControl.RIGHT).first - centre(InputControl.LEFT).first, .01f)
}
@Test fun anUntouchedSavedDpadIsResizedAroundItsCentreAndAMovedOneIsKept() {
val fresh = LegacyGamepadLayout(context, 1200, 800)
val target = fresh.elements().filter { it.control in setOf(InputControl.UP, InputControl.RIGHT, InputControl.DOWN, InputControl.LEFT) }
val cx = target.map { it.x + it.width / 2f }.average().toFloat()
val cy = target.map { it.y + it.height / 2f }.average().toFloat()
val scale = 26f / 30f
val old = target.map { e ->
val ex = cx + (e.x + e.width / 2f - cx) * 52f / 50f
val ey = cy + (e.y + e.height / 2f - cy) * 52f / 50f
e.copy(x = ex - e.width * scale / 2f, y = ey - e.height * scale / 2f, width = e.width * scale, height = e.height * scale, buttonShape = InputButtonShape.ROUNDED)
}
val restyled = fresh.restyle(old)
for ((want, got) in target.zip(restyled)) {
assertEquals(want.x, got.x, .0005f); assertEquals(want.y, got.y, .0005f)
assertEquals(want.width, got.width, .0005f); assertEquals(InputButtonShape.CIRCLE, got.buttonShape)
}
val moved = old.mapIndexed { i, e -> if (i == 0) e.copy(buttonShape = InputButtonShape.RECTANGLE) else e }
assertEquals(moved.drop(1).map { it.width }, fresh.restyle(moved).drop(1).map { it.width })
val shifted = old.mapIndexed { i, e -> if (i == 0) e.copy(x = e.x + .03f) else e }
assertEquals(shifted.map { listOf(it.x, it.y, it.width, it.height) }, fresh.restyle(shifted).map { listOf(it.x, it.y, it.width, it.height) })
}
@Test fun stickTouchAreasReachFurtherOutwardButKeepTheirInnerEdge() {
val elements = LegacyGamepadLayout(context, 1200, 800).elements()
for (control in listOf(InputControl.LS, InputControl.RS)) {
val stick = elements.single { it.control == control }
assertEquals(control.id, stick.height * 800f * 1.25f, stick.width * 1200f, 1f)
}
val left = elements.single { it.control == InputControl.LS }
val right = elements.single { it.control == InputControl.RS }
ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (.3f to .5f), "rs" to (.7f to .5f)))
val placed = LegacyGamepadLayout(context, 1200, 800).elements()
val ls = placed.single { it.control == InputControl.LS }
val rs = placed.single { it.control == InputControl.RS }
assertEquals(.3f, ls.x + ls.width - ls.height * 800f / 1200f / 2f, .0001f)
assertEquals(.7f, rs.x + rs.height * 800f / 1200f / 2f, .0001f)
assertTrue(left.width > left.height * 800f / 1200f && right.width > right.height * 800f / 1200f)
}
@Test fun adaptiveSticksToggleChangesOnlyTheSticksOfThatLayout() {
val library = InputLibraries.read(context)
val overlay = library.layouts.single { it.id == InputLibraries.OVERLAY }
assertEquals(true, overlay.adaptiveSticks)
InputLibraries.setAdaptiveSticks(context, overlay.id, false)
val off = InputLibraries.read(context)
val changed = off.layouts.single { it.id == overlay.id }
assertEquals(false, changed.adaptiveSticks)
assertFalse(ControllerPrefs.read(context).adaptiveSticks)
assertEquals(overlay.elements.filter { it.kind != InputElementKind.STICK }, changed.elements.filter { it.kind != InputElementKind.STICK })
assertEquals(library.layouts.filter { it.id != overlay.id }, off.layouts.filter { it.id != overlay.id })
assertNull(off.layouts.single { it.id == InputLibraries.DECK }.adaptiveSticks)
assertTrue(InputLibraries.setAdaptiveSticks(context, overlay.id, true))
assertEquals(true, InputLibraries.read(context).layouts.single { it.id == overlay.id }.adaptiveSticks)
prefs.edit().putString("library", JSONObject().put("version", 99).toString()).commit()
assertFalse(InputLibraries.setAdaptiveSticks(context, overlay.id, false))
assertTrue(ControllerPrefs.read(context).adaptiveSticks)
}
@Test fun savedGamepadsFromTheFirstUnifiedBuildGetTheRoundLookOnce() {
val fresh = InputLibraries.read(context)
val overlay = fresh.layouts.single { it.id == InputLibraries.OVERLAY }
val old = overlay.copy(elements = overlay.elements.map { e ->
if (e.id == "builtin:keyboard") InputSurfaceElement(InputControl.A, .02f, .9f, .12f, .08f, "builtin:keyboard", name = "Keyboard")
else if (e.control == InputControl.A) e.copy(buttonShape = InputButtonShape.RECTANGLE, x = .5f)
else e.copy(buttonShape = InputButtonShape.ROUNDED)
})
val custom = SavedInputLayout("mine", "Mine", listOf(InputSurfaceElement(InputControl.B, .1f, .1f, .1f, .1f)))
val stored = fresh.withLayout(old).withLayout(custom)
val renamed = InputSurfaceElement(InputControl.A, .02f, .9f, .12f, .08f, "builtin:keyboard", name = "Keys")
assertEquals(renamed, LegacyGamepadLayout(context, 1200, 800).restyle(listOf(renamed)).single())
prefs.edit().putString("library", JSONObject(InputLibraries.encode(stored)).put("version", 8).toString()).commit()
val upgraded = InputLibraries.read(context)
val restyled = upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.elements
assertEquals(overlay.elements.single { it.id == "builtin:keyboard" }, restyled.single { it.id == "builtin:keyboard" })
assertEquals(InputButtonShape.RECTANGLE, restyled.single { it.control == InputControl.A && it.id.startsWith("legacy:") }.buttonShape)
assertEquals(.5f, restyled.single { it.control == InputControl.A && it.id.startsWith("legacy:") }.x, .0001f)
assertEquals(InputButtonShape.PILL, restyled.single { it.control == InputControl.LB }.buttonShape)
assertEquals(InputButtonShape.CIRCLE, restyled.single { it.control == InputControl.UP }.buttonShape)
assertEquals(InputButtonShape.ROUNDED, upgraded.layouts.single { it.id == "mine" }.elements.single().buttonShape)
assertEquals(upgraded, InputLibraries.read(context))
for (desktop in listOf(false, true))
assertEquals(InputAction.Command(InputCommand.KEYBOARD), upgraded.compileActive(desktop).elementAction(InputRole.PRIMARY, "builtin:keyboard", InputControl.A))
assertTrue(OnScreenLayout.generated(layout))
assertEquals(60, layout.style.opacity)
assertEquals(InputAction.Command(InputCommand.KEYBOARD), migrated.compile("game").elementAction(InputRole.PRIMARY, KitLayout.KEYBOARD_ID, InputControl.A))
assertEquals(InputAction.Native(), migrated.compile("game").elementAction(InputRole.PRIMARY, KitLayout.DPAD_ID, InputControl.LS))
assertEquals(InputAction.Native(), preset.action(InputSurfaceElement(InputControl.A, .1f, .1f, .1f, .1f)))
}
@Test fun quickPartsAreModeSpecificAndDoNotEditSavedProfiles() {
@@ -505,7 +383,7 @@ class InputLibraryTest {
assertNull(fresh.layouts.single { it.id == InputLibraries.DECK }.style.tint)
assertNull(fresh.layouts.single { it.id == InputLibraries.TRACKPAD }.style.tint)
assertEquals(ControllerPrefs.STEAM_BLUE, fresh.layouts.single { it.id == InputLibraries.OVERLAY }.style.tint)
val red = ControllerPrefs.tints.last().first
val red = 0xFFFF6FB5.toInt()
val blue = fresh.layouts.map { it.copy(style = it.style.copy(tint = if (it.id == InputLibraries.TRACKPAD) red else ControllerPrefs.STEAM_BLUE)) }
val mine = SavedInputLayout("mine", "Mine", listOf(InputSurfaceElement(InputControl.B, .1f, .1f, .1f, .1f)))
val old = JSONObject(InputLibraries.encode(blue.fold(fresh) { library, layout -> library.withLayout(layout) }.withLayout(mine))).put("version", 8)
@@ -20,9 +20,9 @@ class InputProfilesTest {
}
@Test fun migrationKeepsLegacyTouchMappingSeparateFromPhysicalControls() {
ControllerPrefs.setTarget(context, "a", "b")
ControllerPrefs.setTarget(context, "x", "off")
ControllerPrefs.setSelectSteam(context, true)
LegacyControllerPrefs.setTarget(context, "a", "b")
LegacyControllerPrefs.setTarget(context, "x", "off")
LegacyControllerPrefs.setSelectSteam(context, true)
val game = InputProfiles.read(context, InputProfile.GAME)
assertEquals(InputAction.Native(InputControl.B), game.action(InputRole.PRIMARY, InputControl.A))
assertEquals(InputAction.Disabled, game.action(InputRole.PRIMARY, InputControl.X))
@@ -35,7 +35,7 @@ class InputProfilesTest {
}
@Test fun migrationPreservesSavedDesktopSelectBinding() {
ControllerPrefs.setSelectSteam(context, true)
LegacyControllerPrefs.setSelectSteam(context, true)
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().putString("profile.desktop",
"""{"version":1,"bindings":[{"role":"PHYSICAL","control":"select","action":{"type":"disabled"}}]}""").commit()
assertEquals(InputAction.Disabled, InputProfiles.read(context, InputProfile.DESKTOP)
@@ -68,9 +68,8 @@ class InputProfilesTest {
.putString("profile.game", """{"version":999,"bindings":[]} """).commit()
val profile = InputProfiles.read(context, InputProfile.GAME)
assertEquals(InputProfile.defaults(InputProfile.GAME).bindings, profile.bindings)
assertEquals(mapOf(
InputRole.PRIMARY to mapOf("builtin:keyboard" to InputAction.Command(InputCommand.KEYBOARD)),
), profile.elements)
assertEquals(InputProfile.defaults(InputProfile.GAME).elements, profile.elements)
assertEquals(InputAction.Command(InputCommand.KEYBOARD), profile.elementAction(InputRole.PRIMARY, KitLayout.KEYBOARD_ID, InputControl.A))
}
@Test fun layoutsPersistIndependentOfBindingsAndStayInsideScreen() {
@@ -0,0 +1,241 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import kotlin.math.hypot
private const val HANDHELD = "w833dp-h468dp-land-369dpi"
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, qualifiers = HANDHELD)
class KitLayoutTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
private val sizes = listOf(1080 to 1920, 1920 to 1080, 1240 to 1080, 2400 to 1080, 1080 to 2400, 1600 to 900, 1280 to 960)
private fun px(e: InputSurfaceElement, w: Int, h: Int) = floatArrayOf(e.x * w, e.y * h, e.width * w, e.height * h)
private fun centre(e: InputSurfaceElement, w: Int, h: Int) = (e.x + e.width / 2) * w to (e.y + e.height / 2) * h
private fun overlapping(elements: List<InputSurfaceElement>, w: Int, h: Int): List<Pair<String, String>> {
val result = mutableListOf<Pair<String, String>>()
for ((i, a) in elements.withIndex()) for (b in elements.drop(i + 1)) {
val (ax, ay) = centre(a, w, h); val (bx, by) = centre(b, w, h)
val round = a.buttonShape == InputButtonShape.CIRCLE && b.buttonShape == InputButtonShape.CIRCLE
val hit = if (round) hypot(ax - bx, ay - by) < (minOf(a.width * w, a.height * h) + minOf(b.width * w, b.height * h)) / 2 - .5f
else kotlin.math.abs(ax - bx) < (a.width + b.width) * w / 2 - .5f && kotlin.math.abs(ay - by) < (a.height + b.height) * h / 2 - .5f
if (hit) result += a.id to b.id
}
return result
}
private fun ids(kit: PadKit) = KitLayout.elements(context, kit, 1920, 1080).map { it.id }.toSet()
@Test fun everyKitHasTheCommonControlsOnceEach() {
val common = setOf("legacy:lt", "legacy:lb", "legacy:rt", "legacy:rb", "legacy:a", "legacy:b", "legacy:x", "legacy:y", "legacy:ls", "legacy:rs",
"legacy:select", "legacy:start", "legacy:guide", "legacy:qam", KitLayout.DPAD_ID, KitLayout.KEYBOARD_ID)
for (kit in PadKit.entries) {
val elements = KitLayout.elements(context, kit, 1920, 1080)
assertEquals(kit.name, elements.size, elements.map { it.id }.distinct().size)
assertTrue(kit.name, elements.map { it.id }.containsAll(common))
}
}
@Test fun steamKitsAddGripsAndTrackpadsAndTheOthersAddStickClicks() {
val grips = setOf("legacy:l4", "legacy:l5", "legacy:r4", "legacy:r5")
val pads = setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD)
val clicks = setOf("legacy:l3", "legacy:r3")
for (kit in PadKit.entries) {
val elements = KitLayout.elements(context, kit, 1920, 1080)
assertEquals(kit.name, kit.steam, elements.map { it.id }.containsAll(grips))
assertEquals(kit.name, if (kit.steam) pads else emptySet<InputControl>(), elements.filter { it.kind == InputElementKind.TRACKPAD }.map { it.control }.toSet())
assertEquals(kit.name, !kit.steam, elements.map { it.id }.containsAll(clicks))
assertTrue(kit.name, elements.none { kit.steam && it.id in clicks || !kit.steam && it.id in grips })
}
assertEquals(KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 1080), KitLayout.elements(context, PadKit.STEAM_CONTROLLER, 1920, 1080))
assertEquals(KitLayout.elements(context, PadKit.DUALSHOCK, 1920, 1080), KitLayout.elements(context, PadKit.DUALSENSE, 1920, 1080))
assertNotEquals(ids(PadKit.STEAM_DECK), ids(PadKit.XBOX))
}
@Test fun onlySticksFloatAndTheDpadAndKeyboardAreKitElements() {
for (kit in PadKit.entries) {
val elements = KitLayout.elements(context, kit, 1920, 1080)
for (e in elements) assertEquals(e.id, e.kind == InputElementKind.STICK, e.floating)
assertEquals(InputElementKind.DPAD, elements.single { it.id == KitLayout.DPAD_ID }.kind)
assertEquals(InputButtonIcons.KEYBOARD, elements.single { it.id == KitLayout.KEYBOARD_ID }.icon)
for (shoulder in listOf("legacy:lt", "legacy:lb", "legacy:rt", "legacy:rb")) assertEquals(InputButtonShape.PILL, elements.single { it.id == shoulder }.buttonShape)
}
}
@Test fun controlsStayOnScreenAndApartAtEverySize() {
for (kit in PadKit.entries) for ((w, h) in sizes) for (scale in listOf(.8f, 1f, 1.25f)) {
val elements = KitLayout.elements(context, kit, w, h, scale = scale)
for (e in elements) assertEquals("$kit $w x $h ${e.id}", e, e.bounded())
assertEquals("$kit $w x $h at $scale", emptyList<Pair<String, String>>(), overlapping(elements, w, h))
}
}
@Test fun buttonsAreRoundAndStayRoundOnEveryAspect() {
for (kit in PadKit.entries) for ((w, h) in sizes) {
for (e in KitLayout.elements(context, kit, w, h).filter { it.buttonShape == InputButtonShape.CIRCLE })
assertEquals("$kit $w x $h ${e.id}", e.width * w, e.height * h, 1f)
}
}
@Test fun theFaceButtonsFormACross() {
for (kit in PadKit.entries) {
val e = KitLayout.elements(context, kit, 2400, 1080).associateBy { it.id }
val (yx, yy) = centre(e.getValue("legacy:y"), 2400, 1080); val (ax, ay) = centre(e.getValue("legacy:a"), 2400, 1080)
val (xx, xy) = centre(e.getValue("legacy:x"), 2400, 1080); val (bx, by) = centre(e.getValue("legacy:b"), 2400, 1080)
assertEquals(yx, ax, .5f); assertEquals(xy, by, .5f)
assertTrue(yy < xy && xy < ay && xx < yx && yx < bx)
assertEquals(ay - yy, bx - xx, .5f)
}
}
@Test fun safeInsetsMoveEdgeControlsInByTheInsetOnly() {
val safe = Rect(120, 30, 60, 40)
for (kit in PadKit.entries) {
val plain = KitLayout.elements(context, kit, 2400, 1080).associateBy { it.id }
val inset = KitLayout.elements(context, kit, 2400, 1080, safe)
for (e in inset) {
val (x, y, ew, eh) = px(e, 2400, 1080).toList()
assertTrue("$kit ${e.id}", x >= safe.left - .5f && y >= safe.top - .5f && x + ew <= 2400 - safe.right + .5f && y + eh <= 1080 - safe.bottom + .5f)
}
val a = plain.getValue("legacy:lt"); val b = inset.single { it.id == "legacy:lt" }
assertEquals(safe.left.toFloat(), (b.x - a.x) * 2400, .5f)
assertEquals(safe.top.toFloat(), (b.y - a.y) * 1080, .5f)
val r = plain.getValue("legacy:rt"); val s = inset.single { it.id == "legacy:rt" }
assertEquals(-safe.right.toFloat(), (s.x - r.x) * 2400, .5f)
}
}
@Test fun widerScreensSpreadTheControlsInsteadOfStretchingThem() {
for (kit in PadKit.entries) {
val narrow = KitLayout.elements(context, kit, 1920, 1080).associateBy { it.id }
val wide = KitLayout.elements(context, kit, 2400, 1080).associateBy { it.id }
for ((id, n) in narrow) {
val v = wide.getValue(id)
assertEquals("$kit $id width", n.width * 1920, v.width * 2400, .5f)
assertEquals("$kit $id y", n.y * 1080, v.y * 1080, .5f)
val (nx, _) = centre(n, 1920, 1080); val (vx, _) = centre(v, 2400, 1080)
val shift = vx - nx
assertTrue("$kit $id moved $shift", listOf(0f, 240f, 480f).any { kotlin.math.abs(shift - it) < .5f })
}
}
}
@Test fun theCentreOfTheScreenStaysClear() {
for (kit in PadKit.entries) for ((w, h) in sizes.filter { it.first > it.second }) {
val box = android.graphics.RectF(w * .4f, h * .35f, w * .6f, h * .65f)
for (e in KitLayout.elements(context, kit, w, h)) {
val (x, y, ew, eh) = px(e, w, h).toList()
assertFalse("$kit $w x $h ${e.id}", android.graphics.RectF.intersects(box, android.graphics.RectF(x, y, x + ew, y + eh)))
}
}
}
@Test @Config(qualifiers = "mdpi")
fun aBigScreenCapsTheControlsAtAHandheldHeight() {
val metrics = context.resources.displayMetrics
val dpi = metrics.ydpi.takeIf { it > metrics.densityDpi * .6f && it < metrics.densityDpi * 1.6f } ?: metrics.densityDpi.toFloat()
val small = KitLayout.elements(context, PadKit.XBOX, 1600, 900).single { it.id == "legacy:a" }
val big = KitLayout.elements(context, PadKit.XBOX, 3200, 1800).single { it.id == "legacy:a" }
assertEquals(small.height * 900, big.height * 1800, 1f)
val mm = small.height * 900 / dpi * 25.4f
assertEquals(116f / 900f * 80f, mm, .3f)
}
@Test fun aHandheldScreenUsesTheFullReferenceSize() {
val a = KitLayout.elements(context, PadKit.XBOX, 1920, 1080).single { it.id == "legacy:a" }
assertEquals(116f * 1.2f, a.height * 1080, 1f)
}
@Test fun noDefaultControlSitsUnderTheCornerButton() {
val density = context.resources.displayMetrics.density
val corner = android.graphics.RectF(4 * density, 1080 - 52 * density, 52 * density, 1080 - 4 * density)
for (kit in PadKit.entries) for (e in KitLayout.elements(context, kit, 1920, 1080)) {
val (cx, cy) = centre(e, 1920, 1080)
val r = minOf(e.width * 1920, e.height * 1080) / 2
val nx = cx.coerceIn(corner.left, corner.right); val ny = cy.coerceIn(corner.top, corner.bottom)
val touches = if (e.buttonShape == InputButtonShape.CIRCLE) hypot(cx - nx, cy - ny) < r - 1f
else android.graphics.RectF.intersects(corner, android.graphics.RectF(e.x * 1920, e.y * 1080, (e.x + e.width) * 1920, (e.y + e.height) * 1080))
assertFalse("$kit ${e.id} is under the corner button", touches)
}
}
@Test fun clustersStayTogetherOnTallAndSquareScreens() {
val ratio = mapOf(PadKit.STEAM_DECK to 82f / 50f, PadKit.STEAM_CONTROLLER to 82f / 50f, PadKit.XBOX to 94f / 58f,
PadKit.DUALSHOCK to 92f / 56f, PadKit.DUALSENSE to 92f / 56f)
for (kit in PadKit.entries) for ((w, h) in listOf(1080 to 1920, 1240 to 1080, 2400 to 1080)) {
val e = KitLayout.elements(context, kit, w, h).associateBy { it.id }
val face = listOf("legacy:y", "legacy:x", "legacy:b", "legacy:a").map { centre(e.getValue(it), w, h) }
val cx = face.map { it.first }.average().toFloat(); val cy = face.map { it.second }.average().toFloat()
val radius = e.getValue("legacy:a").height * h / 2
for ((x, y) in face) assertEquals("$kit $w x $h", radius * ratio.getValue(kit), hypot(x - cx, y - cy), 1f)
if (kit == PadKit.XBOX) {
val (lx, ly) = centre(e.getValue("legacy:ls"), w, h); val (cx3, cy3) = centre(e.getValue("legacy:l3"), w, h)
val unit = e.getValue("legacy:ls").height * h / 208f
assertEquals("$w x $h", hypot(150f, 110f) * unit, hypot(cx3 - lx, cy3 - ly), 1f)
}
}
}
@Test @Config(qualifiers = "mdpi")
fun smallControlsKeepTheirShapeOnABigLowDensityScreen() {
for (kit in PadKit.entries) {
val elements = KitLayout.elements(context, kit, 1920, 1080)
for (e in elements.filter { it.buttonShape == InputButtonShape.CIRCLE }) assertEquals("$kit ${e.id}", e.width * 1920, e.height * 1080, 1f)
assertEquals(kit.name, emptyList<Pair<String, String>>(), overlapping(elements, 1920, 1080))
}
}
@Test fun theBottomLeftRowStartsRightOfTheCornerButtonWithGaps() {
val density = context.resources.displayMetrics.density
for (safe in listOf(Rect(), Rect(120, 0, 0, 40))) for (kit in PadKit.entries) for ((w, h) in sizes) {
val elements = KitLayout.elements(context, kit, w, h, safe)
val keyboard = elements.single { it.id == KitLayout.KEYBOARD_ID }
val row = elements.filter { e -> val cy = e.y + e.height / 2; cy > keyboard.y && cy < keyboard.y + keyboard.height && e.x + e.width / 2 < .5f }
.sortedBy { it.x }
assertEquals("$kit $w x $h", keyboard, row.first())
assertTrue("$kit $w x $h $safe keyboard at ${keyboard.x * w}", keyboard.x * w >= safe.left + 52 * density - .5f)
for ((a, b) in row.zipWithNext()) assertTrue("$kit $w x $h ${a.id} ${b.id}", (b.x - a.x - a.width) * w >= 8 * density - .5f)
}
}
@Test fun portraitSurfacesKeepEveryControlInTheBottomBlock() {
for (kit in PadKit.entries) for ((w, h) in listOf(1080 to 1920, 1200 to 2000)) {
val elements = KitLayout.elements(context, kit, w, h)
val unit = w / 1200f
val top = elements.minOf { it.y } * h
assertTrue("$kit $w x $h top $top", top >= h - 900 * unit - .5f)
assertEquals("$kit $w x $h", h.toFloat(), elements.maxOf { (it.y + it.height) * h }, 900 * unit * .1f)
val tall = KitLayout.elements(context, kit, w, h + 100).associateBy { it.id }
for (e in elements.filter { it.height > .031f && tall.getValue(it.id).height > .031f }) {
val t = tall.getValue(e.id)
assertEquals("$kit ${e.id}", (1 - e.y - e.height / 2) * h, (1 - t.y - t.height / 2) * (h + 100), 1f)
}
}
}
@Test fun anEmptySurfaceHasNoControls() {
assertTrue(KitLayout.elements(context, PadKit.STEAM_DECK, 0, 1080).isEmpty())
assertTrue(KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 0).isEmpty())
}
@Test fun theDockedStripAddsGripsOnlyForSteamKitsAndNeverSystemButtons() {
val density = context.resources.displayMetrics.density
for (kit in PadKit.entries) {
val placed = KitLayout.dock(context, kit, 1080, 1300, true, InputControl.LS, InputControl.RS)
val boxes = GamepadGeometry.layout(1080f, 1300f, density, true)
assertEquals(kit.name, kit.steam && boxes.containsKey(GamepadGeometry.Slot.L4), placed.any { it.control == InputControl.L4 })
assertNull(placed.firstOrNull { it.control == InputControl.GUIDE || it.control == InputControl.QAM })
assertEquals(1, placed.count { it.id == KitLayout.DPAD_ID })
assertTrue(placed.none { it.floating })
}
}
}
@@ -0,0 +1,14 @@
package com.droiddeck.launcher.input
import android.content.Context
/** Writes the controller settings older builds saved, so tests can seed the migrations that read them. */
internal object LegacyControllerPrefs {
private fun edit(context: Context) = ControllerPrefs.prefs(context).edit()
fun setTarget(context: Context, id: String, target: String) { edit(context).putString("map.$id", target).commit() }
fun target(context: Context, id: String): String = ControllerPrefs.read(context).mapping[id] ?: id
fun setSelectSteam(context: Context, on: Boolean) { edit(context).putBoolean("selectSteam", on).commit() }
fun setOpacity(context: Context, percent: Int) { edit(context).putInt("opacity", percent).commit() }
fun setStickClick(context: Context, on: Boolean) { edit(context).putBoolean("stickClick", on).commit() }
}
@@ -0,0 +1,129 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE)
class OnScreenControlPrefsTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
private val session get() = context.getSharedPreferences("session", Context.MODE_PRIVATE)
private val library get() = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
@Before fun reset() {
for (name in listOf("session", "game-controls", "input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun oldShowModesMapOntoAutoAlwaysAndNever() {
assertEquals(SessionPrefs.OSC_AUTO, SessionPrefs.oscMode(context))
for ((saved, mode) in listOf(SessionPrefs.OSC_AUTO to SessionPrefs.OSC_AUTO, SessionPrefs.OSC_ALWAYS to SessionPrefs.OSC_ALWAYS,
SessionPrefs.OSC_NEVER to SessionPrefs.OSC_NEVER, SessionPrefs.OSC_STEAM_QAM to SessionPrefs.OSC_ALWAYS,
SessionPrefs.OSC_STEAM_TOUCH to SessionPrefs.OSC_AUTO, "buttons" to SessionPrefs.OSC_AUTO)) {
session.edit().putString("osc", saved).commit()
assertEquals(saved, mode, SessionPrefs.oscMode(context))
}
}
@Test fun theOldSteamTouchModeBecomesTheSteamLayoutUntilChanged() {
assertFalse(SessionPrefs.steamTouchLayout(context))
session.edit().putString("osc", SessionPrefs.OSC_STEAM_TOUCH).commit()
assertTrue(SessionPrefs.steamTouchLayout(context))
SessionPrefs.setSteamTouchLayout(context, false)
assertFalse(SessionPrefs.steamTouchLayout(context))
session.edit().putString("osc", SessionPrefs.OSC_ALWAYS).putBoolean("steamTouchLayout", true).commit()
assertTrue(SessionPrefs.steamTouchLayout(context))
}
@Test fun eachGameKeepsItsOwnLayoutChoice() {
assertNull(GameControls.bindings(context, null))
assertNull(GameControls.bindings(context, 7))
GameControls.choose(context, 7, "mine.bindings", steam = false)
assertEquals("mine.bindings", GameControls.bindings(context, 7))
assertNull(GameControls.bindings(context, 8))
assertFalse(GameControls.steamLayout(context, 7))
GameControls.choose(context, 7, null, steam = true)
assertNull(GameControls.bindings(context, 7))
assertTrue(GameControls.steamLayout(context, 7))
}
@Test fun gamesWithoutAChoiceFollowTheDefaultSteamLayout() {
SessionPrefs.setSteamTouchLayout(context, true)
assertTrue(GameControls.steamLayout(context, null))
assertTrue(GameControls.steamLayout(context, 9))
GameControls.choose(context, 9, null, steam = false)
assertFalse(GameControls.steamLayout(context, 9))
assertTrue(GameControls.steamLayout(context, 10))
}
@Test fun kitElementsWithoutSavedBindingsGetTheirDefaultActions() {
val profile = InputProfile("empty")
assertEquals(InputAction.Native(), profile.elementAction(InputRole.PRIMARY, KitLayout.DPAD_ID, InputControl.LS))
assertEquals(InputAction.Command(InputCommand.KEYBOARD), profile.elementAction(InputRole.PRIMARY, KitLayout.KEYBOARD_ID, InputControl.A))
assertEquals(InputAction.Native(), profile.elementAction(InputRole.PRIMARY, "legacy:a", InputControl.A))
assertEquals(InputAction.Disabled, profile.elementAction(InputRole.PRIMARY, "custom:1", InputControl.A))
val mapped = profile.copy(bindings = mapOf(InputRole.PRIMARY to mapOf(InputControl.A to InputAction.Keys(listOf(57)))),
elements = mapOf(InputRole.PRIMARY to mapOf(KitLayout.KEYBOARD_ID to InputAction.Disabled)))
assertEquals(InputAction.Keys(listOf(57)), mapped.elementAction(InputRole.PRIMARY, "legacy:a", InputControl.A))
assertEquals(InputAction.Disabled, mapped.elementAction(InputRole.PRIMARY, KitLayout.KEYBOARD_ID, InputControl.A))
val bindings = SavedInputBindings("b", "B", false, "layout")
assertEquals(InputAction.Native(), bindings.action(InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, KitLayout.DPAD_ID, InputElementKind.DPAD)))
assertEquals(InputAction.Command(InputCommand.KEYBOARD), bindings.action(InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, KitLayout.KEYBOARD_ID)))
assertEquals(InputAction.Disabled, bindings.action(InputSurfaceElement(InputControl.A, 0f, 0f, .1f, .1f, "custom:1")))
}
private fun storeAt(version: Int, change: (InputLibrary) -> InputLibrary) {
val stored = change(InputLibraries.read(context))
library.edit().putString("library", JSONObject(InputLibraries.encode(stored)).put("version", version).toString()).commit()
}
@Test fun gamepadsSavedByTheOldEditorFollowTheKitAgainOnce() {
val placed = KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 1080)
val custom = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.B, .1f, .1f, .1f, .1f)), aspect = 2f)
storeAt(14) { lib ->
val overlay = lib.layouts.single { it.id == InputLibraries.OVERLAY }
lib.withLayout(overlay.copy(elements = placed, aspect = 16f / 9, scale = 1.25f))
.withLayout(SavedInputLayout("copy", "Copy", placed, aspect = 16f / 9, origin = InputLibraries.OVERLAY))
.withLayout(SavedInputLayout("migrated.layout.1600x900", "Gamepad", placed, aspect = 16f / 9))
.withLayout(custom)
}
val before = InputLibraries.decode(library.getString("library", null)!!)!!
val upgraded = InputLibraries.read(context)
for (id in listOf(InputLibraries.OVERLAY, "copy", "migrated.layout.1600x900")) {
val layout = upgraded.layouts.single { it.id == id }
assertTrue(id, layout.elements.isEmpty())
assertEquals(id, 0f, layout.aspect)
assertEquals(id, 1f, layout.scale)
assertTrue(id, OnScreenLayout.generated(layout))
}
assertNull(upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.origin)
assertEquals(InputLibraries.OVERLAY, upgraded.layouts.single { it.id == "migrated.layout.1600x900" }.origin)
assertEquals(custom, upgraded.layouts.single { it.id == "custom" })
for (id in listOf(InputLibraries.DECK, InputLibraries.TRACKPAD)) assertEquals(before.layouts.single { it.id == id }, upgraded.layouts.single { it.id == id })
assertEquals(upgraded, InputLibraries.read(context))
val edited = upgraded.withLayout(upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.copy(elements = placed, aspect = 16f / 9))
InputLibraries.update(context) { edited }
assertEquals(placed, InputLibraries.read(context).layouts.single { it.id == InputLibraries.OVERLAY }.elements)
}
@Test fun theKitUpgradeKeepsScreenKeysMergedIntoTheGamepad() {
val key = InputSurfaceElement(InputControl.A, .45f, .1f, .1f, .1f, "imported:0", name = "Find", alwaysShown = true)
storeAt(14) { lib ->
val overlay = lib.layouts.single { it.id == InputLibraries.OVERLAY }
val bindings = lib.preset(lib.activePart(false, InputRole.PRIMARY).bindings)
lib.withLayout(overlay.copy(elements = KitLayout.elements(context, PadKit.STEAM_DECK, 1920, 1080) + key, aspect = 16f / 9))
.withPreset(bindings.copy(elements = bindings.elements + (key.id to InputAction.Keys(listOf(29, 33)))))
}
val upgraded = InputLibraries.read(context)
assertEquals(listOf(key.id), upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.elements.map { it.id }.filter { it.startsWith("imported:") })
assertEquals(InputAction.Keys(listOf(29, 33)), upgraded.compileActive(false).elementAction(InputRole.PRIMARY, key.id, InputControl.A))
}
}
@@ -1,6 +1,13 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.os.Looper
import android.view.ViewConfiguration
import com.droiddeck.launcher.session.SessionPrefs
import java.time.Duration
import org.robolectric.Shadows.shadowOf
import org.robolectric.Robolectric
import androidx.activity.ComponentActivity
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
@@ -105,25 +112,11 @@ class OnScreenControlsTest {
view.updateLayout(SavedInputLayout("test", "Test", listOf(left.copy(floating = floating)), aspect = ASPECT))
measure(view)
touch(MotionEvent.ACTION_DOWN, 3 to (230f to 300f))
assertEquals(if (floating) 0f else .5f, state().leftX, .001f)
assertEquals(if (floating) 0f else .5f, state().leftX, .01f)
touch(MotionEvent.ACTION_UP, 3 to (230f to 300f))
}
}
@Test fun systemOnlyVisibilityMovesSteamAndQamToTheBottomCornersAndReleasesOtherButtons() {
val guide = InputSurfaceElement(InputControl.GUIDE, .4f, .7f, .1f, .2f)
view.updateLayout(SavedInputLayout("test", "Test", listOf(button, guide), aspect = ASPECT))
measure(view)
touch(MotionEvent.ACTION_DOWN, 0 to (800f to 250f))
view.setButtonsOnly(true)
measure(view)
assertFalse(state().isDown(PadState.A))
assertFalse(view.takesTouchAt(800f, 250f))
assertFalse(view.takesTouchAt(450f, 480f))
assertTrue(view.takesTouchAt(44f, 556f))
assertTrue(view.takesTouchAt(956f, 556f))
}
@Test fun aCancelledSecondFingerDoesNotArmAStickClick() {
touch(MotionEvent.ACTION_DOWN, 7 to (800f to 250f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (800f to 250f), 9 to (200f to 300f))
@@ -177,54 +170,99 @@ class OnScreenControlsTest {
assertFalse(state().isDown(PadState.L3))
}
@Test fun theQuickToggleHidesEverythingButTheKeyboardAndShowsItAgain() {
val keyboard = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, "builtin:keyboard", name = "Keyboard")
view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button, keyboard), aspect = ASPECT))
measure(view)
val density = context.resources.displayMetrics.density
val x = 34 * density
val y = 600 - 34 * density
assertTrue(view.takesTouchAt(x, y))
touch(MotionEvent.ACTION_UP, 4 to (x to y))
touch(MotionEvent.ACTION_DOWN, 5 to (x to y)); touch(MotionEvent.ACTION_CANCEL, 5 to (x to y)); touch(MotionEvent.ACTION_UP, 5 to (x to y))
assertFalse(view.isQuickHidden)
private val corner get() = 26 * context.resources.displayMetrics.density to 600 - 26 * context.resources.displayMetrics.density
private fun tapCorner() {
val (x, y) = corner
touch(MotionEvent.ACTION_DOWN, 1 to (x to y)); touch(MotionEvent.ACTION_UP, 1 to (x to y))
shadowOf(Looper.getMainLooper()).idle()
measure(view)
assertTrue(view.isQuickHidden)
assertFalse(view.takesTouchAt(800f, 250f))
assertTrue(view.takesTouchAt(450f, 270f))
touch(MotionEvent.ACTION_DOWN, 2 to (800f to 250f)); touch(MotionEvent.ACTION_UP, 2 to (800f to 250f))
assertTrue(view.isQuickHidden)
touch(MotionEvent.ACTION_DOWN, 3 to (x to y)); touch(MotionEvent.ACTION_UP, 3 to (x to y))
measure(view)
assertFalse(view.isQuickHidden)
assertTrue(view.takesTouchAt(800f, 250f))
view.setButtonsOnly(true)
measure(view)
touch(MotionEvent.ACTION_DOWN, 6 to (x to y)); touch(MotionEvent.ACTION_UP, 6 to (x to y))
assertFalse(view.isQuickHidden)
}
@Test fun hidingTheGamepadKeepsAlwaysShownKeysDrawnAndTouchable() {
val key = InputSurfaceElement(InputControl.A, .45f, .1f, .1f, .1f, "imported:0", name = "Find", alwaysShown = true)
view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button, key), aspect = ASPECT))
@Test fun tappingTheCornerHidesTheControlsAndTappingAgainShowsThem() {
val taps = mutableListOf<OnScreenControls.Hidden?>()
view.onCornerTap = { taps += it }
touch(MotionEvent.ACTION_DOWN, 4 to (800f to 250f))
assertTrue(state().isDown(PadState.A))
val (x, y) = corner
assertTrue(view.cornerTakes(x, y))
assertFalse(view.cornerTakes(800f, 250f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 4 to (800f to 250f), 1 to (x to y))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 4 to (800f to 250f), 1 to (x to y))
shadowOf(Looper.getMainLooper()).idle()
measure(view)
assertTrue(view.hasPinned)
view.setPinnedOnly(true)
measure(view)
assertTrue(view.takesTouchAt(500f, 90f))
assertEquals(OnScreenControls.Hidden.BY_TAP, view.hidden)
assertFalse(state().isDown(PadState.A))
assertFalse(view.takesTouchAt(800f, 250f))
assertFalse(view.takesTouchAt(200f, 300f))
view.setPinnedOnly(false)
measure(view)
assertTrue(view.takesTouchAt(x, y))
touch(MotionEvent.ACTION_UP, 4 to (800f to 250f))
tapCorner()
assertNull(view.hidden)
assertTrue(view.takesTouchAt(800f, 250f))
assertTrue(view.takesTouchAt(500f, 90f))
view.setQuickHidden(true)
assertEquals(listOf(OnScreenControls.Hidden.BY_TAP, null), taps)
}
@Test fun holdingTheCornerOpensTheMenuOnLiftWithoutHiding() {
var held = 0
val taps = mutableListOf<OnScreenControls.Hidden?>()
view.onCornerHold = { held++ }
view.onCornerTap = { taps += it }
val activity = Robolectric.buildActivity(ComponentActivity::class.java).setup().get()
activity.setContentView(view, FrameLayout.LayoutParams(1000, 600))
measure(view)
assertTrue(view.takesTouchAt(500f, 90f))
val (x, y) = corner
touch(MotionEvent.ACTION_DOWN, 1 to (x to y))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ViewConfiguration.getLongPressTimeout() + 50L))
assertEquals(0, held)
touch(MotionEvent.ACTION_UP, 1 to (x to y))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(1, held)
assertNull(view.hidden)
assertTrue(taps.isEmpty())
touch(MotionEvent.ACTION_DOWN, 1 to (x to y))
touch(MotionEvent.ACTION_CANCEL, 1 to (x to y))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ViewConfiguration.getLongPressTimeout() + 50L))
touch(MotionEvent.ACTION_UP, 1 to (x to y))
shadowOf(Looper.getMainLooper()).idle()
assertEquals(1, held)
assertNull(view.hidden)
assertTrue(taps.isEmpty())
}
@Test fun aControllerHideReleasesHeldControlsAndATapBringsThemBack() {
touch(MotionEvent.ACTION_DOWN, 4 to (800f to 250f))
view.setHidden(OnScreenControls.Hidden.BY_CONTROLLER)
measure(view)
assertFalse(state().isDown(PadState.A))
assertFalse(view.takesTouchAt(800f, 250f))
touch(MotionEvent.ACTION_UP, 4 to (800f to 250f))
tapCorner()
assertNull(view.hidden)
assertTrue(view.takesTouchAt(800f, 250f))
}
@Test fun theCornerIsGoneWithoutALayoutAndOnTheDockedStrip() {
val (x, y) = corner
view.updateLayout(null)
measure(view)
assertFalse(view.cornerTakes(x, y))
assertFalse(view.takesTouchAt(x, y))
val docked = OnScreenControls(context, bridge, OnScreenLayout.Dock(false, grips = true))
docked.updateLayout(SavedInputLayout("test", "Test", listOf(button), aspect = ASPECT))
measure(docked)
assertFalse(docked.cornerTakes(x, y))
docked.releaseAll()
}
@Test fun switchingTheVirtualControllerRedrawsTheSameLayoutWithTheNewKit() {
assertEquals(PadKit.STEAM_DECK, view.inputSurface.kit)
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DS4)
view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button), aspect = ASPECT))
assertFalse(view.hasPinned)
assertEquals(PadKit.DUALSHOCK, view.inputSurface.kit)
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360)
view.reload()
assertEquals(PadKit.XBOX, view.inputSurface.kit)
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK)
}
private companion object { const val ASPECT = 1000f / 600f }
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
@@ -38,39 +39,6 @@ class OnScreenLayoutTest {
}
}
@Test fun theBuiltInGamepadIsRegeneratedForEverySizeWithoutStretching() {
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 })
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)
}
}
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() {
val saved = gamepad().copy(elements = LegacyGamepadLayout(context, 2608, 1200).elements(), aspect = 2608f / 1200)
val placed = OnScreenLayout.elements(context, saved, 2048, 1200, Rect())
assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed)
}
@Test @Config(qualifiers = "w745dp-h343dp-land-420dpi")
fun previouslyGeneratedEdgeSticksRegenerateWithoutOverridingCustomGeometry() {
val w = 2608
val h = 1200
ControllerPrefs.setLayout(context, w, h, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f)))
val generator = LegacyGamepadLayout(context, w, h)
val old = generator.elements(previousStickGeometry = true)
val current = generator.elements()
assertTrue(old.filter { it.control == InputControl.LS || it.control == InputControl.RS }.zip(current.filter { it.control == InputControl.LS || it.control == InputControl.RS }).any { (a, b) -> kotlin.math.abs(a.width - b.width) > .01f })
val saved = gamepad().copy(elements = old, aspect = w.toFloat() / h)
assertEquals(LegacyGamepadLayout(context, 2048, h).regenerate(old), OnScreenLayout.elements(context, saved, 2048, h, Rect()))
val custom = saved.copy(elements = old.map { if (it.id == "legacy:a") it.copy(x = .4f) else it })
assertEquals(OnScreenLayout.fit(custom.elements, custom.aspect, 1f, 2048, h, Rect()), OnScreenLayout.elements(context, custom, 2048, h, Rect()))
}
@Test fun savingTheEditorFrameKeepsEveryControlWhereTheEditorShowsIt() {
val w = 2608
val h = 1200
@@ -90,6 +58,27 @@ class OnScreenLayoutTest {
}
}
@Test fun onlyAnUntouchedBuiltInGamepadOrACopyOfOneFollowsTheKit() {
assertTrue(OnScreenLayout.generated(gamepad()))
assertTrue(OnScreenLayout.generated(SavedInputLayout("copy", "Copy", origin = InputLibraries.OVERLAY)))
assertFalse(OnScreenLayout.generated(SavedInputLayout("custom", "Custom")))
assertFalse(OnScreenLayout.generated(SavedInputLayout("copy", "Copy", origin = InputLibraries.DECK)))
val edited = gamepad().copy(elements = listOf(InputSurfaceElement(InputControl.A, .5f, .5f, .1f, .1f)), aspect = 2f)
assertFalse(OnScreenLayout.generated(edited))
assertEquals(listOf("legacy:a"), OnScreenLayout.elements(context, edited, 2000, 1000, Rect()).map { it.id })
}
@Test fun theBuiltInGamepadFollowsTheVirtualControllersKitAndScale() {
for ((type, kit) in listOf(SessionPrefs.CONTROLLER_DECK to PadKit.STEAM_DECK, SessionPrefs.CONTROLLER_XBOX360 to PadKit.XBOX,
SessionPrefs.CONTROLLER_DUALSENSE to PadKit.DUALSENSE)) {
SessionPrefs.setSteamController(context, type)
val safe = Rect(40, 0, 20, 10)
assertEquals(KitLayout.elements(context, kit, 2400, 1080, safe), OnScreenLayout.elements(context, gamepad(), 2400, 1080, safe))
assertEquals(KitLayout.elements(context, kit, 2400, 1080, safe, 1.25f), OnScreenLayout.elements(context, gamepad().copy(scale = 1.25f), 2400, 1080, safe))
}
assertEquals(emptyList<InputSurfaceElement>(), OnScreenLayout.elements(context, null, 2400, 1080, Rect()))
}
@Test fun editorAndGameUseTheSamePixelRectsOnWideAndStandardScreens() {
val layout = gamepad()
for ((w, h) in listOf(2000 to 900, 1600 to 900)) {
@@ -105,7 +94,7 @@ class OnScreenLayoutTest {
@Test fun editedGeneratedAndCustomLayoutsKeepTheirPixelRectsAcrossRefreshes() {
for ((w, h) in listOf(2000 to 900, 1600 to 900)) {
val generated = gamepad()
val generatedEdit = generated.elements.map { if (it.id == "legacy:a") it.copy(x = .3f, y = .4f, width = .12f, height = .12f) else it }
val generatedEdit = KitLayout.elements(context, PadKit.current(context), w, h).map { if (it.id == "legacy:a") it.copy(x = .3f, y = .4f, width = .12f, height = .12f) else it }
val generatedSaved = generated.copy(elements = generatedEdit, aspect = w.toFloat() / h)
val generatedPixels = px(OnScreenLayout.elements(context, generatedSaved, w, h, Rect()).first { it.id == "legacy:a" }, w, h)
val generatedRefresh = px(OnScreenLayout.editorElements(context, generatedSaved, w, h, edited = true).first { it.id == "legacy:a" }, w, h)
@@ -117,25 +106,6 @@ class OnScreenLayoutTest {
}
}
@Test fun resetPositionsRestoresGeneratedGeometryAfterAnEdit() {
for ((w, h) in listOf(2000 to 900, 1600 to 900)) {
val original = gamepad()
val moved = original.copy(elements = original.elements.map { if (it.id == "legacy:a") it.copy(x = .3f) else it }, aspect = w.toFloat() / h)
val reset = LegacyGamepadLayout(context, w, h).regenerate(moved.elements)
assertEquals(LegacyGamepadLayout(context, w, h).regenerate(original.elements), OnScreenLayout.elements(context, moved.copy(elements = reset), w, h, Rect()))
}
}
@Test fun regenerationKeepsTheUsersButtonStylesAndRemovedButtons() {
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" })
val a = placed.first { it.id == "legacy:a" }
assertEquals(.4f, a.opacity)
assertEquals("Jump", a.name)
assertEquals(LegacyGamepadLayout(context, 2000, 1000).elements().first { it.id == "legacy:a" }.x, a.x, .0001f)
}
@Test fun anEditedLayoutKeepsItsAspectAndCornersWhenTheScreenRotates() {
val corner = InputSurfaceElement(InputControl.A, .85f, .7f, .1f, .2f)
val left = InputSurfaceElement(InputControl.LS, .05f, .5f, .2f, .4f)
@@ -167,26 +137,6 @@ class OnScreenLayoutTest {
assertInside(OnScreenLayout.elements(context, edge, 2400, 1080, safe), 2400, 1080, safe)
}
@Test fun steamAndQamOnlyModePutsLargeButtonsInTheBottomCornersAndTheKeyboardBetween() {
val safe = Rect(80, 0, 30, 20)
val placed = OnScreenLayout.elements(context, gamepad(), 1000, 500, safe, buttonsOnly = true)
assertEquals(setOf(InputControl.GUIDE, InputControl.QAM, InputControl.A), placed.map { it.control }.toSet())
val radius = 30 * density
val inset = 44 * density
fun centre(e: InputSurfaceElement) = (e.x + e.width / 2f) * 1000 to (e.y + e.height / 2f) * 500
val guide = placed.first { it.control == InputControl.GUIDE }
val qam = placed.first { it.control == InputControl.QAM }
val keyboard = placed.first { it.id == "builtin:keyboard" }
assertEquals(2 * radius, guide.width * 1000, .5f)
assertEquals(80 + inset, centre(guide).first, .5f)
assertEquals(500 - 20 - inset, centre(guide).second, .5f)
assertEquals(1000 - 30 - inset, centre(qam).first, .5f)
assertEquals(500f, centre(keyboard).first, .5f)
assertEquals(500 - 20 - inset, centre(keyboard).second, .5f)
val user = SavedInputLayout("edited", "Edited", listOf(InputSurfaceElement(InputControl.A, .5f, .5f, .1f, .1f)))
assertEquals(setOf(InputControl.GUIDE, InputControl.QAM), OnScreenLayout.elements(context, user, 2000, 1000, Rect(), buttonsOnly = true).map { it.control }.toSet())
}
@Test fun theUnfoldedStripUsesTheDockGeometryInLandscapeAndPortrait() {
for ((size, portrait) in listOf((2208 to 800) to false, (1080 to 1300) to true)) {
val (w, h) = size
@@ -233,8 +183,15 @@ class OnScreenLayoutTest {
assertTrue(migrated.profiles.any { it.id == "migrated.screenkeys.0" })
assertTrue(prefs.getBoolean(LegacyScreenKeyMigration.MERGED, false))
assertEquals(migrated, InputLibraries.read(context))
val placed = OnScreenLayout.elements(context, layout, 2400, 1080, Rect())
assertEquals(layout.elements.map { it.id }, placed.map { it.id })
}
@Test fun migratedScreenKeysAreDrawnNextToTheKitGamepad() {
prefs.edit().clear().commit()
ControllerPrefs.prefs(context).edit().putString("screenKeys", legacyKeys).commit()
val layout = InputLibraries.read(context).activeLayout(false, InputRole.PRIMARY)!!
val placed = OnScreenLayout.elements(context, layout, 2400, 1080, Rect()).map { it.id }
assertTrue(placed.contains("imported:0"))
assertTrue(placed.containsAll(listOf("legacy:a", KitLayout.DPAD_ID, "legacy:ls")))
}
@Test fun librariesMigratedBeforeTheMergeGetTheirScreenKeysBackOnceWithoutLosingEdits() {
@@ -266,20 +223,6 @@ class OnScreenLayoutTest {
assertEquals(selected, LegacyScreenKeyMigration.merge(selected, shown))
}
@Test fun alwaysShownKeysStayInButtonsOnlyModeAndLeaveTheUnfoldedStrip() {
val key = InputSurfaceElement(InputControl.A, .45f, .1f, .1f, .1f, "imported:0", name = "Find", alwaysShown = true)
val plain = InputSurfaceElement(InputControl.A, .45f, .4f, .1f, .1f, "imported:1", name = "Jump")
val layout = gamepad().let { it.copy(elements = it.elements + key + plain) }
val buttons = OnScreenLayout.elements(context, layout, 1000, 500, Rect(), buttonsOnly = true)
assertTrue(buttons.any { it.id == key.id })
assertFalse(buttons.any { it.id == plain.id })
assertEquals(OnScreenLayout.elements(context, gamepad(), 1000, 500, Rect(), buttonsOnly = true), buttons.filterNot { it.id == key.id })
val strip = OnScreenLayout.elements(context, layout, 2208, 800, Rect(), dock = OnScreenLayout.Dock(false, grips = false))
assertFalse(strip.any { it.id == key.id })
assertTrue(strip.any { it.id == plain.id })
assertTrue(OnScreenLayout.elements(context, layout, 1000, 500, Rect()).map { it.id }.containsAll(listOf(key.id, plain.id)))
}
@Test fun migratedScreenKeysAreAlwaysShownButOtherElementsAreNot() {
prefs.edit().clear().commit()
ControllerPrefs.prefs(context).edit().putString("screenKeys", legacyKeys).commit()
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE)
class PadKitTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@After fun reset() { context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() }
@Test fun eachVirtualControllerGetsItsOwnKit() {
assertEquals(PadKit.STEAM_DECK, PadKit.of(SessionPrefs.CONTROLLER_DECK))
assertEquals(PadKit.STEAM_CONTROLLER, PadKit.of(SessionPrefs.CONTROLLER_STEAM))
assertEquals(PadKit.XBOX, PadKit.of(SessionPrefs.CONTROLLER_XBOX360))
assertEquals(PadKit.DUALSHOCK, PadKit.of(SessionPrefs.CONTROLLER_DS4))
assertEquals(PadKit.DUALSENSE, PadKit.of(SessionPrefs.CONTROLLER_DUALSENSE))
assertEquals(PadKit.STEAM_DECK, PadKit.of(SessionPrefs.CONTROLLER_NONE))
assertEquals(PadKit.STEAM_DECK, PadKit.of("switchpro"))
}
@Test fun theKitFollowsTheChosenVirtualController() {
assertEquals(PadKit.STEAM_DECK, PadKit.current(context))
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DUALSENSE)
assertEquals(PadKit.DUALSENSE, PadKit.current(context))
}
@Test fun steamAndPlayStationKitsAreGroupedForTheirLayouts() {
assertEquals(setOf(PadKit.STEAM_DECK, PadKit.STEAM_CONTROLLER), PadKit.entries.filter { it.steam }.toSet())
assertEquals(setOf(PadKit.DUALSHOCK, PadKit.DUALSENSE), PadKit.entries.filter { it.playStation }.toSet())
assertFalse(PadKit.XBOX.steam || PadKit.XBOX.playStation)
}
@Test fun faceGlyphsMatchTheRealControllers() {
assertEquals(FaceGlyphs.MONO_LETTERS, PadKit.STEAM_DECK.face)
assertEquals(FaceGlyphs.MONO_LETTERS, PadKit.STEAM_CONTROLLER.face)
assertEquals(FaceGlyphs.COLOR_LETTERS, PadKit.XBOX.face)
assertEquals(FaceGlyphs.COLOR_SYMBOLS, PadKit.DUALSHOCK.face)
assertEquals(FaceGlyphs.MONO_SYMBOLS, PadKit.DUALSENSE.face)
assertEquals(DpadStyle.ARROWS, PadKit.DUALSHOCK.dpad)
assertEquals(DpadStyle.ARROWS, PadKit.DUALSENSE.dpad)
}
@Test fun onlyXboxNamesItsShouldersBumpersAndTriggers() {
val shoulders = listOf(InputControl.LB, InputControl.RB, InputControl.LT, InputControl.RT)
assertEquals(listOf("LB", "RB", "LT", "RT"), shoulders.map(PadKit.XBOX::label))
for (kit in PadKit.entries - PadKit.XBOX) assertEquals(kit.name, listOf("L1", "R1", "L2", "R2"), shoulders.map(kit::label))
for (kit in PadKit.entries) assertEquals(InputControl.A.label, kit.label(InputControl.A))
}
@Test fun playStationFaceButtonsAreNamedByTheirSymbols() {
val face = listOf(InputControl.A, InputControl.B, InputControl.X, InputControl.Y)
for (kit in listOf(PadKit.DUALSHOCK, PadKit.DUALSENSE)) {
assertEquals(kit.name, listOf("Cross", "Circle", "Square", "Triangle"), face.map(kit::name))
assertEquals("L1", kit.name(InputControl.LB))
val elements = KitLayout.elements(context, kit, 1920, 1080).associateBy { it.id }
assertEquals("Triangle", elements.getValue("legacy:y").name)
assertEquals("Cross", elements.getValue("legacy:a").name)
}
for (kit in listOf(PadKit.STEAM_DECK, PadKit.STEAM_CONTROLLER, PadKit.XBOX)) {
assertEquals(kit.name, face.map { it.label }, face.map(kit::name))
assertEquals(kit.label(InputControl.LT), kit.name(InputControl.LT))
assertEquals(InputControl.Y.label, KitLayout.elements(context, kit, 1920, 1080).single { it.id == "legacy:y" }.name)
}
}
}
@@ -177,8 +177,8 @@ class PhysicalShortcutsTest {
}
@Test fun resetAndRemovalPreserveOtherControllerSettings() {
ControllerPrefs.setSelectSteam(context, true)
ControllerPrefs.setTarget(context, "a", "b")
LegacyControllerPrefs.setSelectSteam(context, true)
LegacyControllerPrefs.setTarget(context, "a", "b")
assign(key(), Action.STEAM)
assign(key(KeyEvent.KEYCODE_BUTTON_2), Action.QAM)
PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).first())
@@ -186,7 +186,7 @@ class PhysicalShortcutsTest {
PhysicalShortcuts.remove(context, PhysicalShortcuts.read(context).single())
assertTrue(PhysicalShortcuts.read(context).isEmpty())
assertTrue(ControllerPrefs.read(context).selectSteam)
assertEquals("b", ControllerPrefs.target(context, "a"))
assertEquals("b", LegacyControllerPrefs.target(context, "a"))
assign(key(), Action.STEAM)
ControllerPrefs.resetAll(context)
assertTrue(PhysicalShortcuts.read(context).isEmpty())
@@ -36,7 +36,7 @@ class SelectProfileRoutingTest {
@Before fun setUp() {
context.getSharedPreferences("input-profiles", 0).edit().clear().commit()
context.getSharedPreferences("controller", 0).edit().clear().commit()
ControllerPrefs.setSelectSteam(context, true)
LegacyControllerPrefs.setSelectSteam(context, true)
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
bridge.setInputRouter(InputRouter(output))
bridge.setInputProfile(InputProfiles.active(context, desktop = false))
@@ -80,7 +80,8 @@ class SessionKeyboardPadTest {
ReflectionHelpers.setField(activity, "steamTouchOptions",
SteamTouchConfig.Options(inputMode = SteamTouchConfig.INPUT_CONTROLLER))
SessionPrefs.setTouchMode(activity, SessionPrefs.TOUCH_DIRECT)
SessionPrefs.setOscMode(activity, SessionPrefs.OSC_STEAM_TOUCH)
SessionPrefs.setOscMode(activity, SessionPrefs.OSC_ALWAYS)
SessionPrefs.setSteamTouchLayout(activity, true)
update()
assertEquals(View.VISIBLE, steam.visibility)
assertEquals(SessionPrefs.TOUCH_OFF, routedTouchMode())
@@ -0,0 +1,45 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.view.View
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.InputSurfaceView
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, qualifiers = "w833dp-h468dp-land-369dpi")
class ShowLayoutTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@After fun close() { context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() }
private fun sized(view: View, w: Int, h: Int) {
view.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY))
view.layout(0, 0, w, h)
}
@Test fun aGeneratedLayoutIsDrawnFromTheKitAtTheViewSize() {
SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_XBOX360)
val view = InputSurfaceView(context)
sized(view, 1240, 1080)
view.showLayout(SavedInputLayout(InputLibraries.OVERLAY, "Gamepad"))
assertEquals(KitLayout.elements(context, PadKit.XBOX, 1240, 1080), view.shownElements)
view.releaseInputs()
}
@Test fun aSavedLayoutIsDrawnAsSaved() {
val saved = listOf(InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f))
val view = InputSurfaceView(context)
sized(view, 1240, 1080)
view.showLayout(SavedInputLayout("mine", "Mine", saved))
assertEquals(saved, view.shownElements)
view.showLayout(null)
assertTrue(view.shownElements.isEmpty())
view.releaseInputs()
}
}
@@ -61,7 +61,7 @@ class StickDeadZoneTest {
val button = PhysicalShortcuts.Button("test-pad", "Test pad", KeyEvent.KEYCODE_BUTTON_MODE, 0)
val binding = PhysicalShortcuts.Binding(button, PhysicalShortcuts.Action.QAM)
PhysicalShortcuts.assign(context, button, binding.action)
ControllerPrefs.setTarget(context, "a", "b")
LegacyControllerPrefs.setTarget(context, "a", "b")
ControllerPrefs.setRumble(context, false)
for (percent in ControllerPrefs.deadZones) {
ControllerPrefs.setDeadZone(context, percent)
@@ -395,27 +395,22 @@ class StickDeadZoneTest {
@Test fun neutralScreenStickPressClearsRetainedPhysicalInput() {
val device = device()
for (adaptive in listOf(false, true)) {
ControllerPrefs.setAdaptiveSticks(context, adaptive)
ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (0.45f to 0.5f), "rs" to (0.55f to 0.5f)))
for (id in listOf("ls", "rs")) {
motion(device, MotionEvent.AXIS_X to 0.6f, MotionEvent.AXIS_Z to 0.7f)
val view = OnScreenControls(context, bridge)
val elements = LegacyGamepadLayout(context, 1200, 800).elements()
view.updateLayout(SavedInputLayout("test", "Test", elements))
val elements = KitLayout.elements(context, PadKit.STEAM_DECK, 1200, 800).map { if (it.kind == InputElementKind.STICK) it.copy(floating = adaptive) else it }
view.updateLayout(SavedInputLayout("test", "Test", elements, aspect = 1200f / 800f))
view.measure(android.view.View.MeasureSpec.makeMeasureSpec(1200, android.view.View.MeasureSpec.EXACTLY), android.view.View.MeasureSpec.makeMeasureSpec(800, android.view.View.MeasureSpec.EXACTLY))
view.layout(0, 0, 1200, 800)
val control = elements.first { it.control.id == id }
val left = (control.x * 1200).toInt()
val top = (control.y * 800).toInt()
val height = (control.height * 800).toInt()
val x = left + if (id == "ls") (control.width * 1200).toInt() - height / 2f else height / 2f
val y = top + height / 2f
val control = elements.first { it.id == "legacy:$id" }
val x = (control.x + control.width / 2) * 1200
val y = (control.y + control.height / 2) * 800
val down = MotionEvent.obtain(1000, 1000, MotionEvent.ACTION_DOWN, x, y, 0)
try { assertTrue(view.dispatchTouchEvent(down)) } finally { down.recycle() }
assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, 0f)
assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, .05f)
assertTrue((if (id == "ls") pad().rightX else pad().leftX) > 0f)
bridge.setStickDeadZone(25)
assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, 0f)
assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, .05f)
motion(device, MotionEvent.AXIS_X to 0.6f, MotionEvent.AXIS_Z to 0.7f)
val button = elements.first { it.control == InputControl.A }
val bx = (button.x + button.width / 2) * 1200
@@ -60,6 +60,20 @@ class SessionDisplayTest {
assertEquals(864, SessionDisplay.unfoldedGameHeight(1920, 1080))
}
@Test fun unfoldedControlsFitTheGamesOwnAspectUnderTheCap() {
assertEquals(810, SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = 4f / 3f))
assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = 16f / 9f))
assertEquals((1920 * SessionDisplay.UNFOLDED_MAX_GAME_SHARE).toInt() and 1.inv(), SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = 9f / 16f))
assertEquals(SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = .5f), SessionDisplay.unfoldedGameHeight(1080, 1920, aspect = .1f))
assertEquals(810, SessionDisplay.unfoldedGameHeight(1080, 1920, 136, aspect = 4f / 3f))
assertEquals(1240, SessionDisplay.unfoldedGameHeight(2448, 1848, 136, aspect = 16f / 9f))
}
@Test fun aTallScreenTakesTheTabRowFromTheControlsSoTheGameKeepsTheFullWidth() {
assertEquals(606, SessionDisplay.unfoldedGameHeight(1080, 1920, 146))
assertEquals(1080, SessionDisplay.unfoldedGameHeight(1080, 2400, 146, aspect = 1f))
}
@Test fun aTabRowUnderTheBarComesOutOfTheGameNotTheControls() {
assertEquals(1376, SessionDisplay.unfoldedGameHeight(2448, 1848, 0))
assertEquals(1240, SessionDisplay.unfoldedGameHeight(2448, 1848, 136))
@@ -9,6 +9,7 @@ import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.InputProfile
import com.droiddeck.launcher.input.InputProfiles
import com.droiddeck.launcher.input.InputRole
import com.droiddeck.launcher.input.LegacyControllerPrefs
import com.droiddeck.launcher.input.InputSurfaceLayout
import org.junit.Assert.*
import org.junit.Before
@@ -52,7 +53,7 @@ class SettingsResetTest {
SessionPrefs.setHudOpacity(app, 40)
SessionPrefs.setDroidDeckHudConfig(app, "hudSize=mega,showFPSGraph=0")
SessionPrefs.setDroidDeckHudPosition(app, 120f, 40f)
ControllerPrefs.setOpacity(app, 40)
LegacyControllerPrefs.setOpacity(app, 40)
AppUiPrefs.setScale(app, 150)
FrameGen.set(app, FrameGen.Mode(FrameGen.ENGINE_DDFG, 3))
prefs("steam_touch").edit().putBoolean("gyro", false).commit()
@@ -154,7 +155,7 @@ class SettingsResetTest {
val defaultGame = InputProfiles.read(app, InputProfile.GAME)
val defaultDesktop = InputProfiles.read(app, InputProfile.DESKTOP)
val defaultSurface = InputSurfaceLayout.read(app, InputProfile.DESKTOP)
ControllerPrefs.setTarget(app, "a", "b")
LegacyControllerPrefs.setTarget(app, "a", "b")
InputProfiles.select(app, InputProfile.DESKTOP)
InputProfiles.save(app, InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Disabled))
@@ -60,42 +60,12 @@ class InputSettingsTest {
ModeSettingsActions(onResolution = {}, onHdr = {}, onTouch = {}, onSuspendPolicy = {}, onOsc = {},
onInputSettings = { opened++ }, onDirectAudio = {}, onMic = {}, onDismiss = {}), SheetTab.CONTROLS)
} }
compose.onNodeWithTag("input-profile-expand").performClick()
compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performClick()
compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)
compose.runOnIdle { assertEquals(1, opened); mode.value = SessionService.MODE_DESKTOP }
compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performClick()
compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.OnClick)
compose.runOnIdle { assertEquals(2, opened) }
}
@Test fun quickMenuCombinesPartsWithoutChangingTheSavedProfile() {
val original = InputLibraries.read(context)
compose.setContent { DroidDeckTheme {
androidx.compose.foundation.layout.Column { InputQuickSettings(rememberMenuHost(), desktop = true) }
} }
compose.onNodeWithTag("setting-input-profile").assertExists()
compose.onNodeWithTag("setting-input-part-PHYSICAL").assertDoesNotExist()
compose.onNodeWithTag("input-profile-expand").performClick()
compose.onNodeWithTag("setting-input-part-PHYSICAL").assertExists()
compose.onNodeWithTag("setting-input-part-PRIMARY").assertExists()
compose.onNodeWithTag("setting-input-part-SECONDARY").performClick()
compose.onNodeWithText("Deck grips + trackpads").performScrollTo().performClick()
compose.runOnIdle {
val changed = InputLibraries.read(context)
assertEquals(InputStockLayouts.DECK, changed.activePart(true, InputRole.SECONDARY).bindings)
assertEquals(original.profiles, changed.profiles)
assertEquals(original.compileActive(false), changed.compileActive(false))
}
compose.onNodeWithText(context.getString(R.string.input_save_combination)).performClick()
compose.onNode(hasSetTextAction()).performTextInput("Reading")
compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick()
compose.runOnIdle {
val saved = InputLibraries.read(context)
assertEquals("Reading", saved.profile(saved.activeId(true)).name)
assertTrue(saved.selection(true).parts.isEmpty())
assertEquals(original.profile("desktop"), saved.profile("desktop"))
}
}
@Test fun actionDraftSurvivesRouteAndTypeChanges() {
var saved: InputAction? = null
compose.setContent { DroidDeckTheme { InputActionEditor(InputControl.RS, InputAction.Scroll(27f, true), "Right stick", {}, { saved = it }) } }
@@ -134,12 +104,9 @@ class InputSettingsTest {
val layout = library.layout(InputProfile.GAME, InputRole.SECONDARY)!!
compose.setContent { DroidDeckTheme { InputSurfaceDialog(InputProfile.GAME, {}, { changed = true },
role = InputRole.PRIMARY, layoutId = layout.id, bindingsId = library.profile(InputProfile.GAME).binding(InputRole.SECONDARY)) } }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_editor_add)).performClick()
compose.onNodeWithText(context.getString(R.string.input_element_button), substring = false).performClick()
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_properties)).assertExists()
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performClick()
addButton(layout)
compose.onNodeWithText(context.getString(R.string.input_options)).assertExists()
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle {
assertTrue(changed)
val updated = InputLibraries.read(context)
@@ -189,24 +156,15 @@ class InputSettingsTest {
}
}
@Test fun hidingEditorToolsPreservesPlacedElements() {
val library = InputLibraries.read(context)
val layout = library.layout("game", InputRole.SECONDARY)!!
compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.SECONDARY)) } }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_editor_add)).performClick()
compose.onNodeWithText(context.getString(R.string.input_element_button)).performClick()
compose.onNodeWithTag("input-layout-canvas").performTouchInput { click(center) }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_hide_tools)).performClick()
compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertDoesNotExist()
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performClick()
compose.runOnIdle { assertEquals(layout.elements.size + 1, InputLibraries.read(context).layout("game", InputRole.SECONDARY)!!.elements.size) }
private val add get() = context.getString(R.string.input_editor_add)
private fun addButton(layout: SavedInputLayout) {
compose.onNodeWithText(add).performScrollTo().performClick()
val clicks = listOf("legacy:l3", "legacy:r3").count { id -> layout.elements.none { it.id == id } }
compose.onAllNodesWithText(add)[1 + clicks + InputElementKind.entries.indexOf(InputElementKind.BUTTON)].performScrollTo().performClick()
}
@Test fun localToolsCanMoveAndExpandWithoutMovingTheCanvas() {
@Test fun theEditorToolbarStaysAboveTheCanvasAndAddOpensAndClosesItsList() {
val library = InputLibraries.read(context)
compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = library.layout("game", InputRole.SECONDARY)!!.id, bindingsId = library.profile("game").binding(InputRole.SECONDARY)) } }
@@ -216,15 +174,49 @@ class InputSettingsTest {
assertEquals(android.view.WindowManager.LayoutParams.MATCH_PARENT, window.attributes.height)
}
val canvas = compose.onNodeWithTag("input-layout-canvas").fetchSemanticsNode().boundsInRoot
val before = compose.onNodeWithTag("input-editor-tools").fetchSemanticsNode().boundsInRoot
compose.onNodeWithTag("input-editor-tools").performTouchInput { swipe(center, center + androidx.compose.ui.geometry.Offset(250f, 150f), 500) }
val after = compose.onNodeWithTag("input-editor-tools").fetchSemanticsNode().boundsInRoot
assertTrue(after.left > before.left + 100f)
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertIsDisplayed()
val tools = compose.onNodeWithTag("input-editor-tools").fetchSemanticsNode().boundsInRoot
assertTrue(tools.top >= canvas.top && tools.bottom < canvas.center.y)
val button = context.getString(R.string.input_element_button)
compose.onNodeWithText(button).assertDoesNotExist()
compose.onNodeWithText(add).performScrollTo().performClick()
compose.onNodeWithText(button).assertIsDisplayed()
compose.onAllNodesWithText(add).onFirst().performScrollTo().performClick()
compose.onNodeWithText(button).assertDoesNotExist()
assertEquals(canvas, compose.onNodeWithTag("input-layout-canvas").fetchSemanticsNode().boundsInRoot)
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertDoesNotExist()
}
@Test @Config(qualifiers = "w833dp-h468dp-land-369dpi")
fun removedKitControlsWaitUnderHiddenAndRestoringThemKeepsTheGamepadGenerated() {
val library = InputLibraries.read(context)
val layout = library.layout("game", InputRole.PRIMARY)!!
val a = InputLibraries.defaultPositions(context, library, layout)!!.first.single { it.id == "legacy:a" }
compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } }
compose.onNodeWithText(context.getString(R.string.input_hidden_count, 0)).performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.input_nothing_hidden)).assertExists()
compose.onNodeWithText(context.getString(R.string.input_hidden_count, 0)).performScrollTo().performClick()
compose.onNodeWithTag("input-layout-canvas").performTouchInput { click(percentOffset(a.x + a.width / 2, a.y + a.height / 2)) }
compose.onNodeWithText(context.getString(R.string.input_remove_element)).performClick()
compose.onNodeWithText(context.getString(R.string.input_hidden_count, 1)).performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.input_restore)).performClick()
compose.onNodeWithText(context.getString(R.string.input_hidden_count, 0)).assertExists()
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle { assertTrue(OnScreenLayout.generated(InputLibraries.read(context).layouts.first { it.id == layout.id })) }
}
@Test fun resetAfterResizingMakesTheGamepadFollowTheKitAgain() {
val library = InputLibraries.read(context)
val layout = library.layout("game", InputRole.PRIMARY)!!
compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } }
val reset = compose.onNodeWithText(context.getString(R.string.hud_reset_button))
reset.performScrollTo().assertIsNotEnabled()
pressPlus(2)
reset.performScrollTo().assertIsEnabled().performClick()
compose.onNodeWithTag("input-editor-scale").assertTextEquals("100%")
reset.performScrollTo().assertIsNotEnabled()
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle { assertTrue(OnScreenLayout.generated(InputLibraries.read(context).layouts.first { it.id == layout.id })) }
}
@Test fun deckPresetOffersItsRealElementsAndTheCommonEditor() {
@@ -253,7 +245,6 @@ class InputSettingsTest {
compose.onNodeWithTag("input-element-legacy:a").performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("input-binding-a").assertDoesNotExist()
compose.onNodeWithTag("input-surface-primary").performScrollTo().performClick()
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_editor_add)).assertIsDisplayed()
compose.onNodeWithTag("input-layout-canvas").assertExists()
}
@@ -420,15 +411,14 @@ class InputSettingsTest {
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.SECONDARY)) } } }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_reset_positions)).performScrollTo().assertIsNotEnabled()
compose.onNodeWithTag("input-editor-scale").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(80f) }
compose.onNodeWithText(context.getString(R.string.hud_reset_button)).performScrollTo().assertIsNotEnabled()
repeat(4) { compose.onNodeWithText("\u2212").performScrollTo().performClick() }
compose.onNodeWithTag("input-editor-scale").assertTextEquals("80%")
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
val scaled = InputLibraries.read(context).layouts.first { it.id == layout.id }
assertEquals(layout.elements.scaled(.8f), scaled.elements)
compose.runOnIdle { round.value = 1 }
compose.onNodeWithTag("input-editor-tools").performClick()
compose.onNodeWithText(context.getString(R.string.input_reset_positions)).performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.hud_reset_button)).performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle { assertEquals(layout.elements, InputLibraries.read(context).layouts.first { it.id == layout.id }.elements) }
}
@@ -450,21 +440,6 @@ class InputSettingsTest {
com.droiddeck.launcher.input.ControllerPrefs.setSnap(context, true)
}
@Test fun quickButtonTogglesHideBuiltInButtonsWithoutDeletingThem() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-profile-game").performScrollTo().performClick()
compose.onNodeWithTag("input-part-primary").performScrollTo().performClick()
val before = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!
compose.onNodeWithTag("setting-quick-keyboard").performScrollTo().performClick()
compose.runOnIdle {
val after = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!
assertEquals(before.elements, after.elements)
assertEquals(setOf(InputCommand.KEYBOARD), after.style.hidden)
}
compose.onNodeWithTag("setting-quick-keyboard").performScrollTo().performClick()
compose.runOnIdle { assertTrue(InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!.style.hidden.isEmpty()) }
}
@Test fun layoutsCanBeImportedAndExported() {
val source = java.io.File(context.cacheDir, "jump.icp").apply {
writeText("""{"name":"Jump keys","elements":[{"type":"BUTTON","shape":"CIRCLE","bindings":["KEY_SPACE"],"scale":1.0,"x":0.8,"y":0.7,"text":"Jump"}]}""")
@@ -499,55 +474,54 @@ class InputSettingsTest {
assertEquals("KEY_SPACE", org.json.JSONObject(target.readText()).getJSONArray("elements").getJSONObject(0).getJSONArray("bindings").getString(0))
}
@Test fun buttonSizeRegeneratesTheGamepadAndUndoesAsOneStep() {
private fun pressPlus(times: Int) = repeat(times) { compose.onNodeWithText("+").performScrollTo().performClick() }
@Test fun sizeButtonsScaleTheWholeGamepadAndUndoAsOneStep() {
val library = InputLibraries.read(context)
val layout = library.layout("game", InputRole.PRIMARY)!!
val (_, metrics) = InputLibraries.primaryDisplay(context)
assertNotNull(OnScreenLayout.generatedSize(context, layout, metrics.widthPixels, metrics.heightPixels))
assertTrue(OnScreenLayout.generated(layout))
val defaults = InputLibraries.defaultPositions(context, library, layout)!!.first
compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.PRIMARY)) } }
compose.onNodeWithTag("input-editor-tools").performClick()
val slider = compose.onNodeWithTag("input-editor-scale").performScrollTo()
slider.assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%"))
for (value in listOf(110f, 125f)) slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(value) }
val scale = compose.onNodeWithTag("input-editor-scale")
scale.assertTextEquals("100%")
pressPlus(2)
scale.assertTextEquals("110%")
compose.onNodeWithText(context.getString(R.string.input_editor_undo)).performScrollTo().performClick()
slider.assert(SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.StateDescription, "100%"))
slider.performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(125f) }
scale.assertTextEquals("100%")
pressPlus(5)
scale.assertTextEquals("125%")
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle {
val saved = InputLibraries.read(context).layouts.first { it.id == layout.id }
assertEquals(1.25f, saved.scale)
assertNotNull(OnScreenLayout.generatedSize(context, saved, metrics.widthPixels, metrics.heightPixels))
assertNotEquals(layout.elements.first { it.id == "legacy:a" }.y, saved.elements.first { it.id == "legacy:a" }.y)
assertFalse(OnScreenLayout.generated(saved))
assertEquals(defaults.map { it.id }, saved.elements.map { it.id })
assertTrue(saved.elements.first { it.id == "legacy:a" }.width > defaults.first { it.id == "legacy:a" }.width * 1.2f)
}
}
@Test @Config(qualifiers = "w833dp-h468dp-land-369dpi")
fun buttonSizeKeepsMovedGamepadGroupsInShape() {
fun sizeButtonsKeepAMovedFaceClusterInShape() {
val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y")
val original = InputLibraries.read(context)
val gamepad = original.layout("game", InputRole.PRIMARY)!!
val moved = gamepad.copy(elements = gamepad.elements.map { if (it.id in face) it.copy(x = it.x + .012f, y = it.y + .017f) else it })
val (defaults, aspect) = InputLibraries.defaultPositions(context, original, gamepad)!!
val moved = gamepad.copy(elements = defaults.map { if (it.id in face) it.copy(x = it.x + .012f, y = it.y + .017f) else it }, aspect = aspect)
InputLibraries.update(context) { it.withLayout(moved) }
val (_, metrics) = InputLibraries.primaryDisplay(context)
assertNull(OnScreenLayout.generatedSize(context, moved, metrics.widthPixels, metrics.heightPixels))
val library = InputLibraries.read(context)
compose.setContent { DroidDeckTheme { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = moved.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(125f) }
pressPlus(5)
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle {
val saved = InputLibraries.read(context).layouts.first { it.id == moved.id }
assertEquals(1.25f, saved.scale)
val w = metrics.widthPixels; val h = metrics.heightPixels
val w = saved.aspect * 1000; val h = 1000f
fun centre(id: String) = saved.elements.first { it.id == id }.let { (it.x + it.width / 2) * w to (it.y + it.height / 2) * h }
val cross = face.associateWith(::centre)
assertEquals(centre("legacy:y").first, centre("legacy:a").first, 1f)
assertEquals(centre("legacy:x").second, centre("legacy:b").second, 1f)
assertTrue(centre("legacy:y").second < centre("legacy:x").second && centre("legacy:x").second < centre("legacy:a").second)
assertEquals(centre("legacy:a").second - centre("legacy:y").second, centre("legacy:b").first - centre("legacy:x").first, 1f)
assertEquals(centre("legacy:up").first, centre("legacy:down").first, 1f)
assertEquals(centre("legacy:left").second, centre("legacy:right").second, 1f)
assertTrue("$cross", centre("legacy:y").second < centre("legacy:x").second && centre("legacy:x").second < centre("legacy:a").second)
assertTrue("$cross", centre("legacy:x").first < centre("legacy:a").first && centre("legacy:a").first < centre("legacy:b").first)
val before = moved.elements.first { it.id == "legacy:a" }
assertTrue(saved.elements.first { it.id == "legacy:a" }.width > before.width * 1.2f)
}
@@ -134,26 +134,23 @@ class InputSurfaceTouchTest {
touch(MotionEvent.ACTION_UP, 1 to (600f to 510f))
assertTrue(events.isEmpty())
show(a, b, stick)
view.setQuickHidden(true)
view.setHidden(OnScreenControls.Hidden.BY_TAP)
measure(view)
assertFalse(view.takesTouchAt(450f, 510f))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (450f to 510f)))
assertTrue(events.isEmpty())
}
@Test fun keyboardShortcutWorksWithHiddenPadAndButtonsOnly() {
view.setQuickHidden(true)
@Test fun hiddenControlsHideTheKeyboardShortcutUntilShownAgain() {
view.setHidden(OnScreenControls.Hidden.BY_CONTROLLER)
measure(view)
assertFalse(view.takesTouchAt(800f, 240f))
assertFalse(view.takesTouchAt(450f, 510f))
view.setHidden(null)
measure(view)
touch(MotionEvent.ACTION_DOWN, 1 to (450f to 510f))
touch(MotionEvent.ACTION_UP, 1 to (450f to 510f))
view.setButtonsOnly(true)
measure(view)
val (x, y) = centre(element(view, "builtin:keyboard"))
assertFalse(view.takesTouchAt(800f, 240f))
touch(MotionEvent.ACTION_DOWN, 1 to (x to y))
touch(MotionEvent.ACTION_UP, 1 to (x to y))
assertEquals(listOf("KEYBOARD:PRIMARY", "KEYBOARD:PRIMARY"), events)
assertEquals(listOf("KEYBOARD:PRIMARY"), events)
}
@Test fun hidingTheViewReleasesLatchedKeys() {
@@ -181,11 +178,14 @@ class InputSurfaceTouchTest {
touch(MotionEvent.ACTION_CANCEL, 1 to (800f to 240f), target = panel)
}
@Test fun classicSticksTravelTheirFullRadius() {
@Test fun fixedSticksReachFullTiltInsideTheirRing() {
show(stick.copy(buttonShape = InputButtonShape.CIRCLE))
val reach = (100f - 3 * context.resources.displayMetrics.density) * .62f
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
touch(MotionEvent.ACTION_MOVE, 1 to (250f to 300f))
touch(MotionEvent.ACTION_MOVE, 1 to (200f + reach / 2 to 300f))
assertEquals(.5f, state().leftX, .01f)
touch(MotionEvent.ACTION_MOVE, 1 to (200f + reach to 300f))
assertEquals(1f, state().leftX, .01f)
touch(MotionEvent.ACTION_MOVE, 1 to (300f to 300f))
assertEquals(1f, state().leftX, .01f)
touch(MotionEvent.ACTION_UP, 1 to (300f to 300f))
@@ -209,14 +209,15 @@ class InputSurfaceTouchTest {
}
@Test fun adaptiveSticksCaptureAroundThemAndTheLeftOneToTheEdge() {
val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, hideWhenIdle = true)
val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, hideWhenIdle = true)
val left = InputSurfaceElement(InputControl.LS, .3f, .3f, .2f, .4f, floating = true)
val right = InputSurfaceElement(InputControl.RS, .6f, .3f, .2f, .4f, floating = true)
show(left, right)
val limit = (100f - 3 * context.resources.displayMetrics.density) * 1.71f
assertTrue(view.takesTouchAt(10f, 300f))
assertTrue(view.takesTouchAt(10f, 390f))
assertFalse(view.takesTouchAt(10f, 420f))
assertTrue(view.takesTouchAt(795f, 300f))
assertFalse(view.takesTouchAt(815f, 300f))
assertTrue(view.takesTouchAt(10f, 300f + limit - 4f))
assertFalse(view.takesTouchAt(10f, 300f + limit + 4f))
assertTrue(view.takesTouchAt(990f, 300f))
assertFalse(view.takesTouchAt(990f, 300f + limit + 4f))
val missed = mutableListOf<Int>()
view.onTouchMiss = { missed += it.getPointerId(0) }
touch(MotionEvent.ACTION_DOWN, 1 to (50f to 300f))
@@ -224,9 +225,9 @@ class InputSurfaceTouchTest {
assertEquals(listOf(2), missed)
touch(MotionEvent.ACTION_MOVE, 1 to (150f to 300f), 2 to (60f to 310f))
assertTrue(state().leftX > .9f)
show(left.copy(hideWhenIdle = false), right.copy(hideWhenIdle = false))
show(left.copy(floating = false), right.copy(floating = false))
assertFalse(view.takesTouchAt(10f, 300f))
assertFalse(view.takesTouchAt(815f, 300f))
assertFalse(view.takesTouchAt(990f, 300f))
}
private fun element(root: View, id: String): View = descendants(root).first { (it.tag as? InputSurfaceElement)?.id == id }
@@ -16,6 +16,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.ui.Modifier
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.LegacyControllerPrefs
import com.droiddeck.launcher.input.PadBridgeRoutingTest
import com.droiddeck.launcher.input.PhysicalShortcuts
import org.junit.Assert.*
@@ -127,7 +128,7 @@ class PhysicalShortcutsDialogTest {
}
@Test fun removalRestoresDefaultAndPreservesOtherAssignmentsAndControllerSettings() {
ControllerPrefs.setSelectSteam(context, true)
LegacyControllerPrefs.setSelectSteam(context, true)
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN))),
PhysicalShortcuts.Action.STEAM)
PhysicalShortcuts.assign(context, requireNotNull(PhysicalShortcuts.button(event(KeyEvent.KEYCODE_F2, KeyEvent.ACTION_DOWN))),
@@ -71,11 +71,8 @@ class SessionSecondScreenTest {
@Test fun steamMenuKeepsTheExistingTrackpadAndTerminal() = checkModes(steam = true)
@Test fun desktopQuickMenuChangesTheRunningDesktopLayout() = checkQuickSelection(steam = false, desktop = true, direct = true)
@Test fun steamQuickMenuLeavesTheDesktopSelectionAlone() = checkQuickSelection(steam = true, desktop = false, direct = false)
@Test fun directGameQuickMenuLeavesTheDesktopSelectionAlone() = checkQuickSelection(steam = false, desktop = false, direct = true)
@Test fun closingTheDockedDrawerKeepsTheSelectedControlsPanel() {
SessionState.mode = SessionService.MODE_STEAM
@@ -308,43 +305,6 @@ class SessionSecondScreenTest {
compose.onNodeWithText(context.getString(R.string.mode_mic)).assertDoesNotExist()
}
private fun checkQuickSelection(steam: Boolean, desktop: Boolean, direct: Boolean) {
SessionState.mode = if (desktop) SessionService.MODE_DESKTOP else if (steam) SessionService.MODE_STEAM else SessionService.MODE_RUN
val original = InputLibraries.update(context) { it.chooseLayout("desktop", InputRole.SECONDARY, InputLibraries.DECK) }
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val panel = SecondScreenPresentation(activity, display, {}, {}, {})
val open = androidx.compose.runtime.mutableStateOf(true)
try {
panel.show()
panel.showMode(SecondScreenMode.CUSTOM_CONTROLS)
compose.setContent {
DroidDeckTheme {
SessionDrawer(open.value, SessionDrawerPage.CONTROLLER, false, {},
actions(steam, emptyList(), desktop = desktop, direct = direct,
onInputSelection = { panel.refreshControls() }, onClose = { open.value = false }))
}
}
compose.onNodeWithTag("setting-input-profile").performScrollTo().performClick()
compose.onNodeWithText("Desktop").performScrollTo().performClick()
compose.onNodeWithTag("input-profile-expand").performScrollTo().performClick()
compose.onNodeWithTag("setting-input-part-SECONDARY").performScrollTo().performClick()
compose.onNodeWithText("Trackpad + keyboard").performScrollTo().performClick()
compose.onNode(hasContentDescription(context.getString(R.string.common_close)) and
SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.Role, androidx.compose.ui.semantics.Role.Button)).performClick()
compose.runOnIdle {
val updated = InputLibraries.read(context)
assertEquals("desktop", updated.selection(desktop).profile)
assertEquals(InputLibraries.TRACKPAD, updated.activeLayout(desktop, InputRole.SECONDARY)?.id)
assertEquals(original.selection(!desktop), updated.selection(!desktop))
assertEquals(original.profiles, updated.profiles)
val controls = descendants(panel.window!!.decorView).filterIsInstance<InputSurfaceView>().single()
val pads = descendants(controls).mapNotNull { it.tag as? InputSurfaceElement }.filter { it.kind == InputElementKind.TRACKPAD }.toList()
assertEquals(1, pads.size)
}
} finally { panel.closeControls() }
}
private fun checkModes(steam: Boolean) {
SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP
val selected = mutableListOf<SecondScreenMode>()