fix(input): restore the controls, panels and settings #1439 removed (#2238)

* fix(input): restore on-screen touch behaviour: slide between buttons, mouse pass-through, keyboard on release, overlay haptics, stick reach and hit areas

* fix(dual-screen): restore second-screen bars, swapped Terminal and Deck panel tabs

* fix(input): fit on-screen layouts to the real view size, cutout, Steam + QAM mode and unfolded strip

* fix(input): unfolded strip keeps press haptics

* fix(input): restore layout import/export, element editor rows and layout tools

Bring back .icp layout import and export on the saved layouts page, the
per-element image, opacity and label controls, a uniform size slider and
reset positions in the layout editor, and non-destructive Steam, QAM and
keyboard button toggles stored on the layout style. Remove strings left
unused by the input profile unification.

* fix(input): keep hit slack to gamepad-shaped buttons and fit touch tests to saved layout geometry

* fix(input): button size regenerates the gamepad and scales spacing

A generated gamepad now stores its button size and is regenerated at that
size, so spacing follows the radius and the layout keeps regenerating on
rotation. Edited layouts scale positions from their anchor edge or centre
so gaps grow and shrink with the controls.

* fix(input): button size rescales moved gamepads around the generator

Gamepad layouts that no longer match the generated positions exactly were
scaled element by element from screen thirds, which split the face buttons
and D-pad across anchors. Gamepad controls now take the generator's
positions at the new size plus each control's own offset from the
generated position, so groups keep their shape and spacing.
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-07 16:36:23 -05:00
1 parent a33954b8bd
commit 8fa30b99f9
70 files changed
+2383 -1789

No files matched your search

