Unify configurable control surfaces and profile management

This commit is contained in:
Delete228 committed 2026-11-06 19:11:58 +03:00
1 parent aa3757eff1
commit 63004567fd
73 files changed
+5237 -5015

No files matched your search

@@ -0,0 +1,281 @@
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 InputLibraryTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
private val prefs get() = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun migrationPreservesExistingBindingsGeometryAndActiveSelection() {
prefs.edit().putString("selected", "desktop").putBoolean("migrated", true)
.putString("profile.desktop", """{"version":1,"bindings":[{"role":"PHYSICAL","control":"a","action":{"type":"keys","codes":[29,33]}}]}""").commit()
InputSurfaceLayout.saveLegacy(context, "desktop", listOf(InputSurfaceElement(InputControl.B, .3f, .2f, .4f, .4f)))
val legacy = InputProfiles.readLegacy(context, "desktop")
assertEquals(InputAction.Keys(listOf(29, 33)), legacy.action(InputRole.PHYSICAL, InputControl.A))
val library = InputLibraries.read(context)
assertEquals(legacy.bindings, library.compile("desktop").bindings)
assertEquals(legacy.keys, library.compile("desktop").keys)
assertEquals("desktop", library.selected)
assertEquals(.3f, library.layout("desktop", InputRole.SECONDARY)!!.elements.single().x)
assertEquals(library, InputLibraries.decode(InputLibraries.encode(library)))
}
@Test fun profilesSharePhysicalBindingsWhileUsingDifferentTouchActions() {
val original = InputLibraries.read(context)
val shared = original.duplicateProfile("desktop", "Editor", "editor", sharePhysical = true)
val p = shared.preset(shared.profile("desktop").binding(InputRole.PHYSICAL))
val updated = shared.withPreset(p.copy(controls = p.controls + (InputControl.R3 to InputAction.Keys(listOf(29, 33)))))
.copyBindings(shared.profile("editor").binding(InputRole.SECONDARY), "Editor touch", "editor", InputRole.SECONDARY, "editor.touch")
val touch = updated.preset("editor.touch")
val final = updated.withPreset(touch.copy(controls = touch.controls + (InputControl.A to InputAction.Keys(listOf(28))))).validate()
assertEquals(InputAction.Keys(listOf(29, 33)), final.compile("editor").action(InputRole.PHYSICAL, InputControl.R3))
assertEquals(InputAction.Keys(listOf(29, 33)), final.compile("desktop").action(InputRole.PHYSICAL, InputControl.R3))
assertEquals(InputAction.MouseButton(272), final.compile("desktop").action(InputRole.SECONDARY, InputControl.A))
assertEquals(InputAction.Keys(listOf(28)), final.compile("editor").action(InputRole.SECONDARY, InputControl.A))
assertEquals(final.layout("desktop", InputRole.SECONDARY)!!.elements, final.layout("editor", InputRole.SECONDARY)!!.elements)
assertNotEquals(final.layout("desktop", InputRole.SECONDARY)!!.id, final.layout("editor", InputRole.SECONDARY)!!.id)
}
@Test fun copyingPhysicalBindingsOnlyRelinksTheSelectedProfile() {
val library = InputLibraries.read(context).duplicateProfile("desktop", "Editor", "editor")
val id = library.profile("desktop").binding(InputRole.PHYSICAL)
val copied = library.copyBindings(id, "Editor controller", "editor", InputRole.PHYSICAL, "private")
assertEquals(id, copied.profile("desktop").binding(InputRole.PHYSICAL))
assertEquals("private", copied.profile("editor").binding(InputRole.PHYSICAL))
assertEquals(library.preset(id).controls, copied.preset("private").controls)
assertEquals(library.profile("editor").parts, library.copyBindings(id, "Library copy").profile("editor").parts)
}
@Test fun copyingProfileIsIndependentAndPreservesElementActions() {
val original = InputLibraries.read(context)
val library = original.duplicateProfile("desktop", "Editor", "editor").validate()
for (role in InputRole.entries) {
assertNotEquals(library.profile("desktop").binding(role), library.profile("editor").binding(role))
assertEquals(library.compile("desktop").bindings[role], library.compile("editor").bindings[role])
if (library.layout("desktop", role)?.editable == true) {
assertNotEquals(library.layout("desktop", role)!!.id, library.layout("editor", role)!!.id)
assertEquals(library.layout("desktop", role)!!.elements, library.layout("editor", role)!!.elements)
}
}
assertEquals(original.profiles, library.profiles.filterNot { it.id == "editor" })
assertEquals(original.selected, library.selected)
}
@Test fun sharingGeometryKeepsActionsIndependentAndDetachingCopiesBoth() {
var library = InputLibraries.read(context).duplicateProfile("desktop", "Editor", "editor")
val source = library.layout("desktop", InputRole.SECONDARY)!!
library = library.useLayout("editor", InputRole.SECONDARY, source.id, shared = true).validate()
assertEquals(source.id, library.layout("editor", InputRole.SECONDARY)!!.id)
assertNotEquals(library.profile("desktop").binding(InputRole.SECONDARY), library.profile("editor").binding(InputRole.SECONDARY))
library = library.usePart("editor", InputRole.SECONDARY, "desktop", shared = true).validate()
assertEquals(library.profile("desktop").parts[InputRole.SECONDARY], library.profile("editor").parts[InputRole.SECONDARY])
val detached = library.usePart("editor", InputRole.SECONDARY, "editor", shared = false).validate()
assertNotEquals(source.id, detached.layout("editor", InputRole.SECONDARY)!!.id)
assertNotEquals(detached.profile("desktop").binding(InputRole.SECONDARY), detached.profile("editor").binding(InputRole.SECONDARY))
assertEquals(library.compile("editor"), detached.compile("editor"))
}
@Test fun elementIdsSurviveGeometryEditsAndDeletionPrunesEveryLinkedPreset() {
val library = InputLibraries.read(context)
val layout = library.layout("game", InputRole.SECONDARY)!!
val e = InputSurfaceElement(InputControl.A, .1f, .1f, .2f, .2f, "button-1")
val b = library.preset(library.profile("game").binding(InputRole.SECONDARY))
val saved = library.withLayout(layout.copy(elements = listOf(e)))
.withPreset(b.copy(elements = mapOf(e.id to InputAction.Keys(listOf(57)))))
.copyBindings(b.id, "Alternative", newId = "alternative").validate()
val moved = saved.withLayout(layout.copy(elements = listOf(e.copy(x = .6f)))).validate()
assertEquals(InputAction.Keys(listOf(57)), moved.preset(b.id).action(e))
val deleted = moved.withLayout(layout.copy(elements = emptyList())).validate()
assertTrue(deleted.preset(b.id).elements.isEmpty())
assertTrue(deleted.preset("alternative").elements.isEmpty())
}
@Test fun missingAndIncompatibleReferencesAreRejected() {
val library = InputLibraries.read(context)
assertThrows(IllegalArgumentException::class.java) { library.removeBindings(library.profile("game").binding(InputRole.PHYSICAL)) }
assertThrows(IllegalArgumentException::class.java) { library.removeLayout(library.layout("game", InputRole.SECONDARY)!!.id) }
assertThrows(IllegalArgumentException::class.java) { library.chooseBindings("game", InputRole.PHYSICAL, library.profile("game").binding(InputRole.SECONDARY)) }
assertThrows(IllegalArgumentException::class.java) { library.chooseLayout("game", InputRole.PHYSICAL, InputLibraries.DECK) }
}
@Test fun deletingActiveProfileFallsBackWithoutDeletingSharedParts() {
val library = InputLibraries.read(context).duplicateProfile("desktop", "Editor", "editor")
val removed = library.copy(selected = "editor", desktop = "editor").removeProfile("editor").validate()
assertEquals(InputProfiles.AUTO, removed.selected)
assertEquals("desktop", removed.desktop)
assertEquals(library.layouts, removed.layouts)
assertEquals(library.bindings, removed.bindings)
}
@Test fun futureLibrariesAreNotOverwritten() {
val future = org.json.JSONObject(InputLibraries.encode(InputLibraries.read(context))).put("version", 999).toString()
prefs.edit().putString("library", future).commit()
InputLibraries.read(context)
assertThrows(IllegalArgumentException::class.java) { InputLibraries.update(context) { it.copy(selected = "desktop") } }
assertEquals(future, prefs.getString("library", null))
}
@Test fun resettingAProfileDoesNotResetSharedBindingsOrAccumulatePrivateCopies() {
var library = InputLibraries.read(context).duplicateProfile("desktop", "Editor", "editor", sharePhysical = true)
val common = library.preset(library.profile("desktop").binding(InputRole.PHYSICAL))
library = library.withPreset(common.copy(controls = common.controls + (InputControl.A to InputAction.Keys(listOf(57)))))
.resetProfile("editor").validate()
val count = library.bindings.size
repeat(100) { library = library.resetProfile("editor").validate() }
assertEquals(count, library.bindings.size)
assertEquals(InputAction.Keys(listOf(57)), library.compile("desktop").action(InputRole.PHYSICAL, InputControl.A))
assertEquals(InputAction.MouseButton(272), library.compile("editor").action(InputRole.PHYSICAL, InputControl.A))
}
@Test fun clickActionsRoundTripAndArePrunedWithTheirElement() {
val library = InputLibraries.read(context)
val layout = library.layout("desktop", InputRole.SECONDARY)!!
val pad = layout.elements.first { it.hasClick }
val preset = library.preset(library.profile("desktop").binding(InputRole.SECONDARY))
val updated = library.withPreset(preset.copy(clicks = mapOf(pad.id to InputAction.Keys(listOf(29, 33))))).validate()
val roundTrip = InputLibraries.decode(InputLibraries.encode(updated))!!
assertEquals(InputAction.Keys(listOf(29, 33)), roundTrip.compile("desktop").elementClickAction(InputRole.SECONDARY, pad))
assertEquals(preset.action(pad), roundTrip.preset(preset.id).action(pad))
assertTrue(roundTrip.withLayout(layout.copy(elements = emptyList())).preset(preset.id).clicks.isEmpty())
}
@Test fun versionTwoFixedGamepadMigratesOnceWithoutChangingOtherProfiles() {
val original = InputLibraries.read(context)
val fixed = original.copy(layouts = original.layouts.map { if (it.id == InputLibraries.OVERLAY) it.copy(elements = emptyList(), template = InputLayoutTemplate.OVERLAY) else it },
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)))
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 / 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 quickPartsAreModeSpecificAndDoNotEditSavedProfiles() {
val original = InputLibraries.read(context)
val mixed = original.selectPart(true, InputRole.SECONDARY, InputStockLayouts.TRACKPAD).validate()
assertEquals(original.profiles, mixed.profiles)
assertEquals(original.compileActive(false), mixed.compileActive(false))
assertEquals(InputLibraries.TRACKPAD, mixed.activeLayout(true, InputRole.SECONDARY)?.id)
assertEquals(InputAction.Pointer(), mixed.compileActive(true).elementAction(InputRole.SECONDARY, "legacy:right-pad", InputControl.RIGHT_PAD))
assertEquals(mixed, InputLibraries.decode(InputLibraries.encode(mixed)))
val restored = mixed.selectProfile(true, InputProfiles.AUTO)
assertTrue(restored.selection(true).parts.isEmpty())
assertEquals(original.compileActive(true), restored.compileActive(true))
}
@Test fun savedQuickCombinationOwnsIndependentCopiesOfAllThreeParts() {
val original = InputLibraries.read(context)
val mixed = original.selectPart(true, InputRole.SECONDARY, InputStockLayouts.TRACKPAD)
val saved = mixed.saveSelection(true, "Writing", "writing").validate()
assertEquals("writing", saved.activeId(true))
assertTrue(saved.selection(true).parts.isEmpty())
for (role in InputRole.entries) {
val source = mixed.activePart(true, role)
val copy = saved.activePart(true, role)
assertNotEquals(source.bindings, copy.bindings)
if (role != InputRole.PHYSICAL) assertNotEquals(source.layout, copy.layout)
assertEquals(mixed.preset(source.bindings).elements, saved.preset(copy.bindings).elements)
}
assertEquals(original.profile("desktop"), saved.profile("desktop"))
}
@Test fun activeQuickPartsCannotBeDeletedAndInvalidCombinationsAreRejected() {
val library = InputLibraries.read(context).selectPart(false, InputRole.SECONDARY, InputStockLayouts.RIGHT)
assertThrows(IllegalArgumentException::class.java) { library.removeBindings(InputStockLayouts.RIGHT) }
assertThrows(IllegalArgumentException::class.java) { library.removeLayout("builtin.right-pad") }
assertThrows(IllegalArgumentException::class.java) { library.selectPart(false, InputRole.PHYSICAL, InputStockLayouts.RIGHT).validate() }
assertThrows(IllegalArgumentException::class.java) { library.selectProfile(false, "missing").validate() }
}
@Test fun oldFixedLowerPanelsMigrateIntoEditableLayoutsWithWorkingCommands() {
val current = InputLibraries.read(context)
val profile = current.profile("game")
val old = current.copy(layouts = current.layouts.map { if (it.id == InputLibraries.DECK) it.copy(elements = emptyList(), template = InputLayoutTemplate.DECK) else it },
bindings = current.bindings.filterNot { it.layoutId == InputLibraries.DECK })
.withPreset(SavedInputBindings("old-deck", "Old Deck", false, controls = mapOf(InputControl.L4 to InputAction.Keys(listOf(57)))))
.withProfile(profile.copy(parts = profile.parts + (InputRole.SECONDARY to InputPart("old-deck", InputLibraries.DECK)))).validate()
val raw = org.json.JSONObject(InputLibraries.encode(old)).put("version", 3).toString()
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().putString("library", raw).commit()
val upgraded = InputLibraries.read(context)
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(upgraded, InputLibraries.read(context))
}
@Test fun stockPresetsAreScopedToTheSecondScreenAndCopiedWithTheirActions() {
val library = InputLibraries.read(context)
for (layout in InputStockLayouts.layouts()) {
val role = InputRole.SECONDARY
assertFalse(library.layouts.first { it.id == layout.id }.supports(InputRole.PRIMARY))
val changed = library.useLayout("game", role, layout.id, shared = false).validate()
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))
}
}
@Test fun versionFourScopingPreservesLayoutsAlreadySharedAcrossScreens() {
val original = InputLibraries.read(context)
val deck = original.layouts.first { it.id == InputLibraries.DECK }.copy(screen = InputLayoutScreen.BOTH)
val shared = original.withLayout(deck).useLayout("game", InputRole.PRIMARY, deck.id, shared = true)
.useLayout("game", InputRole.SECONDARY, deck.id, shared = true)
val json = org.json.JSONObject(InputLibraries.encode(shared)).put("version", 4)
val layouts = json.getJSONArray("layouts")
for (i in 0 until layouts.length()) layouts.getJSONObject(i).remove("screen")
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().putString("library", json.toString()).commit()
val migrated = InputLibraries.read(context)
assertEquals(InputLayoutScreen.BOTH, migrated.layouts.first { it.id == deck.id }.screen)
assertEquals(shared.profiles, migrated.profiles)
assertEquals(shared.bindings, migrated.bindings)
assertEquals(migrated, InputLibraries.read(context))
}
@Test fun horizontalScrollAndLayoutTargetSurviveSerialization() {
val library = InputLibraries.read(context)
val preset = library.preset(library.profile("desktop").binding(InputRole.PHYSICAL))
val changed = library.withPreset(preset.copy(controls = preset.controls + (InputControl.RS to InputAction.Scroll(17f, true))))
assertEquals(changed, InputLibraries.decode(InputLibraries.encode(changed)))
}
}
@@ -51,13 +51,15 @@ class InputProfilesTest {
@Test fun unknownVersionDoesNotExecuteBindings() {
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit()
.putString("profile.game", """{"version":999,"bindings":[]} """).commit()
assertEquals(InputProfile.defaults(InputProfile.GAME), InputProfiles.read(context, InputProfile.GAME))
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)
}
@Test fun layoutsPersistIndependentOfBindingsAndStayInsideScreen() {
InputSurfaceLayout.save(context, InputProfile.GAME, listOf(InputSurfaceElement(InputControl.A, .95f, -.1f, 2f, 2f)))
val element = InputSurfaceLayout.read(context, InputProfile.GAME).single()
assertEquals(.9f, element.x); assertEquals(0f, element.y)
assertEquals(.95f, element.x); assertEquals(0f, element.y)
assertTrue(element.x + element.width <= 1f)
assertEquals(InputAction.Native(), InputProfiles.read(context, InputProfile.GAME).action(InputRole.SECONDARY, InputControl.A))
}
@@ -10,6 +10,7 @@ class InputRouterTest {
override fun button(code: Int, down: Boolean) { events += "button $code $down" }
override fun pointer(dx: Float, dy: Float) { events += "pointer $dx $dy" }
override fun scroll(steps: Int) { events += "scroll $steps" }
override fun scrollHorizontal(steps: Int) { events += "horizontal $steps" }
override fun command(command: InputCommand) { events += command.name }
override fun requestMotion() { events += "motion" }
}
@@ -18,6 +19,47 @@ class InputRouterTest {
private fun bind(control: InputControl, action: InputAction, role: InputRole = InputRole.PHYSICAL) =
InputProfile.defaults(InputProfile.GAME).withBinding(role, control, action)
@Test fun radialKeysKeepCustomDiagonalsAndReleaseSharedNeighborKeys() {
router.setProfile(bind(InputControl.LS, InputAction.Directions(103, 106, 0, 105, listOf(30, 0, 0, 0))))
val stick = router.channel(InputRole.PHYSICAL, InputControl.LS)
stick.update(.7f, -.7f)
assertEquals(listOf("key 30 true"), output.events)
stick.update(-.7f, -.7f)
assertEquals(listOf("key 30 true", "key 30 false", "key 105 true", "key 103 true"), output.events)
output.events.clear()
stick.update(0f, -1f)
assertEquals(listOf("key 105 false"), output.events)
router.releaseAll()
assertEquals(listOf("key 105 false", "key 103 false"), output.events)
}
@Test fun horizontalStickUsesXAndKeepsTheVerticalWheelIndependent() {
router.setProfile(bind(InputControl.RS, InputAction.Scroll(20f, true)).withBinding(InputRole.PHYSICAL, InputControl.LS, InputAction.Scroll(20f)))
val horizontal = router.channel(InputRole.PHYSICAL, InputControl.RS)
val vertical = router.channel(InputRole.PHYSICAL, InputControl.LS)
horizontal.update(1f, 0f); vertical.update(0f, -1f)
router.tick(.05f)
assertTrue(output.events.contains("horizontal 1"))
assertTrue(output.events.contains("scroll -1"))
output.events.clear()
horizontal.update(0f, 1f); vertical.update(1f, 0f)
assertFalse(router.tick(.05f))
assertTrue(output.events.isEmpty())
}
@Test fun horizontalTouchScrollFollowsContactAndDropsRemainderOnSuspend() {
val channel = router.channel(InputRole.SECONDARY, InputControl.RIGHT_PAD, InputAction.Scroll(10f, true))
channel.update(0f, 0f, true)
channel.update(.25f, .8f, true)
assertEquals(listOf("horizontal -2"), output.events)
router.releaseAll()
output.events.clear()
channel.update(0f, 0f, false)
channel.update(0f, 0f, true)
channel.update(.06f, 0f, true)
assertTrue(output.events.isEmpty())
}
@Test fun nativeProfileReturnsOriginalStateWithoutScheduling() {
val source = router.pad(InputRole.PHYSICAL)
val state = PadState().apply { leftX = .7f; press(PadState.A, true) }
@@ -0,0 +1,33 @@
package com.droiddeck.launcher.input
import org.junit.Assert.*
import org.junit.Test
class InputSurfaceSnapTest {
private val element = InputSurfaceElement(InputControl.A, .395f, .3f, .2f, .2f)
@Test fun snapsToCanvasCenterWithoutChangingSize() {
val result = snapSurfaceElement(element, emptyList(), .01f, .01f)
assertEquals(.4f, result.element.x, .0001f)
assertEquals(.5f, result.x!!, 0f)
assertEquals(element.width, result.element.width, 0f)
}
@Test fun alignsEdgesWithOtherElementsAndLeavesDistantPositionsFree() {
val other = element.copy(x = .1f, y = .65f)
val aligned = snapSurfaceElement(element.copy(x = .105f), listOf(other), .01f, .01f)
assertEquals(.1f, aligned.element.x, .0001f)
val free = snapSurfaceElement(element.copy(x = .36f, y = .34f), listOf(other), .01f, .01f)
assertNull(free.x); assertNull(free.y)
}
@Test fun resizingSnapsTheDraggedEdgeAndKeepsTheOppositeEdge() {
val result = snapSurfaceElement(element.copy(x = .2f, width = .295f), emptyList(), .01f, .01f, 2 or 8)
assertEquals(.2f, result.element.x, 0f)
assertEquals(.3f, result.element.width, .0001f)
}
@Test fun boundsPreventFalseGuidesAndNegativeSize() {
val e = element.copy(x = .01f, width = .98f)
val result = snapSurfaceElement(e, listOf(element.copy(x = .995f)), .02f, .01f, 1 or 4)
assertTrue(result.element.x >= 0f)
assertTrue(result.element.x + result.element.width <= 1f)
assertTrue(result.element.width >= .03f)
}
}
@@ -0,0 +1,161 @@
package 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.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class])
class InputSurfaceSourceTest {
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) { events += "button:$code:$down" }
override fun pointer(dx: Float, dy: Float) { events += "pointer" }
override fun scroll(steps: Int) { events += "scroll" }
override fun command(command: InputCommand) { events += command.name }
override fun requestMotion() {}
})
private val bridge = PadBridge(File(RuntimeEnvironment.getApplication().cacheDir, "element-input"))
private val sources = mutableListOf<InputSurfaceSource>()
@Before fun setup() { bridge.setInputRouter(router); DeckControls.setRouter(router) }
@After fun close() { sources.forEach { it.close() }; bridge.stop(); DeckControls.setRouter(null); DeckControls.releaseAll() }
private fun button(id: String) = InputSurfaceElement(InputControl.A, .1f, .1f, .2f, .2f, id)
private fun source(e: InputSurfaceElement) = InputSurfaceSource(bridge, InputRole.SECONDARY, e).also { sources += it }
private fun bind(vararg actions: Pair<String, InputAction>) {
bridge.setInputProfile(InputProfile("test", elements = mapOf(InputRole.SECONDARY to mapOf(*actions))))
}
private fun state() = JoyConPadTest.RecordingWriter.pads[0] ?: PadState()
@Test fun toggleUsesSharedOwnershipAndReleasesOnMenuAndProfileChange() {
bind("first" to InputAction.Keys(listOf(29)), "second" to InputAction.Keys(listOf(29)))
val a = source(button("first").copy(toggle = true)); val b = source(button("second"))
a.update(1f); a.update(0f)
assertTrue(a.latched)
assertEquals(listOf("key:29:true"), events)
b.update(1f)
a.update(1f); a.update(0f)
assertFalse(a.latched)
assertEquals(1, events.size)
b.update(0f)
assertEquals("key:29:false", events.last())
a.update(1f); a.update(0f)
bridge.setInputEnabled(false)
assertFalse(a.latched)
assertEquals("key:29:false", events.last())
bridge.setInputEnabled(true)
a.update(1f); a.update(0f)
assertEquals("key:29:true", events.last())
bind("first" to InputAction.Keys(listOf(57)))
assertFalse(a.latched)
assertEquals("key:29:false", events.last())
a.update(1f); a.update(0f)
assertEquals("key:57:true", events.last())
a.release()
assertEquals("key:57:false", events.last())
}
@Test fun nativeToggleReleasesWithoutRepressingAcrossProfileChange() {
bind("first" to InputAction.Native(InputControl.B))
val a = source(button("first").copy(toggle = true))
a.update(1f); a.update(0f)
assertTrue(state().isDown(PadState.B))
bind("first" to InputAction.Native(InputControl.X))
assertFalse(state().isDown(PadState.B))
a.update(1f); a.update(0f)
assertTrue(state().isDown(PadState.X))
a.close()
assertFalse(state().isDown(PadState.X))
}
@Test fun twoButtonsWithTheSameShapeHaveIndependentActions() {
bind("first" to InputAction.Keys(listOf(29)), "second" to InputAction.Keys(listOf(57)))
val a = source(button("first")); val b = source(button("second"))
a.update(1f); b.update(1f); a.update(0f); b.update(0f)
assertEquals(listOf("key:29:true", "key:57:true", "key:29:false", "key:57:false"), events)
}
@Test fun sharedLocalButtonRemainsHeldUntilBothElementsRelease() {
bind("first" to InputAction.MouseButton(272), "second" to InputAction.MouseButton(272))
val a = source(button("first")); val b = source(button("second"))
a.update(1f); b.update(1f); a.close()
assertEquals(listOf("button:272:true"), events)
b.update(0f)
assertEquals(listOf("button:272:true", "button:272:false"), events)
a.update(1f)
assertEquals(2, events.size)
}
@Test fun nativeTouchOutputIsNotRemappedTwiceAndKeepsOtherOwners() {
bridge.setInputProfile(InputProfile("test", bindings = mapOf(InputRole.SECONDARY to mapOf(InputControl.B to InputAction.Disabled)),
elements = mapOf(InputRole.SECONDARY to mapOf("first" to InputAction.Native(InputControl.B), "second" to InputAction.Native(InputControl.B)))))
val a = source(button("first")); val b = source(button("second"))
a.update(1f); b.update(1f)
assertTrue(state().isDown(PadState.B))
a.close()
assertTrue(state().isDown(PadState.B))
b.update(0f)
assertFalse(state().isDown(PadState.B))
}
@Test fun profileChangeReleasesOldOutputAndRequiresNeutralBeforeNewAction() {
bind("first" to InputAction.Keys(listOf(29)))
val a = source(button("first")); a.update(1f)
bind("first" to InputAction.Keys(listOf(57)))
a.update(1f)
assertEquals(listOf("key:29:true", "key:29:false"), events)
a.update(0f); a.update(1f)
assertEquals("key:57:true", events.last())
}
@Test fun unmappedNewButtonsDoNotInheritLegacyBindings() {
bridge.setInputProfile(InputProfile.defaults(InputProfile.DESKTOP))
source(button("new")).update(1f)
assertTrue(events.isEmpty())
}
@Test fun stickClicksAreSuspendedWithTheRestOfInput() {
val e = InputSurfaceElement(InputControl.LS, .1f, .1f, .3f, .3f, "stick", InputElementKind.STICK)
bind(e.id to InputAction.Native(InputControl.RS))
val stick = source(e)
stick.click(true)
assertTrue(state().isDown(PadState.R3))
bridge.setInputEnabled(false)
assertFalse(state().isDown(PadState.R3))
bridge.setInputEnabled(true); stick.click(true)
assertFalse(state().isDown(PadState.R3))
stick.click(false); stick.click(true)
assertTrue(state().isDown(PadState.R3))
stick.close(); stick.click(true)
assertFalse(state().isDown(PadState.R3))
}
@Test fun customTrackpadMovementAndClickHaveIndependentActions() {
val e = InputSurfaceElement(InputControl.LEFT_PAD, .1f, .1f, .4f, .4f, "mouse", InputElementKind.TRACKPAD)
bridge.setInputProfile(InputProfile("test", elements = mapOf(InputRole.SECONDARY to mapOf(e.id to InputAction.Pointer())),
clicks = mapOf(InputRole.SECONDARY to mapOf(e.id to InputAction.MouseButton(272)))))
val surface = source(e)
surface.update(0f, 0f, true); surface.update(.2f, .2f, true); surface.click(true)
assertEquals(listOf("pointer", "button:272:true"), events)
bridge.setInputEnabled(false)
assertEquals("button:272:false", events.last())
bridge.setInputEnabled(true); surface.click(true)
assertEquals(3, events.size)
surface.click(false); surface.click(true); surface.close()
assertEquals(listOf("pointer", "button:272:true", "button:272:false", "button:272:true", "button:272:false"), events)
}
@Test fun migratedTrackpadClickStillUsesTheExistingLogicalBinding() {
bridge.setInputProfile(InputProfile.defaults(InputProfile.DESKTOP))
val e = InputSurfaceElement(InputControl.RIGHT_PAD, .1f, .1f, .4f, .4f)
val surface = source(e)
surface.click(true); surface.click(false)
assertEquals(listOf("button:272:true", "button:272:false"), events)
}
}
@@ -0,0 +1,68 @@
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 LegacyScreenKeyMigrationTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
private val prefs get() = context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun upgradeImportsEverySavedSetWithoutChangingExistingProfilesAndIsIdempotent() {
val original = InputLibraries.read(context).selectProfile(false, "desktop")
prefs.edit().putString("library", JSONObject(InputLibraries.encode(original)).put("version", 5).toString()).commit()
ControllerPrefs.prefs(context).edit().putString("screenKeys", "29+33:0.3,0.7,44::Find::0.6:1:1:1")
.putBoolean("screenKeysShown", false).putString("screenLayout.Editor", "28:0.8,0.6,50::::1.0:2:0:1").commit()
val migrated = InputLibraries.read(context)
assertEquals(original.profiles, migrated.profiles.take(original.profiles.size))
assertEquals(original.selections, migrated.selections)
assertEquals(2, migrated.profiles.count { it.id.startsWith("migrated.screenkeys.") })
val imported = migrated.profiles.first { it.name == "Screen keys (imported)" }
val layout = migrated.layout(imported.id, InputRole.PRIMARY)!!
assertEquals(InputLayoutScreen.MAIN, layout.screen)
assertTrue(layout.elements.single().toggle)
assertEquals(InputAction.Keys(listOf(29, 33)), migrated.compile(imported.id).elements[InputRole.PRIMARY]!!.values.single())
assertFalse(ControllerPrefs.prefs(context).contains("screenKeys"))
assertTrue(prefs.contains(LegacyScreenKeyMigration.BACKUP))
assertEquals(migrated, InputLibraries.read(context))
assertEquals(migrated, InputLibraries.decode(InputLibraries.encode(migrated)))
}
@Test fun conversionRetainsCoordinatesImagesOpacitySymbolsAndIndependentDiagonalKeys() {
val values = LegacyScreenKeyMigration.convert(context,
"28:0.25,0.6,50::::0.8:2:0:1;29:0.7,0.8,40::Ctrl:custom.png:0.4:3:1:1;103+30+106+0+108+0+105+0:0.5,0.5,80::::1:6:0:1", 1000, 500, 2f)
val enter = values[0].first
assertEquals(.25f, enter.x + enter.width / 2, .0001f)
assertEquals(.6f, enter.y + enter.height / 2, .0001f)
assertEquals(.1f, enter.width, .0001f)
assertEquals(.2f, enter.height, .0001f)
assertEquals(28, enter.icon)
assertEquals(InputButtonShape.CIRCLE, enter.buttonShape)
assertEquals("custom.png", values[1].first.image)
assertEquals(.4f, values[1].first.opacity)
assertTrue(values[1].first.toggle)
assertEquals(InputAction.Directions(103, 106, 108, 105, listOf(30, 0, 0, 0)), values[2].second)
assertFalse(values[2].first.floating)
}
@Test fun invalidMigrationDoesNotEraseTheOriginalSavedLibraryOrKeys() {
val original = JSONObject(InputLibraries.encode(InputLibraries.read(context))).put("version", 5).toString()
prefs.edit().putString("library", original).commit()
ControllerPrefs.prefs(context).edit().putString("screenKeys", "28:NaN,0.5,44").commit()
InputLibraries.read(context)
assertEquals(original, prefs.getString("library", null))
assertEquals("28:NaN,0.5,44", ControllerPrefs.prefs(context).getString("screenKeys", null))
assertFalse(prefs.contains(LegacyScreenKeyMigration.BACKUP))
}
}
@@ -1,16 +1,11 @@
package com.droiddeck.launcher.input
import kotlin.math.abs
import kotlin.math.sqrt
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.view.DisplayCutout
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import android.widget.FrameLayout
import java.io.File
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -18,453 +13,119 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE, qualifiers = "mdpi")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class])
class OnScreenControlsTest {
private lateinit var context: Context
private val context: Context get() = RuntimeEnvironment.getApplication()
private val bridge = PadBridge(File(context.cacheDir, "surface-overlay"))
private lateinit var view: OnScreenControls
private val left = InputSurfaceElement(InputControl.LS, .1f, .3f, .2f, .4f)
private val button = InputSurfaceElement(InputControl.A, .7f, .3f, .2f, .3f)
private var time = 1000L
@Before fun setUp() {
context = RuntimeEnvironment.getApplication()
context.getSharedPreferences("controller", Context.MODE_PRIVATE).edit().clear().commit()
ControllerPrefs.setLayout(context, 1200, 800, mapOf("ls" to (0.45f to 0.5f), "rs" to (0.55f to 0.5f)))
view = OnScreenControls(context, null)
view.layout(0, 0, 1200, 800)
@Before fun setup() {
view = OnScreenControls(context, bridge)
view.updateLayout(SavedInputLayout("test", "Test", listOf(left, button)))
measure(view)
}
@After fun close() { view.releaseAll(); bridge.stop() }
private fun state() = JoyConPadTest.RecordingWriter.pads[0] ?: PadState()
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)
}
@Test fun editorSnapsToOtherGroupCentreLines() {
editor()
val button = control("lb")
val target = control("rb")
val x = value(button, "cx")
val y = value(button, "cy")
touch(MotionEvent.ACTION_DOWN, 1 to (x to y))
touch(MotionEvent.ACTION_MOVE, 1 to (x to y + 5f))
assertEquals(value(target, "cy"), value(button, "cy"), 0f)
assertEquals(value(target, "cy"), nullableFloat(view, "snapY")!!, 0f)
touch(MotionEvent.ACTION_UP, 1 to (x to y + 5f))
assertNull(nullableFloat(view, "snapY"))
@Test fun independentFingersHoldStickAndButtonAndCancelReleasesBoth() {
touch(MotionEvent.ACTION_DOWN, 3 to (200f to 300f))
touch(MotionEvent.ACTION_MOVE, 3 to (245f to 300f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 3 to (245f to 300f), 8 to (800f to 250f))
assertTrue(state().leftX > .5f)
assertTrue(state().isDown(PadState.A))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 3 to (245f to 300f), 8 to (800f to 250f))
assertFalse(state().isDown(PadState.A))
assertTrue(state().leftX > .5f)
touch(MotionEvent.ACTION_CANCEL, 3 to (245f to 300f))
assertEquals(0f, state().leftX, 0f)
}
@Test fun editorSnapsToClusterCentresNotTheirOuterButtons() {
editor()
val button = control("lb")
val x = value(button, "cx")
val row = value(control("y"), "cy") + 3f
touch(MotionEvent.ACTION_DOWN, 1 to (x to value(button, "cy")))
touch(MotionEvent.ACTION_MOVE, 1 to (x to row))
assertEquals(row, value(button, "cy"), 0f)
assertNull(nullableFloat(view, "snapY"))
touch(MotionEvent.ACTION_MOVE, 1 to (x to value(control("x"), "cy") + 3f))
assertEquals(value(control("x"), "cy"), value(button, "cy"), 0f)
touch(MotionEvent.ACTION_UP, 1 to (x to row))
}
@Test fun editorDoesNotSnapBeyondDistanceAndCanDragFreeFromGuide() {
editor()
val button = control("lb")
val x = value(button, "cx")
val y = value(button, "cy")
val otherYs = (field(view, "controls") as List<*>)
.filter { field(it!!, "group") != "lb" }
.map { value(it!!, "cy") }
val freeY = (100..700 step 31).map(Int::toFloat).first {
otherYs.minOf { targetY -> abs(it - targetY) } > 12f
}
touch(MotionEvent.ACTION_DOWN, 1 to (x to y))
touch(MotionEvent.ACTION_MOVE, 1 to (x to freeY))
assertEquals(freeY, value(button, "cy"), 0f)
assertNull(nullableFloat(view, "snapY"))
val target = value(control("rb"), "cy")
touch(MotionEvent.ACTION_MOVE, 1 to (x to target + 5f))
assertEquals(target, value(button, "cy"), 0f)
touch(MotionEvent.ACTION_MOVE, 1 to (x to freeY))
assertEquals(freeY, value(button, "cy"), 0f)
assertNull(nullableFloat(view, "snapY"))
touch(MotionEvent.ACTION_UP, 1 to (x to freeY))
}
@Test fun editorSnapsToScreenCentreAndCanDisableSnapping() {
editor()
val button = control("lb")
val y = value(button, "cy")
touch(MotionEvent.ACTION_DOWN, 1 to (value(button, "cx") to y))
touch(MotionEvent.ACTION_MOVE, 1 to (605f to y))
assertEquals(600f, value(button, "cx"), 0f)
assertEquals(600f, nullableFloat(view, "snapX")!!, 0f)
touch(MotionEvent.ACTION_UP, 1 to (605f to y))
ControllerPrefs.setSnap(context, false)
editor()
val unsnapped = control("lb")
val x = value(unsnapped, "cx")
val startY = value(unsnapped, "cy")
touch(MotionEvent.ACTION_DOWN, 1 to (x to startY))
touch(MotionEvent.ACTION_MOVE, 1 to (605f to startY))
assertEquals(605f, value(unsnapped, "cx"), 0f)
assertNull(nullableFloat(view, "snapX"))
touch(MotionEvent.ACTION_UP, 1 to (605f to startY))
}
@Test fun editorSnapPreferenceDefaultsOnAndCanBeChanged() {
assertTrue(ControllerPrefs.read(context).snap)
ControllerPrefs.setSnap(context, false)
assertFalse(ControllerPrefs.read(context).snap)
ControllerPrefs.resetAll(context)
assertTrue(ControllerPrefs.read(context).snap)
}
@Test fun adaptiveStickHidesUntilTouchedAndReturnsToNeutralOnRelease() {
val left = control("ls")
assertEquals(0, pixel(value(left, "cx"), value(left, "cy")))
assertTrue(touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f)))
assertEquals(7, field(left, "pressedBy"))
assertEquals(540f, value(left, "ax"), 0f)
assertEquals(400f, value(left, "ay"), 0f)
assertNotEquals(0, pixel(540f, 400f))
touch(MotionEvent.ACTION_MOVE, 7 to (580f to 420f))
assertTrue(value(left, "kx") > 0f)
assertTrue(value(left, "ky") > 0f)
touch(MotionEvent.ACTION_UP, 7 to (580f to 420f))
assertEquals(-1, field(left, "pressedBy"))
assertEquals(0f, value(left, "kx"), 0f)
assertEquals(0f, value(left, "ky"), 0f)
assertEquals(0, pixel(540f, 400f))
}
@Test fun simultaneousSticksKeepTheirPointersAndReleaseIndependently() {
val left = control("ls")
val right = control("rs")
touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (540f to 400f), 9 to (660f to 400f))
assertEquals(7, field(left, "pressedBy"))
assertEquals(9, field(right, "pressedBy"))
touch(MotionEvent.ACTION_POINTER_DOWN or (2 shl 8), 7 to (540f to 400f), 9 to (660f to 400f), 11 to (500f to 400f))
assertEquals(7, field(left, "pressedBy"))
touch(MotionEvent.ACTION_POINTER_UP or (2 shl 8), 7 to (540f to 400f), 9 to (660f to 400f), 11 to (500f to 400f))
touch(MotionEvent.ACTION_MOVE, 7 to (700f to 400f), 9 to (500f to 400f))
assertTrue(value(left, "kx") > 0f)
assertTrue(value(right, "kx") < 0f)
touch(MotionEvent.ACTION_POINTER_UP, 7 to (700f to 400f), 9 to (500f to 400f))
assertEquals(-1, field(left, "pressedBy"))
assertEquals(9, field(right, "pressedBy"))
touch(MotionEvent.ACTION_CANCEL, 9 to (500f to 400f))
for (stick in listOf(left, right)) {
assertEquals(-1, field(stick, "pressedBy"))
assertEquals(0f, value(stick, "kx"), 0f)
}
}
@Test fun cancelledTouchDoesNotBecomeAStickClick() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_CANCEL, 1 to (540f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(false, field(control("ls"), "clicked"))
touch(MotionEvent.ACTION_UP, 1 to (540f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(true, field(control("ls"), "clicked"))
}
@Test fun buttonsTakePriorityOverAdaptiveRegions() {
val button = control("a")
touch(MotionEvent.ACTION_DOWN, 3 to (value(button, "cx") to value(button, "cy")))
assertEquals(3, field(button, "pressedBy"))
assertEquals(-1, field(control("rs"), "pressedBy"))
}
@Test fun takesTouchAtMatchesWhatATouchDoes() {
var checked = 0
for (x in 0 until 1200 step 40) for (y in 0 until 800 step 40) {
val expected = view.takesTouchAt(x.toFloat(), y.toFloat())
assertEquals("($x, $y)", expected, touch(MotionEvent.ACTION_DOWN, 0 to (x.toFloat() to y.toFloat())))
touch(MotionEvent.ACTION_UP, 0 to (x.toFloat() to y.toFloat()))
if (expected) checked++
}
assertTrue("some points land on controls", checked > 0)
}
@Test fun fixedSticksAndEditorRemainVisibleAtSavedPositions() {
ControllerPrefs.setAdaptiveSticks(context, false)
@Test fun reloadCancelsHeldViewsSoTheNextPressWorks() {
touch(MotionEvent.ACTION_DOWN, 0 to (800f to 250f))
assertTrue(state().isDown(PadState.A))
view.reload()
val left = control("ls")
val x = value(left, "cx")
val y = value(left, "cy")
assertNotEquals(0, pixel(x, y))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (0f to y)))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
touch(MotionEvent.ACTION_DOWN, 1 to (x + 10f to y))
assertEquals(x, value(left, "ax"), 0f)
assertEquals(10f, value(left, "kx"), 0f)
ControllerPrefs.setAdaptiveSticks(context, true)
view = OnScreenControls(context, null, editing = true)
view.layout(0, 0, 1200, 800)
assertNotEquals(0, pixel(value(control("ls"), "cx"), value(control("ls"), "cy")))
assertFalse(state().isDown(PadState.A))
touch(MotionEvent.ACTION_DOWN, 0 to (800f to 250f))
assertTrue(state().isDown(PadState.A))
}
@Test fun buttonsOnlyAndReloadReleaseAdaptiveSticks() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_MOVE, 1 to (570f to 400f))
view.reload()
assertEquals(-1, field(control("ls"), "pressedBy"))
assertEquals(0f, value(control("ls"), "kx"), 0f)
view.setButtonsOnly(true)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
@Test fun replacingTheLayoutReleasesOldSourcesAndHitRegions() {
touch(MotionEvent.ACTION_DOWN, 0 to (800f to 250f))
view.updateLayout(SavedInputLayout("empty", "Empty"))
measure(view)
assertFalse(state().isDown(PadState.A))
assertFalse(view.takesTouchAt(800f, 250f))
}
@Test fun adaptiveActivationKeepsItsVerticalAndInwardLimits() {
val left = control("ls")
val x = value(left, "cx")
val y = value(left, "cy")
val reach = activationReach(left)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to y - reach - 1f)))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to y - reach + 1f)))
assertEquals(y - reach + 1f, value(left, "ay"), 0.001f)
touch(MotionEvent.ACTION_UP, 1 to (x to y - reach + 1f))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x + reach to y - reach)))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 200f)))
}
@Test fun leftAdaptiveStickCanStartAtTheLeftEdgeAndReleaseNormally() {
val left = control("ls")
val y = value(left, "cy")
val reach = activationReach(left)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (0f to y - reach - 1f)))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (0f to y)))
assertEquals(1, field(left, "pressedBy"))
assertEquals(0f, value(left, "ax"), 0f)
assertEquals(0f, value(left, "kx"), 0f)
touch(MotionEvent.ACTION_MOVE, 1 to (30f to y))
assertEquals(30f, value(left, "kx"), 0f)
touch(MotionEvent.ACTION_CANCEL, 1 to (30f to y))
assertEquals(-1, field(left, "pressedBy"))
assertEquals(0f, value(left, "kx"), 0f)
assertEquals(-1, field(control("rs"), "pressedBy"))
}
@Test fun rightAdaptiveStickKeepsItsSavedActivationCircle() {
val right = control("rs")
val x = value(right, "cx")
val y = value(right, "cy")
val reach = activationReach(right)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (1199f to y)))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x + reach + 1f to y)))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x + reach - 1f to y)))
assertEquals(1, field(right, "pressedBy"))
}
@Test
@Config(sdk = [30])
@Suppress("DEPRECATION")
fun leftActivationStopsAtTheSafeCutoutEdge() {
val insets = WindowInsets.Builder()
.setDisplayCutout(DisplayCutout(Rect(24, 0, 0, 0), listOf(Rect(0, 380, 24, 420))))
.build()
view.dispatchApplyWindowInsets(insets)
val left = control("ls")
val y = value(left, "cy")
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (23f to y)))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (24f to y)))
assertEquals(1, field(left, "pressedBy"))
}
@Test fun touchesOutsideActivationAreasStayWithTrackpad() {
@Test fun emptySpaceDoesNotConsumeTheUnderlyingTrackpadStream() {
val received = mutableListOf<Int>()
val trackpad = View(context).apply {
setOnTouchListener { _, event -> received.add(event.actionMasked); true }
}
val root = FrameLayout(context).apply {
addView(trackpad, FrameLayout.LayoutParams(1200, 800))
addView(view, FrameLayout.LayoutParams(1200, 800))
measure(View.MeasureSpec.makeMeasureSpec(1200, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY))
layout(0, 0, 1200, 800)
addView(View(context).apply { setOnTouchListener { _, e -> received += e.actionMasked; true } }, FrameLayout.LayoutParams(-1, -1))
addView(view, FrameLayout.LayoutParams(-1, -1))
}
for ((action, position) in listOf(
MotionEvent.ACTION_DOWN to (600f to 200f),
MotionEvent.ACTION_MOVE to (540f to 400f),
MotionEvent.ACTION_UP to (540f to 400f),
)) {
val event = MotionEvent.obtain(1000L, time++, action, position.first, position.second, 0)
measure(root)
for (action in listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP)) {
val event = MotionEvent.obtain(1000, time++, action, 500f, 100f, 0)
try { assertTrue(root.dispatchTouchEvent(event)) } finally { event.recycle() }
}
assertEquals(listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP), received)
assertEquals(-1, field(control("ls"), "pressedBy"))
}
@Test fun trackpadFingerKeepsItsOwnStreamWhileAStickIsHeld() {
val forwarded = mutableListOf<Triple<Int, Int, Float>>()
view.onTouchMiss = { forwarded += Triple(it.actionMasked, it.getPointerId(0), it.getX(0)) }
touch(MotionEvent.ACTION_DOWN, 7 to (540f to 400f))
assertTrue(touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (540f to 400f), 9 to (600f to 200f)))
touch(MotionEvent.ACTION_MOVE, 7 to (500f to 400f), 9 to (650f to 200f))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 7 to (500f to 400f), 9 to (650f to 200f))
assertEquals(listOf(
Triple(MotionEvent.ACTION_DOWN, 9, 600f),
Triple(MotionEvent.ACTION_MOVE, 9, 650f),
Triple(MotionEvent.ACTION_UP, 9, 650f),
), forwarded)
assertEquals(7, field(control("ls"), "pressedBy"))
assertTrue(value(control("ls"), "kx") < 0f)
@Test fun backgroundFingerIsForwardedWhileAStickIsHeld() {
val received = mutableListOf<Pair<Int, Int>>()
view.onTouchMiss = { received += it.actionMasked to it.getPointerId(0) }
touch(MotionEvent.ACTION_DOWN, 3 to (200f to 300f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 3 to (200f to 300f), 8 to (500f to 100f))
touch(MotionEvent.ACTION_MOVE, 3 to (245f to 300f), 8 to (520f to 100f))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 3 to (245f to 300f), 8 to (520f to 100f))
assertEquals(listOf(MotionEvent.ACTION_DOWN to 8, MotionEvent.ACTION_MOVE to 8, MotionEvent.ACTION_UP to 8), received)
assertTrue(state().leftX > .5f)
}
@Test fun stickPressedAfterTrackpadFingerReachesTheControls() {
val received = mutableListOf<Triple<Int, Int, Int>>()
val trackpad = View(context).apply {
setOnTouchListener { _, event -> received += Triple(event.actionMasked, event.pointerCount, event.getPointerId(0)); true }
}
val root = FrameLayout(context).apply {
isMotionEventSplittingEnabled = true
addView(trackpad, FrameLayout.LayoutParams(1200, 800))
addView(view, FrameLayout.LayoutParams(1200, 800))
measure(View.MeasureSpec.makeMeasureSpec(1200, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY))
layout(0, 0, 1200, 800)
}
fun dispatch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>) {
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()
val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
try { assertTrue(root.dispatchTouchEvent(event)) } finally { event.recycle() }
}
dispatch(MotionEvent.ACTION_DOWN, 0 to (600f to 200f))
dispatch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 0 to (600f to 200f), 1 to (540f to 400f))
dispatch(MotionEvent.ACTION_MOVE, 0 to (640f to 220f), 1 to (500f to 400f))
assertEquals(1, field(control("ls"), "pressedBy"))
assertTrue(value(control("ls"), "kx") < 0f)
dispatch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 0 to (640f to 220f), 1 to (500f to 400f))
dispatch(MotionEvent.ACTION_UP, 0 to (640f to 220f))
assertEquals(-1, field(control("ls"), "pressedBy"))
assertEquals(Triple(MotionEvent.ACTION_DOWN, 1, 0), received.first())
assertEquals(Triple(MotionEvent.ACTION_UP, 1, 0), received.last())
assertTrue(received.all { it.second == 1 && it.third == 0 })
@Test fun aBackgroundStreamDoesNotTurnIntoAButtonWhenItCrossesOne() {
val received = mutableListOf<Int>()
view.onTouchMiss = { received += it.actionMasked }
touch(MotionEvent.ACTION_DOWN, 3 to (500f to 100f))
touch(MotionEvent.ACTION_MOVE, 3 to (800f to 250f))
touch(MotionEvent.ACTION_UP, 3 to (800f to 250f))
assertFalse(state().isDown(PadState.A))
assertEquals(listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP), received)
}
@Test fun adaptiveActivationLeavesFivePixelsAroundButtonHitTargets() {
for (id in listOf("a", "rb")) {
val button = control(id)
val radius = value(button, "radius")
val edge = value(button, "cy") - radius * if (id == "rb") 1.05f else 1.25f
val x = value(button, "cx")
val left = control("ls")
moveControl(left, x, edge - 10f)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 4f)))
assertEquals(-1, field(left, "pressedBy"))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 6f)))
assertEquals(1, field(left, "pressedBy"))
touch(MotionEvent.ACTION_UP, 1 to (x to edge - 6f))
@Test fun floatingAndFixedSticksUseTheirConfiguredOrigin() {
for (floating in listOf(true, false)) {
view.updateLayout(SavedInputLayout("test", "Test", listOf(left.copy(floating = floating))))
measure(view)
touch(MotionEvent.ACTION_DOWN, 3 to (230f to 300f))
assertEquals(if (floating) 0f else .5f, state().leftX, .001f)
touch(MotionEvent.ACTION_UP, 3 to (230f to 300f))
}
}
@Test fun leftExtensionKeepsButtonPriorityAndClearance() {
val button = control("left")
val x = value(button, "cx")
val y = value(button, "cy")
val edge = y - value(button, "radius") * 1.25f
val left = control("ls")
moveControl(left, x + 200f, y)
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to y)))
assertEquals(1, field(button, "pressedBy"))
assertEquals(-1, field(left, "pressedBy"))
touch(MotionEvent.ACTION_UP, 1 to (x to y))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 4f)))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (x to edge - 6f)))
assertEquals(1, field(left, "pressedBy"))
}
private fun control(id: String): Any = (field(view, "controls") as List<*>).first { field(it!!, "id") == id }!!
private fun editor() {
view = OnScreenControls(context, null, editing = true)
view.layout(0, 0, 1200, 800)
}
@Test fun keyboardShortcutWorksWithHiddenPadAndButtonsOnly() {
var opened = 0
view = OnScreenControls(context, null, onKeyboard = { opened++ })
view.layout(0, 0, 1200, 800)
view.setQuickHidden(true)
assertNotEquals(0, pixel(90f, 766f))
touch(MotionEvent.ACTION_DOWN, 1 to (90f to 766f))
assertEquals(0, opened)
touch(MotionEvent.ACTION_UP, 1 to (90f to 766f))
assertEquals(1, opened)
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (600f to 400f)))
@Test fun systemOnlyVisibilityUsesTheSameLayoutAndReleasesOtherButtons() {
val guide = InputSurfaceElement(InputControl.GUIDE, .4f, .7f, .1f, .2f)
view.updateLayout(SavedInputLayout("test", "Test", listOf(button, guide)))
measure(view)
touch(MotionEvent.ACTION_DOWN, 0 to (800f to 250f))
view.setButtonsOnly(true)
touch(MotionEvent.ACTION_DOWN, 1 to (600f to 756f))
touch(MotionEvent.ACTION_UP, 1 to (600f to 756f))
assertEquals(2, opened)
assertEquals(-1, field(control("guide"), "pressedBy"))
}
@Test fun cancelledDraggedOrDisabledKeyboardShortcutDoesNotOpen() {
var opened = 0
view = OnScreenControls(context, null, onKeyboard = { opened++ })
view.layout(0, 0, 1200, 800)
touch(MotionEvent.ACTION_DOWN, 1 to (90f to 766f))
touch(MotionEvent.ACTION_CANCEL, 1 to (90f to 766f))
touch(MotionEvent.ACTION_UP, 1 to (90f to 766f))
assertEquals(0, opened)
touch(MotionEvent.ACTION_DOWN, 1 to (90f to 766f))
touch(MotionEvent.ACTION_MOVE, 1 to (180f to 766f))
touch(MotionEvent.ACTION_UP, 1 to (180f to 766f))
assertEquals(0, opened)
ControllerPrefs.setKeyboardButton(context, false)
view.reload()
view.setQuickHidden(true)
assertEquals(0, pixel(90f, 766f))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (90f to 766f)))
}
@Test fun hidingSystemButtonsRemovesHitTargetsInBothOverlayModes() {
for (buttonsOnly in listOf(false, true)) {
ControllerPrefs.setSteamButton(context, true)
ControllerPrefs.setQamButton(context, true)
view.reload()
view.setButtonsOnly(buttonsOnly)
val guide = control("guide")
val qam = control("qam")
val gx = value(guide, "cx"); val gy = value(guide, "cy")
val qx = value(qam, "cx"); val qy = value(qam, "cy")
assertNotEquals(0, pixel(gx, gy))
assertNotEquals(0, pixel(qx, qy))
touch(MotionEvent.ACTION_DOWN, 1 to (gx to gy))
ControllerPrefs.setSteamButton(context, false)
view.reload()
assertEquals(-1, field(guide, "pressedBy"))
assertEquals(0, pixel(gx, gy))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (gx to gy)))
assertTrue(touch(MotionEvent.ACTION_DOWN, 1 to (qx to qy)))
touch(MotionEvent.ACTION_UP, 1 to (qx to qy))
ControllerPrefs.setQamButton(context, false)
view.reload()
assertEquals(0, pixel(qx, qy))
assertFalse(touch(MotionEvent.ACTION_DOWN, 1 to (qx to qy)))
}
}
private fun field(owner: Any, name: String): Any = owner.javaClass.getDeclaredField(name).apply { isAccessible = true }.get(owner)!!
private fun nullableFloat(owner: Any, name: String) = owner.javaClass.getDeclaredField(name).apply { isAccessible = true }.get(owner) as Float?
private fun value(owner: Any, name: String) = field(owner, name) as Float
private fun activationReach(control: Any) = value(control, "radius") * 1.4f * sqrt(1.5f)
private fun moveControl(control: Any, x: Float, y: Float) {
control.javaClass.getDeclaredField("cx").apply { isAccessible = true }.setFloat(control, x)
control.javaClass.getDeclaredField("cy").apply { isAccessible = true }.setFloat(control, y)
}
private fun pixel(x: Float, y: Float): Int {
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
view.draw(Canvas(bitmap))
val color = bitmap.getPixel(x.toInt(), y.toInt())
bitmap.recycle()
return color
measure(view)
assertFalse(state().isDown(PadState.A))
assertFalse(view.takesTouchAt(800f, 250f))
assertTrue(view.takesTouchAt(450f, 480f))
}
private fun touch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>): 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()
val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
return try { view.onTouchEvent(event) } finally { event.recycle() }
return try { view.dispatchTouchEvent(event) } finally { event.recycle() }
}
}
@@ -1,140 +0,0 @@
package com.droiddeck.launcher.input
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ScreenKeysTest {
private val context = RuntimeEnvironment.getApplication()
@Before fun clearKeys() {
ControllerPrefs.setScreenKeys(context, emptyList())
}
@Test fun missesAreForwardedAsTheirOwnTouchStreamWhileAKeyIsHeld() {
val sent = mutableListOf<Pair<Int, Boolean>>()
val keys = ScreenKeys(context) { code, down -> sent += code to down }
keys.layout(0, 0, 1000, 600)
keys.add(listOf(KeyEvent.KEYCODE_W))
val forwarded = mutableListOf<Pair<Int, Int>>()
keys.onTouchMiss = { forwarded += it.actionMasked to it.getPointerId(0) }
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
send(keys, MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), listOf(0, 1), listOf(300f, 900f), listOf(372f, 550f))
send(keys, MotionEvent.ACTION_MOVE, listOf(0, 1), listOf(310f, 880f), listOf(372f, 530f))
send(keys, MotionEvent.ACTION_POINTER_UP or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), listOf(0, 1), listOf(310f, 880f), listOf(372f, 530f))
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(310f), listOf(372f))
assertEquals(
listOf(
MotionEvent.ACTION_DOWN to 1,
MotionEvent.ACTION_MOVE to 1,
MotionEvent.ACTION_UP to 1,
),
forwarded,
)
assertEquals(listOf(KeyEvent.KEYCODE_W to true, KeyEvent.KEYCODE_W to false), sent)
}
@Test fun gestureRecognizerKeepsOneSplitTargetOwnerUntilItsStreamEnds() {
val gate = GestureTouchStreamGate()
fun accepts(source: GestureTouchStreamGate.Source, action: Int): Boolean {
val event = MotionEvent.obtain(0L, 1L, action, 1f, 1f, 0)
return try { gate.accepts(source, event) } finally { event.recycle() }
}
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
assertFalse(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_MOVE))
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_UP))
assertTrue(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
assertFalse(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
assertTrue(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_CANCEL))
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
assertFalse(accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, MotionEvent.ACTION_DOWN))
gate.reset()
assertTrue(accepts(GestureTouchStreamGate.Source.SURFACE, MotionEvent.ACTION_DOWN))
}
@Test fun takesTouchAtMatchesWhatATouchDoes() {
val keys = ScreenKeys(context) { _, _ -> }
keys.layout(0, 0, 1000, 600)
keys.add(listOf(KeyEvent.KEYCODE_W))
var checked = 0
for (x in 0 until 1000 step 25) for (y in 0 until 600 step 25) {
val expected = keys.takesTouchAt(x.toFloat(), y.toFloat())
val down = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, x.toFloat(), y.toFloat(), 0)
assertEquals("($x, $y)", expected, keys.onTouchEvent(down))
down.recycle()
MotionEvent.obtain(0L, 1L, MotionEvent.ACTION_UP, x.toFloat(), y.toFloat(), 0).also { keys.onTouchEvent(it); it.recycle() }
if (expected) checked++
}
assertTrue("some points land on the key", checked > 0)
}
@Test fun loadingLayoutReleasesLatchedKeysBeforeReplacingEntries() {
val sent = mutableListOf<Pair<Int, Boolean>>()
val keys = ScreenKeys(context) { code, down -> sent += code to down }
keys.layout(0, 0, 1000, 600)
keys.add(listOf(KeyEvent.KEYCODE_SHIFT_LEFT))
keys.setToggle(listOf(KeyEvent.KEYCODE_SHIFT_LEFT), true)
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(300f), listOf(372f))
keys.load("")
assertEquals(listOf(KeyEvent.KEYCODE_SHIFT_LEFT to true, KeyEvent.KEYCODE_SHIFT_LEFT to false), sent)
}
@Test fun hidingTheViewReleasesLatchedKeys() {
val sent = mutableListOf<Pair<Int, Boolean>>()
val keys = ScreenKeys(context) { code, down -> sent += code to down }
keys.layout(0, 0, 1000, 600)
keys.add(listOf(KeyEvent.KEYCODE_SHIFT_LEFT))
keys.setToggle(listOf(KeyEvent.KEYCODE_SHIFT_LEFT), true)
send(keys, MotionEvent.ACTION_DOWN, listOf(0), listOf(300f), listOf(372f))
send(keys, MotionEvent.ACTION_UP, listOf(0), listOf(300f), listOf(372f))
keys.visibility = View.GONE
assertEquals(listOf(KeyEvent.KEYCODE_SHIFT_LEFT to true, KeyEvent.KEYCODE_SHIFT_LEFT to false), sent)
}
private fun send(view: View, action: Int, ids: List<Int>, xs: List<Float>, ys: List<Float>) {
val properties = Array(ids.size) { index ->
MotionEvent.PointerProperties().apply {
id = ids[index]
toolType = MotionEvent.TOOL_TYPE_FINGER
}
}
val coordinates = Array(ids.size) { index ->
MotionEvent.PointerCoords().apply {
x = xs[index]
y = ys[index]
pressure = 1f
size = 1f
}
}
val event = MotionEvent.obtain(
0L, 1L, action, ids.size, properties, coordinates, 0, 0,
1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0,
)
try {
view.onTouchEvent(event)
} finally {
event.recycle()
}
}
}
@@ -79,11 +79,7 @@ class SessionInputPointerTest {
}
@Test fun stickContinuesFromTrackpadPositionAndUpdatesVisibleAndGuestCoordinates() {
ReflectionHelpers.callInstanceMethod<Unit>(activity, "moveSecondScreenPointer",
ReflectionHelpers.ClassParameter.from(Float::class.javaPrimitiveType, 250f),
ReflectionHelpers.ClassParameter.from(Float::class.javaPrimitiveType, 150f),
ReflectionHelpers.ClassParameter.from(Float::class.javaPrimitiveType, 1000f),
ReflectionHelpers.ClassParameter.from(Float::class.javaPrimitiveType, 600f))
output.pointer(-400f, -225f)
output.pointer(160f, 90f)
invoke("onPadInput")
assertEquals(Offset(350f, 215.625f), state<Offset>("cursorPos").value)
@@ -175,6 +171,17 @@ class SessionInputPointerTest {
assertTrue(CompositorShadow.events.isEmpty())
}
@Test fun horizontalWheelUsesTheSameDirectionInBothMouseBackends() {
output.scrollHorizontal(2)
assertEquals(listOf(Triple(11, 0, 240)), CompositorShadow.events)
CompositorShadow.events.clear()
ReflectionHelpers.setField(activity, "mouseWriter", FakeInputWriter(activity.cacheDir.path, FakeInputWriter.MOUSE_SLOT))
ReflectionHelpers.setField(activity, "evdevMouseActive", true)
output.scrollHorizontal(2)
assertEquals(listOf("wheel:0:2:120"), WriterShadow.mouse)
assertTrue(CompositorShadow.events.isEmpty())
}
@Test fun leavingRawMouseReleasesItsHoldBeforeReturningToTheWaylandSeat() {
ReflectionHelpers.setField(activity, "mouseWriter", FakeInputWriter(activity.cacheDir.path, FakeInputWriter.MOUSE_SLOT))
ReflectionHelpers.setField(activity, "evdevMouseActive", true)
@@ -400,22 +400,23 @@ class StickDeadZoneTest {
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))
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 controls = ReflectionHelpers.getField<List<Any>>(view, "controls")
val control = controls.first { ReflectionHelpers.getField<String>(it, "id") == id }
val x = ReflectionHelpers.getField<Float>(control, "cx")
val y = ReflectionHelpers.getField<Float>(control, "cy")
val control = elements.first { it.control.id == 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.onTouchEvent(down)) } finally { down.recycle() }
assertFalse(ReflectionHelpers.getField<Boolean>(control, "dirty"))
try { assertTrue(view.dispatchTouchEvent(down)) } finally { down.recycle() }
assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, 0f)
assertTrue((if (id == "ls") pad().rightX else pad().leftX) > 0f)
bridge.setStickDeadZone(25)
assertEquals(0f, if (id == "ls") pad().leftX else pad().rightX, 0f)
motion(device, MotionEvent.AXIS_X to 0.6f, MotionEvent.AXIS_Z to 0.7f)
val button = controls.first { ReflectionHelpers.getField<String>(it, "id") == "a" }
val bx = ReflectionHelpers.getField<Float>(button, "cx")
val by = ReflectionHelpers.getField<Float>(button, "cy")
val button = elements.first { it.control == InputControl.A }
val bx = (button.x + button.width / 2) * 1200
val by = (button.y + button.height / 2) * 800
fun buttonTouch(action: Int, time: Long) {
val event = MotionEvent.obtain(1000, time, action or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), 2,
arrayOf(MotionEvent.PointerProperties().apply { this.id = 0; toolType = MotionEvent.TOOL_TYPE_FINGER },
@@ -423,7 +424,7 @@ class StickDeadZoneTest {
arrayOf(MotionEvent.PointerCoords().apply { this.x = x; this.y = y },
MotionEvent.PointerCoords().apply { this.x = bx; this.y = by }),
0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0)
try { assertTrue(view.onTouchEvent(event)) } finally { event.recycle() }
try { assertTrue(view.dispatchTouchEvent(event)) } finally { event.recycle() }
}
buttonTouch(MotionEvent.ACTION_POINTER_DOWN, 1030)
assertTrue(pad().isDown(PadState.A))
@@ -435,7 +436,7 @@ class StickDeadZoneTest {
assertEquals(0.6f, pad().leftX, 0f)
assertEquals(0.7f, pad().rightX, 0f)
val up = MotionEvent.obtain(1000, 1100, MotionEvent.ACTION_UP, x, y, 0)
try { assertTrue(view.onTouchEvent(up)) } finally { up.recycle() }
try { assertTrue(view.dispatchTouchEvent(up)) } finally { up.recycle() }
}
}
}
@@ -126,6 +126,9 @@ class SettingsResetTest {
}
@Test fun inputProfilesAndSurfacesResetWithoutRestoringLegacyMappings() {
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")
InputProfiles.select(app, InputProfile.DESKTOP)
InputProfiles.save(app, InputProfile.defaults(InputProfile.GAME)
@@ -135,9 +138,9 @@ class SettingsResetTest {
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
assertEquals(InputProfiles.AUTO, InputProfiles.selection(app))
assertEquals(InputProfile.defaults(InputProfile.GAME), InputProfiles.read(app, InputProfile.GAME))
assertEquals(InputProfile.defaults(InputProfile.DESKTOP), InputProfiles.read(app, InputProfile.DESKTOP))
assertEquals(InputSurfaceLayout.defaults(), InputSurfaceLayout.read(app, InputProfile.DESKTOP))
assertEquals(defaultGame, InputProfiles.read(app, InputProfile.GAME))
assertEquals(defaultDesktop, InputProfiles.read(app, InputProfile.DESKTOP))
assertEquals(defaultSurface, InputSurfaceLayout.read(app, InputProfile.DESKTOP))
}
@Test fun gameTextureFilteringIsKeptUnlessGameProfilesAreReset() {
@@ -1,7 +1,8 @@
package com.droiddeck.launcher.ui
import com.droiddeck.launcher.session.SessionDisplay
import com.droiddeck.launcher.ui.GamepadGeometry.Slot
import com.droiddeck.launcher.input.GamepadGeometry
import com.droiddeck.launcher.input.GamepadGeometry.Slot
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -1,8 +1,15 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.app.Presentation
import android.hardware.display.DisplayManager
import android.view.Display
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.*
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionService
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
@@ -10,6 +17,10 @@ import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.shadows.ShadowDialog
import org.robolectric.shadows.ShadowDisplayManager
import org.robolectric.util.ReflectionHelpers
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@@ -25,11 +36,75 @@ class InputSettingsTest {
context.getSharedPreferences("controller", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun steamAndDesktopQuickSettingsOpenTheSameInputLibrary() {
val mode = mutableStateOf(SessionService.MODE_STEAM)
var opened = 0
compose.setContent { DroidDeckTheme {
ModeSheetRows(ModeSettings(mode = mode.value, resolution = "auto", hdr = false, hdrReason = null,
touchMode = "auto", suspendPolicy = "auto", oscMode = "auto", directAudio = null, mic = null),
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.runOnIdle { assertEquals(1, opened); mode.value = SessionService.MODE_DESKTOP }
compose.onNodeWithText(context.getString(R.string.ctrl_edit)).performClick()
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("Left Deck trackpad").performScrollTo().performClick()
compose.runOnIdle {
val changed = InputLibraries.read(context)
assertEquals(InputStockLayouts.LEFT, 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 }) } }
compose.onNodeWithText(context.getString(R.string.input_route_controller), substring = false).performClick()
compose.onNodeWithText(context.getString(R.string.input_disabled), substring = false).performClick()
compose.onNodeWithText(context.getString(R.string.input_route_local), substring = false).performClick()
compose.onNodeWithText(context.getString(R.string.input_scroll_speed, 27)).assertExists()
compose.onNodeWithTag("setting-action-type").performClick()
compose.onNodeWithText(context.getString(R.string.input_mouse_click)).performClick()
compose.onNodeWithTag("setting-action-type").performClick()
compose.onNodeWithText(context.getString(R.string.input_scroll)).performClick()
compose.onNodeWithTag("input-action-save").performClick()
compose.runOnIdle { assertEquals(InputAction.Scroll(27f, true), saved) }
}
@Test fun bindingEditorPersistsDisabledWithoutChangingTouchControls() {
var changed = false
compose.setContent { DroidDeckTheme { InputSettingsPage({}, { changed = true }) } }
compose.onNodeWithTag("input-profile-game").performScrollTo().performClick()
compose.onNodeWithTag("input-part-physical").performScrollTo().performClick()
compose.onNodeWithTag("input-binding-a").performScrollTo().performClick()
compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick()
compose.runOnIdle { assertFalse(changed) }
compose.onNodeWithTag("input-action-save").performClick()
compose.runOnIdle {
assertTrue(changed)
val profile = InputProfiles.read(context, InputProfile.GAME)
@@ -38,15 +113,240 @@ class InputSettingsTest {
}
}
@Test fun customLayoutAddsExistingControlAndKeepsProfileBindings() {
@Test fun addingCreatesAnUnassignedElementAtTheCanvasCenterWithoutAnotherTouch() {
var changed = false
compose.setContent { DroidDeckTheme { InputSurfaceDialog(InputProfile.GAME, {}, { changed = true }) } }
compose.onNodeWithText("Add control").performScrollTo().performClick()
compose.onNodeWithText("R1", substring = false).performScrollTo().performClick()
compose.onNodeWithText("Save changes").performClick()
val library = InputLibraries.read(context)
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()
compose.runOnIdle {
assertTrue(changed)
assertTrue(InputSurfaceLayout.read(context, InputProfile.GAME).any { it.control == InputControl.RB })
val updated = InputLibraries.read(context)
val added = updated.layout(InputProfile.GAME, InputRole.SECONDARY)!!.elements.single { e -> layout.elements.none { it.id == e.id } }
assertEquals(InputAction.Disabled, updated.compile(InputProfile.GAME).elementAction(InputRole.SECONDARY, added.id, added.control))
assertEquals(.5f, added.x + added.width / 2, .01f)
}
}
@Test fun aNewProfileIsIndependentAndDoesNotBecomeActive() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick()
compose.onNodeWithTag("input-name").performTextInput("Minecraft")
compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick()
compose.runOnIdle {
val library = InputLibraries.read(context)
val created = library.profiles.single { it.name == "Minecraft" }
for (role in InputRole.entries) assertNotEquals(library.profile(InputProfile.GAME).binding(role), created.binding(role))
assertNotEquals(library.layout(InputProfile.GAME, InputRole.SECONDARY)!!.id, library.layout(created.id, InputRole.SECONDARY)!!.id)
assertEquals(InputProfiles.AUTO, library.selected)
}
}
@Test fun openingAProfileDoesNotActivateItAndBackKeepsItsContext() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-profile-desktop").performScrollTo().performClick()
compose.onNodeWithTag("input-part-physical").performScrollTo().performClick()
compose.onNodeWithTag("input-binding-a").performScrollTo().performClick()
compose.onNodeWithTag("input-action-save").performClick()
compose.onNodeWithTag("input-binding-a").assertExists()
compose.onNodeWithText(context.getString(R.string.mode_back)).performClick()
compose.onNodeWithTag("input-part-secondary").assertExists()
compose.runOnIdle { assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) }
}
@Test fun profileCreationCanExplicitlyShareOnlyPhysicalControls() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick()
compose.onNodeWithTag("input-name").performTextInput("Shared controls")
compose.onNodeWithTag("input-share-physical").performClick()
compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick()
compose.runOnIdle {
val library = InputLibraries.read(context)
val created = library.profiles.single { it.name == "Shared controls" }
assertEquals(library.profile("game").binding(InputRole.PHYSICAL), created.binding(InputRole.PHYSICAL))
assertNotEquals(library.profile("game").binding(InputRole.SECONDARY), created.binding(InputRole.SECONDARY))
}
}
@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) }
}
@Test fun localToolsCanMoveAndExpandWithoutMovingTheCanvas() {
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)) } }
compose.runOnIdle {
val window = ShadowDialog.getLatestDialog().window!!
assertEquals(android.view.WindowManager.LayoutParams.MATCH_PARENT, window.attributes.width)
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()
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 fun deckPresetOffersItsRealElementsAndTheCommonEditor() {
InputLibraries.update(context) { it.useLayout("game", InputRole.SECONDARY, InputLibraries.DECK, shared = true) }
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-profile-game").performScrollTo().performClick()
compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick()
compose.onNodeWithTag("input-element-legacy:l4").performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("input-binding-a").assertDoesNotExist()
}
@Test fun mouseTrackpadPresetIsEditableLikeAnyOtherLayout() {
InputLibraries.update(context) { it.useLayout("game", InputRole.SECONDARY, InputLibraries.TRACKPAD, shared = true) }
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-profile-game").performScrollTo().performClick()
compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick()
compose.onNodeWithTag("input-element-legacy:right-pad").performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("input-surface-secondary").performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("input-binding-a").assertDoesNotExist()
}
@Test fun primaryScreenOffersItsActualElementsAndTheCommonEditor() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-profile-game").performScrollTo().performClick()
compose.onNodeWithTag("input-part-primary").performScrollTo().performClick()
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()
}
@Test fun deviceSettingsAreInlineBelowProfiles() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-more").assertDoesNotExist()
compose.onNodeWithText(context.getString(R.string.ctrl_dead_zone)).performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("input-profile-game").performScrollTo().assertIsDisplayed()
}
@Test fun migratedPadClicksRemainEditableWithoutChangingMovement() {
compose.setContent { DroidDeckTheme { InputSettingsPage({}) } }
compose.onNodeWithTag("input-profile-desktop").performScrollTo().performClick()
compose.onNodeWithTag("input-part-secondary").performScrollTo().performClick()
compose.onNodeWithTag("input-click-legacy:right-pad").performScrollTo().performClick()
compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick()
compose.onNodeWithTag("input-action-save").performClick()
compose.runOnIdle {
val library = InputLibraries.read(context)
val pad = library.layout("desktop", InputRole.SECONDARY)!!.elements.first { it.control == InputControl.RIGHT_PAD }
val profile = library.compile("desktop")
assertEquals(InputAction.Disabled, profile.elementClickAction(InputRole.SECONDARY, pad))
assertEquals(InputAction.Pointer(), profile.elementAction(InputRole.SECONDARY, pad.id, pad.control))
}
}
@Test @Config(sdk = [34]) fun secondarySettingsCanOpenAnActivityDialogAndCloseCleanly() {
val displayId = ShadowDisplayManager.addDisplay("w640dp-h480dp", ReflectionHelpers.getStaticField<Int>(Display::class.java, "TYPE_EXTERNAL"))
val display = context.getSystemService(DisplayManager::class.java).getDisplay(displayId)
shadowOf(display).setFlags(Display.FLAG_PRESENTATION)
val open = mutableStateOf(true)
try {
compose.setContent { DroidDeckTheme {
val host = androidx.compose.ui.platform.LocalContext.current.findActivity() as androidx.activity.ComponentActivity
if (open.value) InputDisplayContent(host, display, { open.value = false }) { InputSettingsPage({ open.value = false }) }
} }
compose.onNodeWithText(context.getString(R.string.input_new_profile)).performScrollTo().performClick()
compose.onNodeWithTag("input-name").assertExists()
compose.runOnIdle {
assertTrue(ShadowDialog.getShownDialogs().filterIsInstance<Presentation>().any { it.isShowing && it.display.displayId == displayId })
val dialog = ShadowDialog.getShownDialogs().last { it !is Presentation && it.isShowing }
assertEquals(Display.DEFAULT_DISPLAY, dialog.window?.decorView?.display?.displayId)
open.value = false
}
compose.runOnIdle { assertTrue(ShadowDialog.getShownDialogs().none { it.isShowing }) }
} finally { ShadowDisplayManager.removeDisplay(displayId) }
}
@Test @Config(sdk = [34]) fun mainEditorOpenedFromSecondarySettingsUsesAnActivityWindow() {
val displayId = ShadowDisplayManager.addDisplay("w640dp-h480dp", ReflectionHelpers.getStaticField<Int>(Display::class.java, "TYPE_EXTERNAL"))
val display = context.getSystemService(DisplayManager::class.java).getDisplay(displayId)
shadowOf(display).setFlags(Display.FLAG_PRESENTATION)
val open = mutableStateOf(true)
try {
compose.setContent { DroidDeckTheme {
val host = androidx.compose.ui.platform.LocalContext.current.findActivity() as androidx.activity.ComponentActivity
if (open.value) InputDisplayContent(host, display, { open.value = false }) {
InputSurfaceDialog("game", { open.value = false }, {}, role = InputRole.PRIMARY)
}
} }
compose.onNodeWithTag("input-layout-canvas").assertExists()
compose.runOnIdle {
assertTrue(ShadowDialog.getShownDialogs().none { it is Presentation && it.display.displayId == Display.DEFAULT_DISPLAY })
val editor = ShadowDialog.getShownDialogs().last { it !is Presentation && it.isShowing }
assertEquals(Display.DEFAULT_DISPLAY, editor.window?.decorView?.display?.displayId)
open.value = false
}
compose.runOnIdle { assertTrue(ShadowDialog.getShownDialogs().none { it.isShowing }) }
} finally { ShadowDisplayManager.removeDisplay(displayId) }
}
@Test @Config(sdk = [34]) fun auxiliaryEditorUsesThatDisplayAndSurvivesItsRemoval() {
val displayId = ShadowDisplayManager.addDisplay("w640dp-h480dp", ReflectionHelpers.getStaticField<Int>(Display::class.java, "TYPE_EXTERNAL"))
val display = context.getSystemService(DisplayManager::class.java).getDisplay(displayId)
shadowOf(display).setFlags(Display.FLAG_PRESENTATION)
assertTrue(SecondScreenDisplays.available(context.getSystemService(DisplayManager::class.java)).any { it.id == displayId })
val previous = SessionState.secondScreenDisplay
SessionState.secondScreenDisplay = displayId
val open = mutableStateOf(true)
try {
compose.setContent { DroidDeckTheme { if (open.value) InputSurfaceDialog("game", { open.value = false }, {}) } }
compose.onNodeWithText(context.getString(R.string.input_editor_remote)).assertExists()
compose.onAllNodesWithText(context.getString(R.string.input_editor_add)).assertCountEquals(1)
compose.onNodeWithText(context.getString(R.string.input_hide_tools)).assertDoesNotExist()
assertEquals(0f, compose.onNodeWithTag("input-layout-canvas").fetchSemanticsNode().boundsInRoot.top, 1f)
compose.runOnIdle {
assertTrue(ShadowDialog.getShownDialogs().filterIsInstance<Presentation>().any { it.isShowing && it.display.displayId == displayId })
}
compose.onNodeWithTag("input-layout-canvas").performTouchInput { click(percentOffset(.25f, .25f)) }
compose.onAllNodesWithText(context.getString(R.string.input_properties)).onFirst().performClick()
compose.onNodeWithTag("input-action-save").assertIsDisplayed()
compose.onNodeWithText("Disabled", substring = false).performScrollTo().performClick()
compose.runOnIdle {
assertTrue(ShadowDialog.getShownDialogs().any { it !is Presentation && it.isShowing && it.window?.decorView?.display?.displayId == Display.DEFAULT_DISPLAY })
ShadowDisplayManager.removeDisplay(displayId)
}
compose.onNodeWithTag("input-action-save").assertIsDisplayed()
compose.onNodeWithTag("input-action-save").performClick()
compose.onNodeWithText(context.getString(R.string.input_display_unavailable)).assertExists()
compose.onNodeWithText(context.getString(R.string.input_editor_done)).performScrollTo().performClick()
compose.runOnIdle {
assertFalse(open.value)
assertEquals(InputAction.Disabled, InputProfiles.read(context, "game").elementAction(InputRole.SECONDARY, "legacy:left-pad", InputControl.LEFT_PAD))
}
} finally {
SessionState.secondScreenDisplay = previous
if (display.isValid) ShadowDisplayManager.removeDisplay(displayId)
}
}
}
@@ -0,0 +1,120 @@
package com.droiddeck.launcher.ui
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.activity.ComponentActivity
import com.droiddeck.launcher.input.*
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.Shadows.shadowOf
import org.robolectric.annotation.Config
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], shadows = [JoyConPadTest.RecordingWriter::class])
class InputSurfaceGesturesTest {
private val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup()
private val activity = controller.get()
private val events = mutableListOf<String>()
private val moves = mutableListOf<Pair<Float, Float>>()
private val bridge = PadBridge(activity.cacheDir)
private val router = InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) { events += "key:$code:$down" }
override fun button(code: Int, down: Boolean) { events += "button:$code:$down" }
override fun pointer(dx: Float, dy: Float) { moves += dx to dy }
override fun scroll(steps: Int) { events += "scroll:$steps" }
override fun command(command: InputCommand) {}
override fun requestMotion() { error("Touchpad must not schedule stick frames") }
})
private lateinit var panel: InputSurfaceView
private lateinit var pad: View
private var time = 1000L
private val element = InputSurfaceElement(InputControl.RIGHT_PAD, 0f, 0f, 1f, 1f, mouseGestures = true)
private fun profile(action: InputAction = InputAction.Pointer()) = InputProfile("test",
elements = mapOf(InputRole.SECONDARY to mapOf(element.id to action)),
clicks = mapOf(InputRole.SECONDARY to mapOf(element.id to InputAction.MouseButton(272))))
@Before fun setup() {
bridge.setInputRouter(router)
bridge.setInputProfile(profile())
panel = InputSurfaceView(activity, bridge, listOf(element))
activity.setContentView(panel)
panel.measure(View.MeasureSpec.makeMeasureSpec(1000, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY))
panel.layout(0, 0, 1000, 600)
pad = descendants(panel).first { it.javaClass.simpleName == "TrackpadView" }
}
@After fun close() { panel.releaseInputs(); bridge.stop(); controller.pause().stop().destroy() }
@Test fun tapClicksWithoutRepositioningCursorFromAnotherSource() {
touch(MotionEvent.ACTION_DOWN); touch(MotionEvent.ACTION_UP)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100))
assertEquals(listOf("button:272:true", "button:272:false"), events)
assertTrue(moves.isEmpty())
val other = router.channel(InputRole.PHYSICAL, InputControl.LS, fixedAction = InputAction.Pointer())
other.update(0f, 0f, true); other.pointerDelta(.1f, .2f); other.update(0f)
val positionChanges = moves.toList()
time += 1000
touch(MotionEvent.ACTION_DOWN); touch(MotionEvent.ACTION_UP)
assertEquals(positionChanges, moves)
other.close()
}
@Test fun tapUsesTheConfiguredElementClick() {
bridge.setInputProfile(profile().copy(clicks = mapOf(InputRole.SECONDARY to mapOf(element.id to InputAction.Keys(listOf(57))))))
touch(MotionEvent.ACTION_DOWN); touch(MotionEvent.ACTION_UP)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100))
assertEquals(listOf("key:57:true", "key:57:false"), events)
}
@Test fun motionDeliversImmediatelyAndTwoFingerScrollDoesNotMoveThePointer() {
touch(MotionEvent.ACTION_DOWN)
touch(MotionEvent.ACTION_MOVE, y = 230f)
assertTrue(moves.isNotEmpty())
touch(MotionEvent.ACTION_UP)
time += 1000
touch(MotionEvent.ACTION_DOWN)
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), fingers = 2)
val before = moves.size
touch(MotionEvent.ACTION_MOVE, y = 270f, fingers = 2)
assertEquals(before, moves.size)
assertTrue(events.any { it.startsWith("scroll:") })
}
@Test fun profileChangeAndMenuSuspensionSuppressPendingGesturePresses() {
touch(MotionEvent.ACTION_DOWN)
bridge.setInputEnabled(false)
bridge.setInputEnabled(true)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1000))
assertTrue(events.isEmpty())
touch(MotionEvent.ACTION_CANCEL)
time += 1000
touch(MotionEvent.ACTION_DOWN)
bridge.setInputProfile(profile(InputAction.Disabled))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(1000))
assertTrue(events.isEmpty())
panel.releaseInputs()
bridge.setInputProfile(profile())
time += 1000
touch(MotionEvent.ACTION_DOWN); touch(MotionEvent.ACTION_UP)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100))
assertEquals(listOf("button:272:true", "button:272:false"), events)
}
private fun touch(action: Int, y: Float = 200f, fingers: Int = 1) {
val properties = Array(fingers) { i -> MotionEvent.PointerProperties().apply { id = i; toolType = MotionEvent.TOOL_TYPE_FINGER } }
val coords = Array(fingers) { i -> MotionEvent.PointerCoords().apply { x = 200f + 100 * i; this.y = y; pressure = 1f; size = 1f } }
val event = MotionEvent.obtain(time - 20, time, action, fingers, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
try { assertTrue(pad.onTouchEvent(event)) } finally { event.recycle(); time += 10 }
}
private fun descendants(view: View): Sequence<View> = sequence {
yield(view)
if (view is ViewGroup) for (i in 0 until view.childCount) yieldAll(descendants(view.getChildAt(i)))
}
}
@@ -7,7 +7,7 @@ import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.DeckControls
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.input.JoyConPadTest
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadState
@@ -25,23 +25,32 @@ import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], shadows = [JoyConPadTest.RecordingWriter::class])
class DeckControlsPanelOwnershipTest {
class InputSurfaceOwnershipTest {
private val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup()
private val activity = controller.get()
private val root = FrameLayout(activity)
private val bridge = PadBridge(File(activity.cacheDir, "panel-ownership"))
private lateinit var panel: DeckControlsPanel
private lateinit var panel: InputSurfaceView
private val previousDeckPad = SessionState.deckPad
@Before fun setUp() {
SessionState.deckPad = true
DeckControls.releaseAll()
SessionPrefs.setGamepadSurface(activity, false, SessionPrefs.SURFACE_STICK)
SessionPrefs.setGamepadSurface(activity, true, SessionPrefs.SURFACE_TRACKPAD)
bridge.setInputRouter(InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) {}
override fun button(code: Int, down: Boolean) {}
override fun pointer(dx: Float, dy: Float) {}
override fun scroll(steps: Int) {}
override fun command(command: InputCommand) {}
override fun requestMotion() {}
}))
val elements = listOf(InputControl.RIGHT_PAD, InputControl.LS, InputControl.A).mapIndexed { i, c ->
InputSurfaceElement(c, .02f + i * .3f, .1f, .28f, .4f)
} + InputSurfaceElement(InputControl.LS, .02f, .6f, .28f, .3f, "dpad", InputElementKind.DPAD)
bridge.setInputProfile(InputProfile("native", elements = mapOf(InputRole.SECONDARY to mapOf("dpad" to InputAction.Native()))))
activity.setContentView(root)
panel = DeckControlsPanel(activity, {}, {}, {}, bridge)
panel = InputSurfaceView(activity, bridge, elements)
root.addView(panel)
descendants(panel).filterIsInstance<TextView>().first { it.text == activity.getString(R.string.deck_tab_gamepad) }.performClick()
val trackpad = child("TrackpadView")
trackpad.layout(0, 0, 300, 300)
touch(trackpad, MotionEvent.ACTION_DOWN, 200f, 100f)
@@ -57,14 +66,14 @@ class DeckControlsPanelOwnershipTest {
SessionState.deckPad = previousDeckPad
}
@Test fun switchingTheOtherStickKeepsTrackpadContactAndClickHeld() {
@Test fun removingTheStickKeepsTrackpadContactAndClickHeld() {
val stick = child("StickView")
stick.layout(0, 0, 300, 300)
touch(stick, MotionEvent.ACTION_DOWN, 150f, 150f)
touch(stick, MotionEvent.ACTION_MOVE, 240f, 150f)
assertTrue(state().leftX > 0f)
val position = JoyConPadTest.RecordingWriter.deckPads.copyOf()
descendants(stick.parent as View).first { it.contentDescription == activity.getString(R.string.deck_surface_switch) }.performClick()
(stick.parent as ViewGroup).removeView(stick)
assertEquals(0f, state().leftX)
assertTrackpadStillHeld(position)
root.removeView(panel)
@@ -82,8 +91,8 @@ class DeckControlsPanelOwnershipTest {
assertTrackpadStillHeld(position)
}
@Test fun removingFaceButtonsReleasesOnlyTheirOwnInput() {
val buttons = child("FaceButtons")
@Test fun removingAButtonReleasesOnlyItsOwnInput() {
val buttons = child("HoldButton")
buttons.layout(0, 0, 300, 300)
touch(buttons, MotionEvent.ACTION_DOWN, 150f, 240f)
assertTrue(state().isDown(PadState.A))
@@ -93,49 +102,31 @@ class DeckControlsPanelOwnershipTest {
assertTrackpadStillHeld(position)
}
@Test fun switchingTabsRemovesTheOldTouchSourceAfterChildrenRelease() {
val routed = recordTouchRoute()
@Test fun replacingTheLayoutReleasesEveryOldControl() {
holdFaceButton()
assertTrue(routed.last().isDown(PadState.A))
descendants(panel).filterIsInstance<TextView>().first { it.text == activity.getString(R.string.deck_tab_grips) }.performClick()
assertFalse(routed.last().isDown(PadState.A))
assertTrue(state().isDown(PadState.A))
panel.updateCustomLayout(emptyList())
assertFalse(state().isDown(PadState.A))
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
routed.clear()
bridge.applyExternal({ it.press(PadState.B, true) }, true)
assertTrue("removed tab still forwards a neutral touch source", routed.isEmpty())
assertTrue(state().isDown(PadState.B))
descendants(panel).filterIsInstance<TextView>().first { it.text == activity.getString(R.string.deck_tab_gamepad) }.performClick()
holdFaceButton()
assertTrue(routed.last().isDown(PadState.A))
assertFalse(state().isDown(PadState.A))
}
@Test fun removingThePanelLeavesNoTouchSourceForLaterPhysicalInput() {
val routed = recordTouchRoute()
holdFaceButton()
root.removeView(panel)
assertFalse(routed.last().isDown(PadState.A))
routed.clear()
assertFalse(state().isDown(PadState.A))
bridge.applyExternal({ it.press(PadState.B, true) }, true)
assertTrue("removed panel still forwards a neutral touch source", routed.isEmpty())
assertTrue(state().isDown(PadState.B))
}
private fun holdFaceButton() {
val buttons = child("FaceButtons")
val buttons = child("HoldButton")
buttons.layout(0, 0, 300, 300)
touch(buttons, MotionEvent.ACTION_DOWN, 150f, 240f)
}
private fun recordTouchRoute(): MutableList<PadState> {
val routed = mutableListOf<PadState>()
bridge.setTouchRoute(object : PadBridge.TouchRoute {
override fun active() = true
override fun accept(state: PadState) { routed += PadState().apply { copyFrom(state) } }
})
return routed
}
private fun assertTrackpadStillHeld(position: ShortArray) {
assertEquals(32 or 128, JoyConPadTest.RecordingWriter.grips)
assertArrayEquals(position, JoyConPadTest.RecordingWriter.deckPads)
@@ -4,6 +4,8 @@ import android.content.ComponentName
import android.view.MotionEvent
import androidx.activity.ComponentActivity
import android.view.View
import android.widget.FrameLayout
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.input.JoyConPadTest
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.session.SessionState
@@ -20,8 +22,42 @@ import java.nio.file.Files
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"],
shadows = [JoyConPadTest.RecordingWriter::class])
class DeckControlsPanelTest {
shadows = [JoyConPadTest.RecordingWriter::class, SessionInputPointerTest.CompositorShadow::class])
class InputSurfaceViewTest {
@Test fun customControlsReleaseOnDetachAndWorkWhenTheSameViewReturns() {
val controller = Robolectric.buildActivity(ComponentActivity::class.java).setup()
val activity = controller.get()
val events = mutableListOf<Boolean>()
val bridge = PadBridge(activity.cacheDir)
val router = InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) { events += 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) {}
override fun requestMotion() {}
})
bridge.setInputRouter(router)
bridge.setInputProfile(InputProfile("test", elements = mapOf(InputRole.SECONDARY to mapOf("one" to InputAction.Keys(listOf(57))))))
val root = FrameLayout(activity)
activity.setContentView(root)
val panel = InputSurfaceView(activity, bridge,
listOf(InputSurfaceElement(InputControl.A, .2f, .2f, .2f, .2f, "one")))
try {
repeat(2) {
root.addView(panel)
panel.measure(View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY))
panel.layout(0, 0, 600, 600)
val down = MotionEvent.obtain(0, 1, MotionEvent.ACTION_DOWN, 150f, 150f, 0)
try { assertTrue(panel.dispatchTouchEvent(down)) } finally { down.recycle() }
assertEquals(true, events.last())
root.removeView(panel)
assertEquals(false, events.last())
}
assertEquals(listOf(true, false, true, false), events)
} finally { root.removeAllViews(); bridge.stop(); controller.pause().stop().destroy() }
}
@Test fun takesTouchAtMatchesWhatATouchDoes() {
val directory = Files.createTempDirectory("deck-panel").toFile()
try {
@@ -29,12 +65,10 @@ class DeckControlsPanelTest {
val app = RuntimeEnvironment.getApplication()
shadowOf(app.packageManager).addActivityIfNotPresent(ComponentName(app, ComponentActivity::class.java))
val activity = Robolectric.buildActivity(ComponentActivity::class.java).setup().get()
for (pad in listOf(null, PadBridge(directory))) for (portraitDock in listOf(false, true)) {
for (pad in listOf(null, PadBridge(directory))) for (portraitDock in listOf(false, true)) for (layout in InputStockLayouts.layouts()) {
val name = "pad=${pad != null} portraitDock=$portraitDock"
val panel = DeckControlsPanel(activity, onClose = {}, onSteamMenu = {}, onQam = {},
pad = pad, portraitDock = portraitDock)
val panel = InputSurfaceView(activity, pad, layout.elements)
activity.setContentView(panel)
assertEquals(name, pad == null, panel.deckControls)
val (w, h) = if (portraitDock) 720 to 1000 else 1200 to 480
panel.measure(View.MeasureSpec.makeMeasureSpec(w, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(h, View.MeasureSpec.EXACTLY))
@@ -0,0 +1,131 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.material3.Surface
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.semantics.SemanticsActions
import androidx.compose.ui.test.*
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.InputLibraries
import com.droiddeck.launcher.input.InputProfiles
import org.junit.Assert.assertEquals
import com.droiddeck.launcher.input.InputAction
import com.droiddeck.launcher.input.InputControl
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class InputUiLayoutTest {
@get:Rule val compose = createRobolectricComposeRule()
private lateinit var root: View
@Before fun reset() {
val context = RuntimeEnvironment.getApplication()
for (name in listOf("input-profiles", "input-surfaces", "controller")) context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun layoutThumbnailDoesNotPaintOverItsRowOrAdjacentControls() {
val context = RuntimeEnvironment.getApplication()
val library = InputLibraries.read(context)
val preview = InputLayoutPreviewView(context)
preview.update(library.layout("game", com.droiddeck.launcher.input.InputRole.SECONDARY)!!, com.droiddeck.launcher.input.InputRole.SECONDARY)
preview.measure(View.MeasureSpec.makeMeasureSpec(112, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(76, View.MeasureSpec.EXACTLY))
preview.layout(0, 0, 112, 76)
val bitmap = Bitmap.createBitmap(240, 160, Bitmap.Config.ARGB_8888)
bitmap.eraseColor(android.graphics.Color.MAGENTA)
preview.draw(Canvas(bitmap))
assertEquals(android.graphics.Color.MAGENTA, bitmap.getPixel(150, 30))
assertEquals(android.graphics.Color.MAGENTA, bitmap.getPixel(30, 120))
bitmap.recycle()
}
@Test @Config(qualifiers = "w360dp-h800dp")
fun phoneKeepsLibraryNavigationAndProfileEditingReachable() {
compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { BoxWithConstraints {
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < 600.dp)) { InputSettingsPage({}) }
} } } }
compose.onNodeWithTag("input-profile-desktop").performScrollTo().assertIsDisplayed().performClick()
compose.onNodeWithTag("input-part-physical").performScrollTo().assertIsDisplayed().performClick()
compose.onNodeWithTag("input-binding-a").performScrollTo().assertIsDisplayed().performClick()
compose.onNodeWithTag("input-action-save").assertIsDisplayed()
screenshot("phone-properties")
}
@Test @Config(qualifiers = "w640dp-h360dp")
fun handheldPropertiesLeaveSaveVisibleAboveScrollableContent() {
compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { InputActionEditor(InputControl.LS, InputAction.Pointer(), "Left stick", {}, {}) } } }
compose.onNodeWithTag("input-action-save").assertIsDisplayed()
compose.onNode(SemanticsMatcher.keyIsDefined(SemanticsActions.SetProgress)).performScrollTo().assertIsDisplayed()
screenshot("handheld-properties")
}
@Test @Config(qualifiers = "w960dp-h600dp")
fun largeScreenShowsTheProfileLibraryInTheExistingTheme() {
compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { InputSettingsPage({}) } } }
compose.onNodeWithTag("input-profile-game").assertIsDisplayed()
screenshot("profiles")
}
@Test @Config(qualifiers = "w960dp-h600dp")
fun controllerTabKeepsSetupNavigationWithoutDuplicateEditors() {
val context = RuntimeEnvironment.getApplication()
compose.setContent {
root = LocalView.current
DroidDeckTheme {
CompositionLocalProvider(LocalFrontFocus provides FrontFocus(), LocalNarrowPane provides false) {
FocusGlideHost {
SetupPanel(FrontEndState(
installed = null, ready = false, available = null, busy = false, stage = "", percent = -1,
desktopInstalled = false, offlineAccount = null, offline = false, frameGenLabel = "",
romsDir = null, logsEnabled = false, steamGames = emptyList(), emulators = emptyList(), running = null,
controller = ControllerPrefs.read(context),
), FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {},
onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {},
onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {},
onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {},
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> }, controller = ControllerActions({}),
), onOpenDeveloperOptions = {}, onRequestWirelessAdb = {}, onPairWirelessDebugging = {})
}
}
}
}
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()
compose.onNodeWithText(context.getString(R.string.setup_tab_launcher)).assertIsDisplayed()
screenshot("controller-physical")
compose.runOnIdle { assertEquals(InputProfiles.AUTO, InputLibraries.read(context).selected) }
}
private fun screenshot(name: String) {
compose.runOnIdle {
val image = Bitmap.createBitmap(root.width, root.height, Bitmap.Config.ARGB_8888)
root.draw(Canvas(image))
val file = File("build/reports/input-ui/$name.png").apply { parentFile?.mkdirs() }
file.outputStream().use { image.compress(Bitmap.CompressFormat.PNG, 100, it) }
image.recycle()
}
}
}
@@ -70,6 +70,7 @@ class PhysicalShortcutsDialogTest {
compose.setContent {
DroidDeckTheme { InputSettingsPage(onBack = {}) }
}
compose.onNodeWithTag("shortcuts-assign-STEAM").performScrollTo()
compose.onNodeWithTag("shortcuts-assign-STEAM").assertExists()
compose.onNodeWithTag("shortcuts-assign-QAM").assertExists()
compose.onNodeWithTag("shortcuts-assign-DROIDDECK").assertExists()
@@ -134,12 +135,12 @@ class PhysicalShortcutsDialogTest {
compose.setContent { DroidDeckTheme { PhysicalShortcutRows() } }
assign(PhysicalShortcuts.Action.STEAM)
send(KeyEvent.KEYCODE_F3, KeyEvent.ACTION_DOWN)
compose.onNodeWithTag("shortcuts-remove").performScrollTo().performClick()
compose.onNodeWithTag("shortcuts-restore-default").performScrollTo().performClick()
compose.runOnIdle {
assertEquals(PhysicalShortcuts.Action.QAM, PhysicalShortcuts.read(context).single().action)
assertTrue(ControllerPrefs.read(context).selectSteam)
}
compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.game_settings_default))
compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.input_shortcut_guide))
}
@Test fun retryRecoversFromAMissingReleaseWithoutSavingTheOldButton() {
@@ -172,7 +173,7 @@ class PhysicalShortcutsDialogTest {
val label = compose.onNodeWithText(context.getString(R.string.drawer_steam_menu)).getUnclippedBoundsInRoot()
assertTrue(control.right - control.left < 200.dp)
assertTrue("Menu label must not wrap vertically: $label", label.bottom - label.top <= 48.dp)
compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(context.getString(R.string.ctrl_custom))
compose.onNodeWithTag("shortcuts-assign-STEAM").assertTextContains(button.label)
compose.onNodeWithText("${button.label} · ${button.name}").assertExists()
}
@@ -63,6 +63,22 @@ class SessionSecondScreenTest {
@Test fun steamMenuKeepsTheExistingTrackpadAndTerminal() = checkModes(steam = true)
@Test fun closingTheDockedDrawerKeepsTheSelectedControlsPanel() {
SessionState.mode = SessionService.MODE_STEAM
var closes = 0
var selected = SecondScreenMode.CUSTOM_CONTROLS
compose.setContent {
DroidDeckTheme {
SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {},
actions(true, listOf(SecondScreenDisplay(1, "Bottom screen")),
onClose = { closes++ }, select = { selected = it }), docked = true)
}
}
compose.onNodeWithContentDescription(context.getString(R.string.common_close)).performClick()
assertEquals(1, closes)
assertEquals(SecondScreenMode.CUSTOM_CONTROLS, selected)
}
@Test fun desktopWithoutASecondDisplayFallsBackToController() {
SessionState.mode = SessionService.MODE_DESKTOP
var page = SessionDrawerPage.SECOND_SCREEN
@@ -102,36 +118,11 @@ class SessionSecondScreenTest {
}
}
@Test fun trackpadTapUsesPositionLeftByAnotherPointerSource() {
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val positions = mutableListOf<Pair<Float, Float>>()
var position = Offset(0.2f, 0.7f)
val panel = SecondScreenPresentation(activity, display,
{ x, y, w, h -> positions += x / w to y / h }, { _, _ -> }, {}, {}, {}, {},
pointerPosition = { position })
try {
panel.create()
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
val trackpad = descendants(panel.window!!.decorView).first { it is SessionTrackpadView }
trackpad.layout(0, 0, 1000, 600)
for (next in listOf(Offset(0.2f, 0.7f), Offset(0.8f, 0.1f))) {
position = next
for ((action, time) in listOf(MotionEvent.ACTION_DOWN to 1000L, MotionEvent.ACTION_UP to 1010L)) {
val event = MotionEvent.obtain(1000, time, action, 300f, 300f, 0)
try { trackpad.onTouchEvent(event) } finally { event.recycle() }
}
assertEquals(next.x, positions.last().first, 0.001f)
assertEquals(next.y, positions.last().second, 0.001f)
}
} finally { panel.closeControls() }
}
@Test fun terminalOpenedBeforeItWasReadyIsRetriedButOtherPanelsAreLeftAlone() {
SessionState.mode = SessionService.MODE_STEAM
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 panel = SecondScreenPresentation(activity, display, {}, {}, {})
try {
panel.show()
panel.showMode(SecondScreenMode.KEYBOARD_TRACKPAD)
@@ -244,7 +235,7 @@ class SessionSecondScreenTest {
SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, actions(steam, displays) { selected += it })
}
}
val modes = listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.TERMINAL)
val modes = listOf(SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.TERMINAL)
for (mode in modes) {
compose.onNodeWithText(context.getString(mode.label)).performScrollTo().assertIsDisplayed().performClick()
}
@@ -259,6 +250,7 @@ class SessionSecondScreenTest {
private fun actions(steam: Boolean, displays: List<SecondScreenDisplay>,
micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {},
onClose: () -> Unit = {},
select: (SecondScreenMode) -> Unit = {}) =
DrawerActions(steam = steam, isHomeApp = false, androidApps = emptyList(), hudOn = false,
micAvailable = micAvailable, micEnabled = micEnabled, onMicEnabled = onMic,
@@ -269,5 +261,5 @@ class SessionSecondScreenTest {
onHud = {}, onFrameGenPick = {}, onImportLossless = {}, onKeyboard = {}, onHardwareKeyboard = {},
onSteamMenu = null, onQam = null, onOsc = {}, onSuspendPolicy = {}, onBackActionsInverted = {},
onTouch = {}, onFexPreset = {}, onSecondScreenMode = select, onSecondScreenDisplay = {},
onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = {})
onLaunchAndroidApp = { _, _ -> }, onBackground = {}, onShareLogs = {}, onStop = {}, onClose = onClose)
}