@@ -0,0 +1,95 @@
package com.droiddeck.launcher.input
import android.content.Context
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 InputLayoutFileTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
private fun import(raw: String) = InputLayoutFile.import(context, raw, "Fallback", InputLayoutScreen.MAIN, InputSurfaceStyle(), 1000, 500, 2f)
@Test fun exportThenImportKeepsKeysShapesCentresSizesAndToggles() {
val keys = LegacyScreenKeyMigration.convert(context,
"28:0.25,0.6,50::::0.8:2:0:1;29+33:0.7,0.8,40::Find::0.6:3:1:1;103+0+106+0+108+0+105+0:0.5,0.5,80::::1:6:0:1;17+32+31+30:0.2,0.3,70::::1:5:0:1",
1000, 500, 2f)
val layout = SavedInputLayout("source", "My layout", keys.map { it.first })
val bindings = SavedInputBindings("source.bindings", "My layout", false, layout.id, elements = keys.associate { it.first.id to it.second })
val raw = InputLayoutFile.export(layout, bindings, 1000, 500)!!
assertEquals("My layout", JSONObject(raw).getString("name"))
val (imported, actions) = import(raw)!!
assertEquals("My layout", imported.name)
assertEquals(InputLayoutScreen.MAIN, imported.screen)
assertEquals(layout.elements.map { it.kind }, imported.elements.map { it.kind })
for ((before, after) in layout.elements.zip(imported.elements)) {
assertEquals(before.x + before.width / 2, after.x + after.width / 2, .002f)
assertEquals(before.y + before.height / 2, after.y + after.height / 2, .002f)
assertEquals(before.height, after.height, .005f)
assertEquals(before.toggle, after.toggle)
assertEquals(before.opacity, after.opacity, .001f)
}
assertEquals(InputButtonShape.CIRCLE, imported.elements[0].buttonShape)
assertEquals(InputButtonShape.RECTANGLE, imported.elements[1].buttonShape)
assertEquals("Find", imported.elements[1].name)
val codes = imported.elements.map { actions.action(it) }
assertEquals(InputAction.Keys(listOf(28)), codes[0])
assertEquals(InputAction.Keys(listOf(29, 33)), codes[1])
assertEquals(listOf(103, 106, 108, 105), (codes[2] as InputAction.Directions).let { listOf(it.up, it.right, it.down, it.left) })
assertEquals(InputAction.Directions(17, 32, 31, 30), codes[3])
InputLibraries.update(context) { it.withLayout(imported).withPreset(actions).chooseLayout(InputProfile.GAME, InputRole.PRIMARY, imported.id) }
assertEquals(imported.id, InputLibraries.read(context).layout(InputProfile.GAME, InputRole.PRIMARY)!!.id)
}
@Test fun importsOlderDroidDeckAndWinlatorFiles() {
val raw = """{"id":0,"name":"DroidDeck","cursorSpeed":1.5,"elements":[
{"type":"BUTTON","shape":"CIRCLE","bindings":["KEY_SPACE"],"scale":1.2,"x":0.8,"y":0.7,"toggleSwitch":false,"text":"Jump","opacity":0.5},
{"type":"BUTTON","shape":"ROUND_RECT","bindings":["KEY_CTRL_L","KEY_C"],"scale":1.0,"x":0.3,"y":0.2,"toggleSwitch":true,"text":""},
{"type":"STICK","shape":"ROUND_RECT","bindings":["KEY_W","","KEY_D","","KEY_S","","KEY_A",""],"scale":1.0,"x":0.2,"y":0.7},
{"type":"STICK","bindings":["KEY_UP","KEY_RIGHT","KEY_DOWN","KEY_LEFT"],"scale":1.0,"x":0.6,"y":0.5},
{"type":"D_PAD","bindings":["KEY_I","KEY_L","KEY_K","KEY_J"],"scale":1.0,"x":0.4,"y":0.5},
{"type":"TRACKPAD","bindings":["MOUSE_MOVE_LEFT"]},
{"type":"BUTTON","bindings":["GAMEPAD_BUTTON_A"],"x":0.1,"y":0.1}
]}"""
val (layout, actions) = import(raw)!!
assertEquals("DroidDeck", layout.name)
assertEquals(listOf(InputElementKind.BUTTON, InputElementKind.BUTTON, InputElementKind.STICK, InputElementKind.STICK, InputElementKind.DPAD), layout.elements.map { it.kind })
val jump = layout.elements[0]
assertEquals("Jump", jump.name)
assertEquals(.5f, jump.opacity, .001f)
assertEquals(InputButtonShape.CIRCLE, jump.buttonShape)
assertEquals(.8f, jump.x + jump.width / 2, .001f)
assertEquals(6f * 10f * 1.2f / 500f, jump.height, .002f)
assertTrue(layout.elements[1].toggle)
assertEquals(InputAction.Keys(listOf(29, 46)), actions.action(layout.elements[1]))
assertEquals(InputAction.Directions(17, 32, 31, 30, listOf(0, 0, 0, 0)), actions.action(layout.elements[2]))
assertEquals(InputAction.Directions(103, 106, 108, 105, listOf(0, 0, 0, 0)), actions.action(layout.elements[3]))
assertEquals(InputAction.Directions(23, 38, 37, 36), actions.action(layout.elements[4]))
}
@Test fun rejectsFilesWithoutUsableControls() {
assertNull(import("not json"))
assertNull(import("""{"name":"x"}"""))
assertNull(import("""{"elements":[{"type":"BUTTON","bindings":["GAMEPAD_BUTTON_A"]}]}"""))
val (layout, _) = import("""{"elements":[{"type":"BUTTON","bindings":["KEY_E"],"x":"bad","scale":-1}]}""")!!
assertEquals("Fallback", layout.name)
assertEquals(.5f, layout.elements.single().x + layout.elements.single().width / 2, .001f)
}
@Test fun layoutsWithoutKeyBindingsHaveNothingToExport() {
val library = InputLibraries.read(context)
val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY }
assertNull(InputLayoutFile.export(gamepad, library.bindings.firstOrNull { it.layoutId == gamepad.id }, 1000, 500))
assertEquals("A_B_.icp", InputLayoutFile.fileName(gamepad.copy(name = "A/B?")))
}
}
@@ -0,0 +1,194 @@
package com.droiddeck.launcher.input
import android.content.Context
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 InputLayoutToolsTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun scaleAllResizesEveryElementAroundItsCentreInsideTheScreen() {
val elements = listOf(InputSurfaceElement(InputControl.A, .4f, .4f, .2f, .2f, "a", name = "A"),
InputSurfaceElement(InputControl.A, 0f, .9f, .1f, .1f, "b", name = "B"))
val bigger = elements.scaled(1.25f)
assertEquals(.25f, bigger[0].width, .0001f)
assertEquals(.5f, bigger[0].x + bigger[0].width / 2, .0001f)
assertEquals(.5f, bigger[0].y + bigger[0].height / 2, .0001f)
assertEquals(0f, bigger[1].x, .0001f)
assertEquals(1f, bigger[1].y + bigger[1].height, .0001f)
assertTrue(bigger.all { it == it.bounded() })
assertEquals(.16f, elements.scaled(.8f)[0].height, .0001f)
assertEquals(elements.map { it.name }, bigger.map { it.name })
}
@Test fun resetPositionsOnlyRestoresGeometryOfElementsTheDefaultsKnow() {
val defaults = listOf(InputSurfaceElement(InputControl.A, .1f, .1f, .2f, .2f, "legacy:a"))
val moved = listOf(defaults[0].copy(x = .5f, y = .6f, width = .3f, name = "Jump", opacity = .5f),
InputSurfaceElement(InputControl.A, .3f, .3f, .1f, .1f, "custom", name = "Custom"))
val reset = moved.withPositionsOf(defaults)
assertEquals(defaults[0].copy(name = "Jump", opacity = .5f), reset[0])
assertEquals(moved[1], reset[1])
}
@Test fun copiesRememberTheirOriginSoStockPositionsCanBeRestored() {
val library = InputLibraries.read(context)
val copied = library.copyLayout(InputLibraries.DECK, "Mine", "mine")
val mine = copied.layouts.first { it.id == "mine" }
assertEquals(InputLibraries.DECK, mine.origin)
assertEquals(InputLibraries.DECK, copied.copyLayout("mine", "Again", "again").layouts.first { it.id == "again" }.origin)
val independent = library.useLayout(InputProfile.GAME, InputRole.SECONDARY, InputLibraries.DECK, shared = false)
assertEquals(InputLibraries.DECK, independent.layout(InputProfile.GAME, InputRole.SECONDARY)!!.origin)
val stock = InputStockLayouts.layouts().first { it.id == InputLibraries.DECK }.elements
val dragged = mine.copy(elements = mine.elements.map { it.copy(x = 0f, y = 0f) })
assertEquals(stock, InputLibraries.defaultPositions(context, copied, dragged))
assertEquals(mine.elements, dragged.elements.withPositionsOf(stock))
assertEquals(copied, InputLibraries.decode(InputLibraries.encode(copied)))
}
@Test fun builtInGamepadDefaultsComeFromTheGamepadGenerator() {
val library = InputLibraries.read(context)
val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY }
val defaults = InputLibraries.defaultPositions(context, library, gamepad)!!
assertEquals(gamepad.elements.map { it.id }.toSet(), defaults.map { it.id }.toSet())
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 }
assertThrows(IllegalArgumentException::class.java) {
library.withLayout(gamepad.copy(style = gamepad.style.copy(hidden = setOf(InputCommand.MENU)))).validate()
}
val custom = InputSurfaceElement(InputControl.A, .1f, .1f, .1f, .1f, "custom", name = "Steam")
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"))
val right = listOf(InputSurfaceElement(InputControl.A, .7f, .2f, .1f, .1f, "three", name = "Three"),
InputSurfaceElement(InputControl.A, .85f, .2f, .1f, .1f, "four", name = "Four"))
for (pair in listOf(left, right)) {
val gap = pair[1].x - (pair[0].x + pair[0].width)
val bigger = pair.scaled(1.25f)
assertEquals(gap * 1.25f, bigger[1].x - (bigger[0].x + bigger[0].width), .0001f)
val smaller = pair.scaled(.8f)
assertEquals(gap * .8f, smaller[1].x - (smaller[0].x + smaller[0].width), .0001f)
assertTrue((bigger + smaller).all { it.x >= 0f && it.x + it.width <= 1.0001f && it.y >= 0f && it.y + it.height <= 1.0001f })
}
}
@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))
}
@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 }
})
}
}
}
}
@@ -19,11 +19,12 @@ class InputLibraryTest {
for (name in listOf("input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun freshLibraryHasOnlyTheMainGamepadAndTwoLowerScreenLayouts() {
@Test fun freshLibraryHasTheMainGamepadAndTheStockLowerScreenLayouts() {
val library = InputLibraries.read(context)
assertEquals(listOf("game", "desktop"), library.profiles.map { it.id })
assertEquals(setOf(InputLibraries.OVERLAY, InputLibraries.DECK, InputLibraries.TRACKPAD), library.layouts.map { it.id }.toSet())
assertEquals(6, library.bindings.size)
assertEquals(setOf(InputLibraries.OVERLAY, InputLibraries.TRACKPAD) + DeckPanel.entries.map { it.layout }, library.layouts.map { it.id }.toSet())
assertEquals(10, library.bindings.size)
for (panel in DeckPanel.entries) assertEquals(panel.layout, library.panelLayout(false, panel.bindings)?.id)
assertEquals(InputLibraries.DECK, library.activeLayout(false, InputRole.SECONDARY)?.id)
assertEquals(InputLibraries.TRACKPAD, library.activeLayout(true, InputRole.SECONDARY)?.id)
assertEquals(InputAction.Pointer(), library.compileActive(true).action(InputRole.PHYSICAL, InputControl.LS))
@@ -32,22 +33,18 @@ class InputLibraryTest {
val desktop = library.activeLayout(true, InputRole.SECONDARY)!!
val pad = desktop.elements.single { it.kind == InputElementKind.TRACKPAD }
assertTrue(pad.mouseGestures)
assertEquals(3, desktop.elements.size)
assertEquals(1, desktop.elements.size)
assertEquals(InputAction.Pointer(), library.compileActive(true).elementAction(InputRole.SECONDARY, pad.id, pad.control))
assertEquals(InputAction.MouseButton(272), library.compileActive(true).elementClickAction(InputRole.SECONDARY, pad))
val game = library.activeLayout(false, InputRole.SECONDARY)!!
assertEquals(9, game.elements.size)
assertEquals(6, game.elements.size)
assertEquals(setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD), game.elements.filter { it.kind == InputElementKind.TRACKPAD }.map { it.control }.toSet())
for (control in listOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)) {
val element = game.elements.single { it.control == control }
assertEquals(InputAction.Native(), library.compileActive(false).elementAction(InputRole.SECONDARY, element.id, element.control))
}
for ((isDesktop, commands) in listOf(true to listOf(InputCommand.MENU, InputCommand.KEYBOARD),
false to listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.MENU))) {
val elements = library.activeLayout(isDesktop, InputRole.SECONDARY)!!.elements.filter { it.id.startsWith("command:") }
assertEquals(commands.map { InputAction.Command(it) }, elements.map { library.compileActive(isDesktop).elementAction(InputRole.SECONDARY, it.id, it.control) })
assertTrue(elements.all { InputButtonIcons.has(it.icon) && it.icon > 255 })
}
for (layout in InputStockLayouts.layouts()) assertTrue(layout.elements.none { it.id.startsWith("command:") })
assertTrue(game.elements.filter { it.kind == InputElementKind.TRACKPAD }.all { it.y == .02f })
assertEquals(library, InputLibraries.decode(InputLibraries.encode(library)))
}
@@ -71,11 +68,11 @@ class InputLibraryTest {
assertEquals(original, InputLibraries.read(context))
}
@Test fun resettingDefaultActionsKeepsTheMenuAndKeyboardCommands() {
@Test fun resettingDefaultActionsKeepsTheStockPanelActions() {
val library = InputLibraries.read(context)
for (id in listOf("game", "desktop")) {
val reset = library.resetProfile(id).validate()
for (element in library.layout(id, InputRole.SECONDARY)!!.elements.filter { it.id.startsWith("command:") }) {
for (element in library.layout(id, InputRole.SECONDARY)!!.elements) {
assertEquals(library.compile(id).elementAction(InputRole.SECONDARY, element.id, element.control),
reset.compile(id).elementAction(InputRole.SECONDARY, element.id, element.control))
}
@@ -460,7 +457,7 @@ class InputLibraryTest {
assertTrue(upgraded.layout("game", InputRole.SECONDARY)!!.editable)
val output = upgraded.compile("game")
assertEquals(InputAction.Keys(listOf(57)), output.elementAction(InputRole.SECONDARY, "legacy:l4", InputControl.L4))
assertEquals(InputAction.Command(InputCommand.MENU), output.elementAction(InputRole.SECONDARY, "command:0", InputControl.A))
assertEquals(InputStockLayouts.layouts().single { it.id == InputLibraries.DECK }.elements, upgraded.layout("game", InputRole.SECONDARY)!!.elements)
assertEquals(upgraded, InputLibraries.read(context))
}
@@ -473,7 +470,9 @@ class InputLibraryTest {
val copy = changed.layout("game", role)!!
assertNotEquals(layout.id, copy.id)
assertEquals(layout.elements, copy.elements)
assertEquals(InputAction.Command(InputCommand.MENU), changed.compile("game").elementAction(role, "command:0", InputControl.A))
val stock = InputStockLayouts.presets(listOf(layout)).single()
for (element in layout.elements) assertEquals(stock.elements[element.id] ?: stock.controls[element.control] ?: InputAction.Native(),
changed.compile("game").elementAction(role, element.id, element.control))
}
}
@@ -533,4 +532,64 @@ class InputLibraryTest {
assertEquals(ControllerPrefs.STEAM_BLUE, upgraded.layouts.single { it.id == InputLibraries.OVERLAY }.style.tint)
assertEquals(upgraded, InputLibraries.read(context))
}
private fun versionElevenPanel(layout: SavedInputLayout, commands: List<Int>, padTop: Float = .14f) = layout.copy(elements = commands.mapIndexed { position, i ->
InputSurfaceElement(InputControl.A, .02f + position * .3f, .01f, .28f, .11f, "command:$i", name = "Command $i", icon = InputButtonIcons.MENU)
} + layout.elements.map { if (it.kind == InputElementKind.TRACKPAD) it.copy(y = padTop, height = it.y + it.height - padTop) else it })
private fun versionElevenLibrary(change: (InputLibrary) -> InputLibrary = { it }): InputLibrary {
val fresh = InputLibraries.read(context)
val stock = InputStockLayouts.layouts()
var old = fresh.copy(layouts = fresh.layouts.filter { it.id == InputLibraries.OVERLAY || it.id == InputLibraries.DECK || it.id == InputLibraries.TRACKPAD },
bindings = fresh.bindings.filter { b -> DeckPanel.entries.none { it != DeckPanel.BOTH && it.bindings == b.id } })
old = old.withLayout(versionElevenPanel(stock.single { it.id == InputLibraries.DECK }, listOf(2, 3, 0)))
.withLayout(versionElevenPanel(stock.single { it.id == InputLibraries.TRACKPAD }, listOf(0, 1)))
old = old.copy(bindings = old.bindings.map { b ->
when (b.layoutId) {
InputLibraries.DECK -> b.copy(elements = b.elements + mapOf("command:0" to InputAction.Command(InputCommand.MENU), "command:2" to InputAction.Command(InputCommand.STEAM)))
InputLibraries.TRACKPAD -> b.copy(elements = b.elements + ("command:1" to InputAction.Command(InputCommand.KEYBOARD)))
else -> b
}
})
return change(old).validate()
}
private fun storeVersionEleven(library: InputLibrary) {
prefs.edit().putString("library", JSONObject(InputLibraries.encode(library)).put("version", 11).toString()).commit()
}
@Test fun versionTwelveMovesStockPanelCommandsToTheBarAndAddsTheDeckTabs() {
val mine = SavedInputLayout("mine", "Mine", listOf(InputSurfaceElement(InputControl.A, .1f, .1f, .2f, .2f, "command:0", name = "Menu")),
screen = InputLayoutScreen.SECONDARY)
val minePreset = SavedInputBindings("mine.bindings", "Mine", false, mine.id, elements = mapOf("command:0" to InputAction.Command(InputCommand.MENU)))
val old = versionElevenLibrary { it.withLayout(mine).withPreset(minePreset) }
assertTrue(old.layouts.single { it.id == InputLibraries.DECK }.elements.any { it.id.startsWith("command:") })
storeVersionEleven(old)
val upgraded = InputLibraries.read(context)
val stock = InputStockLayouts.layouts()
for (id in listOf(InputLibraries.DECK, InputLibraries.TRACKPAD))
assertEquals(stock.single { it.id == id }.elements, upgraded.layouts.single { it.id == id }.elements)
assertTrue(upgraded.bindings.filter { it.layoutId == InputLibraries.DECK || it.layoutId == InputLibraries.TRACKPAD }
.all { b -> b.elements.keys.none { it.startsWith("command:") } })
assertEquals(InputAction.Pointer(), upgraded.preset(InputStockLayouts.TRACKPAD).elements["legacy:right-pad"])
assertEquals(mine, upgraded.layouts.single { it.id == mine.id })
assertEquals(minePreset, upgraded.preset(minePreset.id))
for (panel in DeckPanel.entries) {
assertEquals(stock.single { it.id == panel.layout }, upgraded.layouts.single { it.id == panel.layout })
assertEquals(panel.layout, upgraded.preset(panel.bindings).layoutId)
}
assertEquals(old.profiles, upgraded.profiles)
assertEquals(upgraded, InputLibraries.read(context))
}
@Test fun versionTwelveLeavesEditedStockPanelsAlone() {
val old = versionElevenLibrary { library ->
val trackpad = library.layouts.single { it.id == InputLibraries.TRACKPAD }
library.withLayout(trackpad.copy(elements = trackpad.elements.map { if (it.kind == InputElementKind.TRACKPAD) it.copy(x = .1f, width = .8f) else it }))
}
storeVersionEleven(old)
val upgraded = InputLibraries.read(context)
assertEquals(old.layouts.single { it.id == InputLibraries.TRACKPAD }, upgraded.layouts.single { it.id == InputLibraries.TRACKPAD })
assertEquals(old.preset(InputStockLayouts.TRACKPAD), upgraded.preset(InputStockLayouts.TRACKPAD))
assertEquals(InputStockLayouts.layouts().single { it.id == InputLibraries.DECK }.elements, upgraded.layouts.single { it.id == InputLibraries.DECK }.elements)
}
}
@@ -70,8 +70,6 @@ class InputProfilesTest {
assertEquals(InputProfile.defaults(InputProfile.GAME).bindings, profile.bindings)
assertEquals(mapOf(
InputRole.PRIMARY to mapOf("builtin:keyboard" to InputAction.Command(InputCommand.KEYBOARD)),
InputRole.SECONDARY to mapOf("command:0" to InputAction.Command(InputCommand.MENU),
"command:2" to InputAction.Command(InputCommand.STEAM), "command:3" to InputAction.Command(InputCommand.QUICK_ACCESS)),
), profile.elements)
}
@@ -146,9 +146,28 @@ class InputRouterTest {
val source = router.pad(InputRole.PHYSICAL)
val raw = PadState()
for (value in listOf(.6f, .5f, .4f, .6f, .3f, .6f)) { raw.leftTrigger = value; source.route(raw) }
assertEquals(listOf("MENU"), output.events)
raw.leftTrigger = 0f; source.route(raw)
assertEquals(listOf("MENU", "MENU"), output.events)
}
@Test fun commandsFireOnReleaseAndNotWhenCancelled() {
router.setProfile(bind(InputControl.A, InputAction.Command(InputCommand.KEYBOARD), InputRole.PRIMARY))
val button = router.channel(InputRole.PRIMARY, InputControl.A)
button.update(1f)
assertTrue(output.events.isEmpty())
button.update(0f)
assertEquals(listOf("KEYBOARD"), output.events)
button.update(1f)
button.release()
button.update(0f)
router.releaseAll()
button.update(1f)
router.releaseAll()
button.update(0f)
assertEquals(listOf("KEYBOARD"), output.events)
}
@Test fun pointerTicksOnlyWhileMovingAndOrdinaryKeysDoNotWaitForTick() {
router.setProfile(InputProfile.defaults(InputProfile.DESKTOP))
val source = router.pad(InputRole.PHYSICAL)
@@ -25,7 +25,7 @@ class OnScreenControlsTest {
private var time = 1000L
@Before fun setup() {
view = OnScreenControls(context, bridge)
view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button)))
view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button), aspect = ASPECT))
measure(view)
}
@After fun close() { view.releaseAll(); bridge.stop() }
@@ -102,7 +102,7 @@ class OnScreenControlsTest {
@Test fun floatingAndFixedSticksUseTheirConfiguredOrigin() {
for (floating in listOf(true, false)) {
view.updateLayout(SavedInputLayout("test", "Test", listOf(left.copy(floating = floating))))
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)
@@ -110,16 +110,18 @@ class OnScreenControlsTest {
}
}
@Test fun systemOnlyVisibilityUsesTheSameLayoutAndReleasesOtherButtons() {
@Test fun systemOnlyVisibilityMovesSteamAndQamToTheBottomCornersAndReleasesOtherButtons() {
val guide = InputSurfaceElement(InputControl.GUIDE, .4f, .7f, .1f, .2f)
view.updateLayout(SavedInputLayout("test", "Test", listOf(button, guide)))
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))
assertTrue(view.takesTouchAt(450f, 480f))
assertFalse(view.takesTouchAt(450f, 480f))
assertTrue(view.takesTouchAt(44f, 556f))
assertTrue(view.takesTouchAt(956f, 556f))
}
@Test fun aCancelledSecondFingerDoesNotArmAStickClick() {
@@ -177,7 +179,7 @@ class OnScreenControlsTest {
@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)))
view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button, keyboard), aspect = ASPECT))
measure(view)
val density = context.resources.displayMetrics.density
val x = 34 * density
@@ -199,9 +201,12 @@ class OnScreenControlsTest {
assertTrue(view.takesTouchAt(800f, 250f))
view.setButtonsOnly(true)
measure(view)
assertFalse(view.takesTouchAt(x, y))
touch(MotionEvent.ACTION_DOWN, 6 to (x to y)); touch(MotionEvent.ACTION_UP, 6 to (x to y))
assertFalse(view.isQuickHidden)
}
private companion object { const val ASPECT = 1000f / 600f }
private fun touch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>, flags: Int = 0): Boolean {
val properties = pointers.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray()
val coords = pointers.map { (_, position) -> MotionEvent.PointerCoords().apply { x = position.first; y = position.second; pressure = 1f; size = 1f } }.toTypedArray()
@@ -0,0 +1,191 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Rect
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 OnScreenLayoutTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
private val prefs get() = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
private val density get() = context.resources.displayMetrics.density
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
private fun gamepad() = InputLibraries.read(context).layouts.first { it.id == InputLibraries.OVERLAY }
private fun px(e: InputSurfaceElement, w: Int, h: Int) = floatArrayOf(e.x * w, e.y * h, e.width * w, e.height * h)
private fun assertSquare(e: InputSurfaceElement, w: Int, h: Int) = assertEquals(e.width * w, e.height * h, 1.5f)
private fun assertInside(elements: List<InputSurfaceElement>, w: Int, h: Int, safe: Rect = Rect()) {
for (e in elements) {
val (x, y, ew, eh) = px(e, w, h).toList()
assertTrue("${e.id} left", x >= safe.left - .5f)
assertTrue("${e.id} top", y >= safe.top - .5f)
assertTrue("${e.id} right", x + ew <= w - safe.right + .5f)
assertTrue("${e.id} bottom", y + eh <= h - safe.bottom + .5f)
}
}
@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 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)
val middle = InputSurfaceElement(InputControl.GUIDE, .45f, .05f, .1f, .2f)
val layout = SavedInputLayout("edited", "Edited", listOf(left, corner, middle), aspect = 2f)
assertEquals(layout.elements, OnScreenLayout.elements(context, layout, 2000, 1000, Rect()).map { it.copy(x = round(it.x), y = round(it.y), width = round(it.width), height = round(it.height)) })
val portrait = OnScreenLayout.elements(context, layout, 1000, 2000, Rect())
val (lx, ly, lw, lh) = px(portrait[0], 1000, 2000).toList()
val (cx, cy, cw, ch) = px(portrait[1], 1000, 2000).toList()
assertEquals(lw, lh, 1f)
assertEquals(cw, ch, 1f)
assertEquals(200f, lw, 1f)
assertEquals(50f, lx, 1f)
assertEquals(2000f, ly + lh + 50f, 1f)
assertEquals(1000f - 50f, cx + cw, 1f)
assertEquals(2000f - 50f, cy + ch, 1f)
assertEquals(500f, px(portrait[2], 1000, 2000).let { it[0] + it[2] / 2f }, 1f)
assertInside(portrait, 1000, 2000)
}
private fun round(v: Float) = Math.round(v * 10000f) / 10000f
@Test fun controlsStayOutOfTheDisplayCutout() {
val safe = Rect(120, 0, 0, 40)
val generated = OnScreenLayout.elements(context, gamepad(), 2400, 1080, safe)
assertInside(generated, 2400, 1080, safe)
assertNotEquals(OnScreenLayout.elements(context, gamepad(), 2400, 1080, Rect()), generated)
val edge = SavedInputLayout("edited", "Edited", listOf(InputSurfaceElement(InputControl.B, 0f, .9f, .05f, .1f)), aspect = 2400f / 1080)
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
val placed = OnScreenLayout.elements(context, gamepad(), w, h, Rect(), dock = OnScreenLayout.Dock(portrait, grips = true))
val boxes = GamepadGeometry.layout(w.toFloat(), h.toFloat(), density, portrait)
val ls = placed.first { it.id == "legacy:ls" }
val box = boxes.getValue(GamepadGeometry.Slot.LEFT_MAIN)
assertEquals(box.left, ls.x * w, 1f)
assertEquals(box.width, ls.width * w, 1f)
assertEquals(box.height, ls.height * h, 1f)
assertSquare(placed.first { it.id == "legacy:a" }, w, h)
assertNull(placed.firstOrNull { it.control == InputControl.GUIDE || it.control == InputControl.QAM })
assertEquals(portrait, placed.any { it.control == InputControl.L4 })
assertInside(placed, w, h)
val solid = placed.filter { it.kind != InputElementKind.STICK }
for (a in solid) for (b in solid) if (a !== b) {
val overlap = if (a.buttonShape == InputButtonShape.CIRCLE && b.buttonShape == InputButtonShape.CIRCLE)
Math.hypot(((a.x + a.width / 2f) - (b.x + b.width / 2f)) * w.toDouble(), ((a.y + a.height / 2f) - (b.y + b.height / 2f)) * h.toDouble()) <
(a.width * w + b.width * w) / 2f - .5f
else a.x < b.x + b.width - .0001f && b.x < a.x + a.width - .0001f && a.y < b.y + b.height - .0001f && b.y < a.y + a.height - .0001f
assertFalse("${a.id} overlaps ${b.id}", overlap)
}
}
val user = SavedInputLayout("edited", "Edited", listOf(InputSurfaceElement(InputControl.A, .8f, .6f, .1f, .2f)), aspect = 2208f / 1768)
val fitted = OnScreenLayout.elements(context, user, 2208, 800, Rect(), dock = OnScreenLayout.Dock(false, false)).single()
assertEquals(.1f * 2208f / 1768 / .2f, fitted.width * 2208 / (fitted.height * 800), .01f)
}
private val legacyKeys = "29+33:0.3,0.7,44::Find::0.6:1:1:1"
private fun importedOn(library: InputLibrary) = library.activeLayout(false, InputRole.PRIMARY)!!.elements.filter { it.id.startsWith("imported:") }
@Test fun shownScreenKeysAreDrawnWithTheGamepadAfterMigration() {
val before = gamepad()
prefs.edit().clear().commit()
ControllerPrefs.prefs(context).edit().putString("screenKeys", legacyKeys).commit()
val migrated = InputLibraries.read(context)
val layout = migrated.activeLayout(false, InputRole.PRIMARY)!!
assertEquals(InputLibraries.OVERLAY, layout.id)
assertEquals(before.elements, layout.elements.filterNot { it.id.startsWith("imported:") })
assertEquals(1, importedOn(migrated).size)
assertEquals(InputAction.Keys(listOf(29, 33)), migrated.compileActive(false).elementAction(InputRole.PRIMARY, "imported:0", InputControl.A))
assertEquals(InputAction.Native(), migrated.compileActive(false).elementAction(InputRole.PRIMARY, "legacy:a", InputControl.A))
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 librariesMigratedBeforeTheMergeGetTheirScreenKeysBackOnceWithoutLosingEdits() {
val fresh = InputLibraries.read(context)
val backup = JSONObject().put("screenKeys", legacyKeys).toString()
val old = LegacyScreenKeyMigration.migrate(context, fresh, backup)
val bindings = old.activePart(false, InputRole.PRIMARY).bindings
val edited = old.withPreset(old.preset(bindings).let { it.copy(controls = it.controls + (InputControl.A to InputAction.Keys(listOf(57)))) })
prefs.edit().putString("library", InputLibraries.encode(edited)).putString(LegacyScreenKeyMigration.BACKUP, backup).commit()
val merged = InputLibraries.read(context)
assertEquals(1, importedOn(merged).size)
assertEquals(InputAction.Keys(listOf(57)), merged.compileActive(false).action(InputRole.PRIMARY, InputControl.A))
assertEquals(edited.profiles, merged.profiles)
assertEquals(edited.layouts.map { it.id }.toSet(), merged.layouts.map { it.id }.toSet())
assertEquals(edited.layouts.first { it.id == "migrated.screenkeys.0.layout" }, merged.layouts.first { it.id == "migrated.screenkeys.0.layout" })
assertEquals(backup, prefs.getString(LegacyScreenKeyMigration.BACKUP, null))
assertEquals(merged, InputLibraries.read(context))
prefs.edit().remove(LegacyScreenKeyMigration.MERGED).commit()
assertEquals(1, importedOn(InputLibraries.read(context)).size)
}
@Test fun hiddenScreenKeysOrAProfileThatAlreadyShowsThemAreLeftAlone() {
val fresh = InputLibraries.read(context)
val hidden = JSONObject().put("screenKeys", legacyKeys).put("screenKeysShown", false).toString()
val old = LegacyScreenKeyMigration.migrate(context, fresh, hidden)
assertEquals(old, LegacyScreenKeyMigration.merge(old, hidden))
val shown = JSONObject().put("screenKeys", legacyKeys).toString()
val selected = old.selectProfile(false, "migrated.screenkeys.0").selectProfile(true, "migrated.screenkeys.0")
assertEquals(selected, LegacyScreenKeyMigration.merge(selected, shown))
}
}
@@ -143,6 +143,21 @@ class SettingsResetTest {
assertEquals(defaultSurface, InputSurfaceLayout.read(app, InputProfile.DESKTOP))
}
@Test fun inputLayoutsAndQuickButtonVisibilityReset() {
val original = com.droiddeck.launcher.input.InputLibraries.read(app)
val gamepad = original.layouts.first { it.id == com.droiddeck.launcher.input.InputLibraries.OVERLAY }
com.droiddeck.launcher.input.InputLibraries.update(app) { library ->
library.withLayout(gamepad.withQuickButton(com.droiddeck.launcher.input.InputCommand.STEAM, false)
.copy(elements = gamepad.elements.map { it.copy(x = 0f, y = 0f) })).copyLayout(gamepad.id, "Mine", "mine")
}
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
val reset = com.droiddeck.launcher.input.InputLibraries.read(app)
assertEquals(original.layouts.map { it.id }.toSet(), reset.layouts.map { it.id }.toSet())
assertEquals(gamepad, reset.layouts.first { it.id == gamepad.id })
}
@Test fun gameTextureFilteringIsKeptUnlessGameProfilesAreReset() {
session.edit().putString("gameTextureFiltering", """{"440":{"anisotropy":16}}""").commit()
SettingsReset.resetAll(app, gameProfiles = false)
@@ -5,6 +5,7 @@ import android.app.Presentation
import android.hardware.display.DisplayManager
import android.view.Display
import androidx.compose.runtime.mutableStateOf
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.test.*
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.R
@@ -379,4 +380,147 @@ class InputSettingsTest {
if (display.isValid) ShadowDisplayManager.removeDisplay(displayId)
}
}
@Test fun elementPropertiesEditOpacityLabelsAndOfferImages() {
val element = mutableStateOf(InputSurfaceElement(InputControl.A, .1f, .1f, .2f, .2f, "custom", name = "Custom button"))
compose.setContent { DroidDeckTheme {
androidx.compose.foundation.layout.Column(androidx.compose.ui.Modifier.verticalScroll(androidx.compose.foundation.rememberScrollState())) {
InputElementProperties(element.value) { element.value = it }
}
} }
compose.onNodeWithTag("setting-element-opacity").performScrollTo().performSemanticsAction(androidx.compose.ui.semantics.SemanticsActions.SetProgress) { it(60f) }
compose.runOnIdle { assertEquals(.6f, element.value.opacity, .001f) }
compose.onNodeWithTag("setting-element-label").performScrollTo().performClick()
compose.runOnIdle { assertFalse(element.value.showLabel) }
compose.onNodeWithText(context.getString(R.string.input_button_text)).performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.screen_key_image)).assertExists()
compose.runOnIdle { element.value = element.value.copy(icon = InputButtonIcons.MENU) }
compose.onNodeWithTag("setting-element-label").assertDoesNotExist()
compose.runOnIdle { element.value = InputSurfaceElement(InputControl.LEFT_PAD, .1f, .1f, .4f, .4f, "pad", InputElementKind.TRACKPAD, "Pad") }
compose.onNodeWithTag("setting-element-label").assertDoesNotExist()
compose.onNodeWithTag("setting-element-opacity").assertExists()
}
@Test fun editorScalesEveryControlAndRestoresStockPositions() {
val library = InputLibraries.read(context)
val layout = library.layout("game", InputRole.SECONDARY)!!
assertEquals(InputLibraries.DECK, layout.id)
val round = mutableStateOf(0)
compose.setContent { DroidDeckTheme { androidx.compose.runtime.key(round.value) { InputSurfaceDialog("game", {}, {}, role = InputRole.PRIMARY,
layoutId = layout.id, bindingsId = library.profile("game").binding(InputRole.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.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.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle { assertEquals(layout.elements, InputLibraries.read(context).layouts.first { it.id == layout.id }.elements) }
}
@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"}]}""")
}
val target = java.io.File(context.cacheDir, "out.icp").apply { delete() }
val registry = object : androidx.activity.result.ActivityResultRegistry() {
override fun <I, O> onLaunch(requestCode: Int, contract: androidx.activity.result.contract.ActivityResultContract<I, O>, input: I,
options: androidx.core.app.ActivityOptionsCompat?) {
dispatchResult(requestCode, android.net.Uri.fromFile(if (input is String) target else source))
}
}
val owner = object : androidx.activity.result.ActivityResultRegistryOwner { override val activityResultRegistry = registry }
compose.setContent { androidx.compose.runtime.CompositionLocalProvider(androidx.activity.compose.LocalActivityResultRegistryOwner provides owner) {
DroidDeckTheme { InputSettingsPage({}) }
} }
compose.onNodeWithTag("input-profile-game").performScrollTo().performClick()
compose.onNodeWithTag("input-part-primary").performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.input_saved_layouts)).performScrollTo().performClick()
compose.onNodeWithTag("layout-manage-${InputLibraries.OVERLAY}").performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.screen_key_layout_export)).assertDoesNotExist()
compose.onNodeWithText(context.getString(R.string.common_close)).performClick()
compose.onNodeWithTag("input-layout-import").performScrollTo().performClick()
compose.waitUntil(5_000) { InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!.name == "Jump keys" }
val imported = InputLibraries.read(context).layout("game", InputRole.PRIMARY)!!
assertEquals(InputLayoutScreen.MAIN, imported.screen)
assertEquals(InputAction.Keys(listOf(57)), InputLibraries.read(context).compile("game").elementAction(InputRole.PRIMARY, imported.elements.single().id, InputControl.A))
compose.onNodeWithText(context.getString(R.string.input_saved_layouts)).performScrollTo().performClick()
compose.onNodeWithTag("layout-manage-${imported.id}").performScrollTo().performClick()
compose.onNodeWithText(context.getString(R.string.screen_key_layout_export)).performClick()
compose.waitUntil(5_000) { target.isFile && target.length() > 0 }
assertEquals(source.readText().let { org.json.JSONObject(it).getString("name") }, org.json.JSONObject(target.readText()).getString("name"))
assertEquals("KEY_SPACE", org.json.JSONObject(target.readText()).getJSONArray("elements").getJSONObject(0).getJSONArray("bindings").getString(0))
}
@Test fun buttonSizeRegeneratesTheGamepadAndUndoesAsOneStep() {
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))
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) }
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) }
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)
}
}
@Test @Config(qualifiers = "w833dp-h468dp-land-369dpi")
fun buttonSizeKeepsMovedGamepadGroupsInShape() {
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 })
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) }
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
fun centre(id: String) = saved.elements.first { it.id == id }.let { (it.x + it.width / 2) * w to (it.y + it.height / 2) * h }
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)
val before = moved.elements.first { it.id == "legacy:a" }
assertTrue(saved.elements.first { it.id == "legacy:a" }.width > before.width * 1.2f)
}
}
}
@@ -93,8 +93,7 @@ class InputSurfaceOwnershipTest {
@Test fun removingAButtonReleasesOnlyItsOwnInput() {
val buttons = child("HoldButton")
buttons.layout(0, 0, 300, 300)
touch(buttons, MotionEvent.ACTION_DOWN, 150f, 240f)
press(buttons)
assertTrue(state().isDown(PadState.A))
val position = JoyConPadTest.RecordingWriter.deckPads.copyOf()
(buttons.parent as ViewGroup).removeView(buttons)
@@ -123,8 +122,7 @@ class InputSurfaceOwnershipTest {
private fun holdFaceButton() {
val buttons = child("HoldButton")
buttons.layout(0, 0, 300, 300)
touch(buttons, MotionEvent.ACTION_DOWN, 150f, 240f)
press(buttons)
}
private fun assertTrackpadStillHeld(position: ShortArray) {
@@ -139,6 +137,11 @@ class InputSurfaceOwnershipTest {
if (view is ViewGroup) for (i in 0 until view.childCount) yieldAll(descendants(view.getChildAt(i)))
}
private fun press(button: View) {
button.javaClass.getDeclaredMethod("press", Int::class.java, Boolean::class.java, Boolean::class.java)
.apply { isAccessible = true }.invoke(button, 0, true, false)
}
private fun touch(view: View, action: Int, x: Float, y: Float, fingers: Int = 1) {
val properties = Array(fingers) { i -> MotionEvent.PointerProperties().apply { id = i; toolType = MotionEvent.TOOL_TYPE_FINGER } }
val coords = Array(fingers) { MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f; size = 1f } }
@@ -0,0 +1,235 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.activity.ComponentActivity
import com.droiddeck.launcher.input.*
import java.io.File
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class])
class InputSurfaceTouchTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
private val bridge = PadBridge(File(context.cacheDir, "surface-touch"))
private val events = mutableListOf<String>()
private val router = InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) { events += "key $code $down" }
override fun button(code: Int, down: Boolean) {}
override fun pointer(dx: Float, dy: Float) {}
override fun scroll(steps: Int) {}
override fun command(command: InputCommand) { events += command.name }
override fun command(command: InputCommand, role: InputRole) { events += "${command.name}:$role" }
override fun requestMotion() {}
})
private lateinit var view: OnScreenControls
private val a = InputSurfaceElement(InputControl.A, .7f, .3f, .2f, .2f)
private val b = InputSurfaceElement(InputControl.B, .7f, .6f, .2f, .2f)
private val stick = InputSurfaceElement(InputControl.LS, .1f, .3f, .2f, .4f, floating = false)
private val keyboard = InputSurfaceElement(InputControl.A, .4f, .8f, .1f, .1f, "builtin:keyboard", name = "Keyboard")
private var time = 1000L
@Before fun setup() {
bridge.setInputRouter(router)
bridge.setInputProfile(InputProfile("touch", elements = mapOf(InputRole.PRIMARY to mapOf(
"builtin:keyboard" to InputAction.Command(InputCommand.KEYBOARD), "latch" to InputAction.Keys(listOf(42))))))
view = OnScreenControls(context, bridge)
show(a, b, stick, keyboard)
}
@After fun close() { view.releaseAll(); bridge.stop() }
private fun show(vararg elements: InputSurfaceElement) {
view.updateLayout(SavedInputLayout("touch", "Touch", elements.toList(), aspect = 1000f / 600f))
measure(view)
}
private fun measure(target: View) {
target.measure(View.MeasureSpec.makeMeasureSpec(1000, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY))
target.layout(0, 0, 1000, 600)
}
private fun state() = JoyConPadTest.RecordingWriter.pads[0] ?: PadState()
@Test fun aFingerSlidingBetweenButtonsMovesThePress() {
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f))
assertTrue(state().isDown(PadState.A))
touch(MotionEvent.ACTION_MOVE, 1 to (800f to 420f))
assertFalse(state().isDown(PadState.A))
assertTrue(state().isDown(PadState.B))
touch(MotionEvent.ACTION_MOVE, 1 to (600f to 100f))
assertFalse(state().isDown(PadState.B))
touch(MotionEvent.ACTION_MOVE, 1 to (800f to 240f))
assertTrue(state().isDown(PadState.A))
touch(MotionEvent.ACTION_UP, 1 to (800f to 240f))
assertFalse(state().isDown(PadState.A))
}
@Test fun aStickKeepsItsFingerWhenItCrossesAButton() {
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
touch(MotionEvent.ACTION_MOVE, 1 to (800f to 240f))
assertFalse(state().isDown(PadState.A))
assertEquals(1f, state().leftX, .01f)
touch(MotionEvent.ACTION_UP, 1 to (800f to 240f))
assertEquals(0f, state().leftX, 0f)
}
@Test fun mouseClicksPassThroughToTheGame() {
val missed = mutableListOf<Int>()
view.onTouchMiss = { missed += it.actionMasked }
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f), tool = MotionEvent.TOOL_TYPE_MOUSE)
touch(MotionEvent.ACTION_UP, 1 to (800f to 240f), tool = MotionEvent.TOOL_TYPE_MOUSE)
assertFalse(state().isDown(PadState.A))
assertEquals(listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP), missed)
view.onTouchMiss = null
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f), tool = MotionEvent.TOOL_TYPE_MOUSE))
assertFalse(state().isDown(PadState.A))
}
@Test fun keyboardShortcutOpensOnRelease() {
touch(MotionEvent.ACTION_DOWN, 1 to (450f to 510f))
assertTrue(events.isEmpty())
touch(MotionEvent.ACTION_UP, 1 to (450f to 510f))
assertEquals(listOf("KEYBOARD:PRIMARY"), events)
}
@Test fun cancelledDraggedOrDisabledKeyboardShortcutDoesNotOpen() {
touch(MotionEvent.ACTION_DOWN, 1 to (450f to 510f))
touch(MotionEvent.ACTION_CANCEL, 1 to (450f to 510f))
touch(MotionEvent.ACTION_UP, 1 to (450f to 510f))
touch(MotionEvent.ACTION_DOWN, 1 to (450f to 510f))
touch(MotionEvent.ACTION_UP, 1 to (450f to 510f), flags = MotionEvent.FLAG_CANCELED)
touch(MotionEvent.ACTION_DOWN, 1 to (450f to 510f))
touch(MotionEvent.ACTION_MOVE, 1 to (600f to 510f))
touch(MotionEvent.ACTION_UP, 1 to (600f to 510f))
assertTrue(events.isEmpty())
show(a, b, stick)
view.setQuickHidden(true)
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)
measure(view)
assertFalse(view.takesTouchAt(800f, 240f))
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)
}
@Test fun hidingTheViewReleasesLatchedKeys() {
val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup()
try {
controller.get().setContentView(view)
show(InputSurfaceElement(InputControl.A, .7f, .3f, .2f, .2f, "latch", toggle = true))
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f))
touch(MotionEvent.ACTION_UP, 1 to (800f to 240f))
assertEquals(listOf("key 42 true"), events)
view.visibility = View.GONE
assertEquals(listOf("key 42 true", "key 42 false"), events)
} finally { controller.pause().stop().destroy() }
}
@Test fun onlyPanelsVibrateOnPress() {
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f))
assertTrue(state().isDown(PadState.A))
assertNotEquals(HapticFeedbackConstants.VIRTUAL_KEY, shadowOf(button(view)).lastHapticFeedbackPerformed())
touch(MotionEvent.ACTION_UP, 1 to (800f to 240f))
val panel = InputSurfaceView(context, bridge, listOf(a))
measure(panel)
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f), target = panel)
assertEquals(HapticFeedbackConstants.VIRTUAL_KEY, shadowOf(button(panel)).lastHapticFeedbackPerformed())
touch(MotionEvent.ACTION_CANCEL, 1 to (800f to 240f), target = panel)
}
@Test fun classicSticksTravelTheirFullRadius() {
show(stick.copy(buttonShape = InputButtonShape.CIRCLE))
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
touch(MotionEvent.ACTION_MOVE, 1 to (250f to 300f))
assertEquals(.5f, 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))
}
@Test fun buttonsAcceptTouchesJustOutsideTheirEdge() {
show(InputSurfaceElement(InputControl.A, .7f, .3f, .1f, 1f / 6f, buttonShape = InputButtonShape.CIRCLE),
InputSurfaceElement(InputControl.B, .3f, .3f, .2f, .1f, buttonShape = InputButtonShape.PILL),
InputSurfaceElement(InputControl.X, .3f, .6f, .2f, .1f))
assertTrue(view.takesTouchAt(750f, 285f))
assertTrue(view.takesTouchAt(805f, 230f))
assertFalse(view.takesTouchAt(750f, 300f))
assertFalse(view.takesTouchAt(805f, 285f))
assertTrue(view.takesTouchAt(400f, 245f))
assertFalse(view.takesTouchAt(400f, 255f))
assertFalse(view.takesTouchAt(400f, 359f))
assertTrue(view.takesTouchAt(400f, 361f))
touch(MotionEvent.ACTION_DOWN, 1 to (750f to 285f))
assertTrue(state().isDown(PadState.A))
touch(MotionEvent.ACTION_UP, 1 to (750f to 285f))
}
@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)
show(left, right)
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))
val missed = mutableListOf<Int>()
view.onTouchMiss = { missed += it.getPointerId(0) }
touch(MotionEvent.ACTION_DOWN, 1 to (50f to 300f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), 1 to (50f to 300f), 2 to (60f to 310f))
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))
assertFalse(view.takesTouchAt(10f, 300f))
assertFalse(view.takesTouchAt(815f, 300f))
}
private fun element(root: View, id: String): View = descendants(root).first { (it.tag as? InputSurfaceElement)?.id == id }
private fun centre(target: View): Pair<Float, Float> {
var x = target.width / 2f
var y = target.height / 2f
var at: View = target
while (at !== view) { x += at.left; y += at.top; at = at.parent as View }
return x to y
}
private fun button(root: View): View = descendants(root).first { it.javaClass.simpleName == "HoldButton" }
private fun descendants(root: View): Sequence<View> = sequence {
yield(root)
if (root is ViewGroup) for (i in 0 until root.childCount) yieldAll(descendants(root.getChildAt(i)))
}
private fun touch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>, flags: Int = 0,
tool: Int = MotionEvent.TOOL_TYPE_FINGER, target: View = view): Boolean {
val properties = pointers.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = tool } }.toTypedArray()
val coords = pointers.map { (_, position) -> MotionEvent.PointerCoords().apply { x = position.first; y = position.second; pressure = 1f; size = 1f } }.toTypedArray()
val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, flags)
return try { target.dispatchTouchEvent(event) } finally { event.recycle() }
}
}
@@ -110,7 +110,6 @@ class InputUiLayoutTest {
compose.onNodeWithText(context.getString(R.string.setup_tab_controller)).performClick()
compose.onNodeWithTag("input-profile-game").assertIsDisplayed()
compose.onNodeWithText(context.getString(R.string.ctrl_layout)).assertDoesNotExist()
compose.onNodeWithText(context.getString(R.string.ctrl_configure)).assertDoesNotExist()
screenshot("controller-tab")
compose.onNodeWithTag("input-profile-game").performClick()
compose.onNodeWithTag("input-part-physical").performScrollTo().performClick()
@@ -0,0 +1,229 @@
package com.droiddeck.launcher.ui
import android.hardware.display.DisplayManager
import android.view.Display
import android.view.View
import android.view.ViewGroup
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.currentComposer
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.input.DeckPanel
import com.droiddeck.launcher.input.InputLibraries
import com.droiddeck.launcher.input.InputSurfaceElement
import com.droiddeck.launcher.input.SecondScreenMode
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w800dp-h600dp")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class SecondScreenBarTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
private var previousMode = ""
private var previousDeckPad = false
@Before fun setUp() {
previousMode = SessionState.mode
previousDeckPad = SessionState.deckPad
context.getSharedPreferences("input-profiles", android.content.Context.MODE_PRIVATE).edit().clear().commit()
SessionPrefs.setDeckPanel(context, DeckPanel.BOTH)
}
@After fun tearDown() {
SessionState.mode = previousMode
SessionState.deckPad = previousDeckPad
}
private fun presentation(swap: (() -> Unit)? = {}): SecondScreenPresentation {
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
return SecondScreenPresentation(activity, display, {}, {}, {}, onMenu = {}, onSwap = swap)
}
private fun descendants(view: View): Sequence<View> = sequence {
yield(view)
if (view is ViewGroup) for (index in 0 until view.childCount) yieldAll(descendants(view.getChildAt(index)))
}
private fun rootChildren(panel: SecondScreenPresentation): List<View> {
val root: ViewGroup = ReflectionHelpers.getField(panel, "root")
return (0 until root.childCount).map { root.getChildAt(it) }
}
@Test fun trackpadPanelHasTheBarWithTheKeyboardToggleState() {
SessionState.mode = SessionService.MODE_STEAM
val panel = presentation()
try {
panel.show()
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
val children = rootChildren(panel)
assertTrue(children[0] is ComposeView)
assertTrue(children[1] is InputSurfaceView)
val bar = panel.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!
assertEquals(context.getString(R.string.second_mode_keyboard_trackpad), bar.title)
assertNotNull(bar.onClose); assertNotNull(bar.onMenu); assertNotNull(bar.onSteam); assertNotNull(bar.onQam)
assertNull(bar.tabs)
val keyboard = bar.extras.single()
assertEquals(context.getString(R.string.second_show_keyboard), keyboard.description)
assertFalse(keyboard.active)
ReflectionHelpers.getField<MutableState<Boolean>>(panel, "keyboardShown").value = true
val shown = panel.barModel(SecondScreenMode.KEYBOARD_TRACKPAD)!!.extras.single()
assertEquals(context.getString(R.string.second_hide_keyboard), shown.description)
assertTrue(shown.active)
} finally { panel.closeControls() }
}
@Test fun deckPanelHasTheBarWithSwapAndTabsAndProfileControlsStayFullScreen() {
SessionState.mode = SessionService.MODE_STEAM
SessionState.deckPad = true
var swaps = 0
val panel = presentation { swaps++ }
try {
panel.show()
panel.showMode(SecondScreenMode.DECK_CONTROLS)
assertTrue(rootChildren(panel)[0] is ComposeView)
val bar = panel.barModel(SecondScreenMode.DECK_CONTROLS)!!
assertEquals(context.getString(R.string.second_mode_deck_controls), bar.title)
assertEquals(listOf(context.getString(R.string.swap_screens)), bar.extras.map { it.description })
bar.extras.single().onClick()
assertEquals(1, swaps)
assertEquals(DeckPanel.entries.map { context.getString(it.label) }, bar.tabs!!.labels)
assertEquals(DeckPanel.BOTH.ordinal, bar.tabs!!.selected)
panel.showMode(SecondScreenMode.CUSTOM_CONTROLS)
assertNull(panel.barModel(SecondScreenMode.CUSTOM_CONTROLS))
assertTrue(rootChildren(panel)[0] is InputSurfaceView)
} finally { panel.closeControls() }
val noSwap = presentation(swap = null)
try {
noSwap.show()
noSwap.showMode(SecondScreenMode.DECK_CONTROLS)
assertTrue(noSwap.barModel(SecondScreenMode.DECK_CONTROLS)!!.extras.isEmpty())
} finally { noSwap.closeControls() }
}
@Test fun nonSteamSessionsHideSteamAndQuickAccess() {
for (mode in listOf(SessionService.MODE_DESKTOP, SessionService.MODE_RUN)) {
SessionState.mode = mode
SessionState.deckPad = true
val panel = presentation()
try {
panel.show()
for (panelMode in listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.DECK_CONTROLS)) {
panel.showMode(panelMode)
val bar = panel.barModel(panelMode)!!
assertNull(bar.onSteam); assertNull(bar.onQam)
assertNotNull(bar.onClose); assertNotNull(bar.onMenu)
}
} finally { panel.closeControls() }
}
val stock = InputLibraries.read(context).layouts.filter { it.id == InputLibraries.DECK || it.id == InputLibraries.TRACKPAD }
assertTrue(stock.all { layout -> layout.elements.none { it.id.startsWith("command:") } })
}
@Test fun deckTabsSwitchTheLayoutAndAreRemembered() {
SessionState.mode = SessionService.MODE_STEAM
SessionState.deckPad = true
val library = InputLibraries.read(context)
fun shown(panel: SecondScreenPresentation): List<InputSurfaceElement> {
val controls = descendants(panel.window!!.decorView).filterIsInstance<InputSurfaceView>().single()
return descendants(controls).mapNotNull { it.tag as? InputSurfaceElement }.toList()
}
val first = presentation()
try {
first.show()
first.showMode(SecondScreenMode.DECK_CONTROLS)
assertEquals(library.layouts.single { it.id == DeckPanel.BOTH.layout }.elements, shown(first))
val controls = descendants(first.window!!.decorView).filterIsInstance<InputSurfaceView>().single()
for (panel in listOf(DeckPanel.GRIPS, DeckPanel.LEFT, DeckPanel.RIGHT, DeckPanel.GAMEPAD)) {
first.barModel(SecondScreenMode.DECK_CONTROLS)!!.tabs!!.onSelect(panel.ordinal)
assertEquals(panel, SessionPrefs.deckPanel(context))
assertEquals(panel.ordinal, first.barModel(SecondScreenMode.DECK_CONTROLS)!!.tabs!!.selected)
assertSame(controls, descendants(first.window!!.decorView).filterIsInstance<InputSurfaceView>().single())
assertEquals(library.layouts.single { it.id == panel.layout }.elements, shown(first))
}
first.barModel(SecondScreenMode.DECK_CONTROLS)!!.tabs!!.onSelect(DeckPanel.GRIPS.ordinal)
} finally { first.closeControls() }
val second = presentation()
try {
second.show()
second.showMode(SecondScreenMode.DECK_CONTROLS)
assertEquals(DeckPanel.GRIPS.ordinal, second.barModel(SecondScreenMode.DECK_CONTROLS)!!.tabs!!.selected)
assertEquals(library.layouts.single { it.id == DeckPanel.GRIPS.layout }.elements, shown(second))
second.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
assertEquals(library.layouts.single { it.id == InputLibraries.TRACKPAD }.elements, shown(second))
} finally { second.closeControls() }
assertEquals(DeckPanel.GRIPS.bindings, SecondScreenMode.DECK_CONTROLS.panel(context))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD.bindings, SecondScreenMode.KEYBOARD_TRACKPAD.panel(context))
}
@Test fun barTabRowSelectsTabs() {
var picked = -1
compose.setContent {
DroidDeckTheme {
BottomScreenBar(BottomBarModel("Deck", {}, {}, null, null, tabs = deckPanelTabs(context, DeckPanel.BOTH) { picked = it.ordinal }))
}
}
for (panel in DeckPanel.entries) compose.onNodeWithText(context.getString(panel.label)).assertIsDisplayed()
compose.onNodeWithTag("tab-${DeckPanel.LEFT.ordinal}").performClick()
compose.runOnIdle { assertEquals(DeckPanel.LEFT.ordinal, picked) }
}
@Test fun swappedTopScreenShowsTheTerminalWithItsBar() {
SessionState.mode = SessionService.MODE_STEAM
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
ReflectionHelpers.getField<MutableState<SecondScreenMode>>(activity, "secondScreenMode\$delegate").value = SecondScreenMode.TERMINAL
val method = SessionActivity::class.java.getDeclaredMethod("SwappedTopPanel", androidx.compose.runtime.Composer::class.java, Int::class.javaPrimitiveType)
method.isAccessible = true
compose.setContent { DroidDeckTheme { method.invoke(activity, currentComposer, 0) } }
compose.onNodeWithText(context.getString(R.string.second_mode_terminal)).assertIsDisplayed()
compose.onNodeWithContentDescription(context.getString(R.string.drawer_keyboard)).assertIsDisplayed()
compose.onNodeWithContentDescription(context.getString(R.string.swap_screens)).assertIsDisplayed()
compose.onNodeWithTag("bottom-bar-steam").assertIsDisplayed()
}
@Test fun swappedTopScreenDeckPanelHasTabs() {
SessionState.mode = SessionService.MODE_DESKTOP
SessionState.deckPad = true
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
ReflectionHelpers.getField<MutableState<SecondScreenMode>>(activity, "secondScreenMode\$delegate").value = SecondScreenMode.DECK_CONTROLS
val method = SessionActivity::class.java.getDeclaredMethod("SwappedTopPanel", androidx.compose.runtime.Composer::class.java, Int::class.javaPrimitiveType)
method.isAccessible = true
compose.setContent { DroidDeckTheme { method.invoke(activity, currentComposer, 0) } }
compose.onNodeWithText(context.getString(R.string.second_mode_deck_controls)).assertIsDisplayed()
compose.onNodeWithTag("bottom-bar-tabs").assertIsDisplayed()
compose.onNodeWithTag("bottom-bar-steam").assertDoesNotExist()
compose.onNodeWithTag("bottom-bar-close").assertIsDisplayed()
}
@Test fun unfoldedControlsGetTheSessionBar() {
SessionState.mode = SessionService.MODE_STEAM
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
assertTrue(ReflectionHelpers.callInstanceMethod<View>(activity, "unfoldedBar") is ComposeView)
}
}