Unify controller and screen input profiles for game and desktop sessions (#1439)

## Problem and intent

Desktop sessions need configurable mouse, keyboard and application
actions from a controller. On dual-screen devices, a lower-screen
trackpad may already handle the pointer, leaving the physical controls
available for other assignments. This PR gives physical controllers and
local touch controls a shared profile/action model instead of separate
configuration paths.

This follows the centralization direction discussed in
[#1202](https://github.com/Droid-Deck/DroidDeck/pull/1202#issuecomment-6299647180)
and addresses the controller-input portion of #860 and #1356. Those
discussions are context, **not prior maintainer approval** of this
implementation. I would appreciate architectural feedback and guidance
on splitting or coordinating this work if that would make review easier.

## Profiles and configuration

- Controller stays within the existing Setup tabs. Game and Desktop each
have a default-profile selector, followed by one profile list and device
settings.
- Named profiles reference three independently reusable parts: Physical
controller, Main screen and Second screen. Layout geometry and action
bindings are stored separately. Profiles can share physical controls
while assigning different touch actions.
- The session menu selects a complete profile, or expands to mix the
three parts. A mixed selection can be saved as a new profile; Game and
Desktop retain separate selections.
- Both screens use the same full-size editor, with add, move, resize,
snapping, undo and shared properties. The main-screen editor has
movable, collapsible tools and is transparent above a running session.
When editing the secondary display, its entire area is the canvas and
the main display hosts tools/properties.
- The old fixed gamepad, fixed Deck controls and separate Screen keys
editor are replaced with editable presets and the shared renderer.
Existing positions, bindings, shapes, symbols, imported images and
toggle behavior migrate; legacy Screen keys become additional profiles
without replacing the user's selected profile. Migration retains a
backup before removing old preferences.
- Saved layouts have thumbnails and screen targeting. Actions include
compatible native output/remapping, keys/combinations, mouse buttons,
pointer movement, vertical/horizontal scrolling, directional keys,
existing menu/keyboard commands, and disabled. Buttons can use symbols,
shapes and toggle behavior.

## Architecture and latency


```mermaid
flowchart LR
    Library[Profiles + reusable layouts and bindings] --> Router[InputRouter]
    Physical[Physical controller adapters] --> Router
    Touch[Main + secondary InputSurfaceView] --> Sources[Owned pad / Deck sources]
    Sources --> Router
    BLE[Steam Controller BLE adapter] --> Router
    Router --> Native[Existing controller publication]
    Native --> Steam[Steam Input / guest controller]
    Router --> Held[Shared key and mouse ownership]
    Held --> Guest[Existing guest input outputs]
    Router --> UI[Existing menu / keyboard hosts]
```

Bindings resolve when the profile changes, outside event dispatch.
Native forwarding has no additional frame/timer queue; identity routes
reuse existing state/reports. Only synthesized continuous stick
pointer/scroll motion uses a frame callback. One source releasing a
key/button does not release another source's hold. Menu, profile,
suspension and removal transitions release old outputs and gate held
controls until neutral.

Steam continues to own game-specific mappings and action sets. Steam
Mobile Touch and VR retain their specialized paths. Raw device adapters
remain responsible for transport/calibration and must join routing
before publishing consumed controls; this does not claim that every
adapter has been unified.

Historical Thor measurements on the native Game path found
kernel-event-to-guest-observer upper-bound medians of **3.061 ms
baseline versus 2.999–3.403 ms candidate**, with a subsequent
installed-APK check at **3.039 ms / 300 matched edges**. These are
relative software-path measurements, not button-to-photon latency. Some
tails increased, simultaneous BLE contention remains unmeasured, and
**this UI revision has not had a new latency measurement**. The previous
cursor fix changed visual update intervals from roughly 33.3 ms to 16.7
ms without changing sensitivity or adding smoothing.

[Full design, migration and
boundaries](https://github.com/Delete228/DroidDeck/blob/codex/unified-controller-input/docs/development/unified-input-proposal.md).

## Validation

Updated through upstream 542bbf89c; current PR head 08526f828. The
latest CodeRabbit review generated no actionable comments.

- **1,017 tests passed in 133 suites after the latest upstream merge**,
with no failures, errors or skips: all input/UI tests, global reset,
component updates, PiP policy, runtime auto-update and Proton menu
auto-selection. The pre-merge review-fix run passed **967
input/UI/global-reset tests**. The subsequent second-screen refresh fix
passed **35 focused surface/presentation tests**, including three new
state-preservation regressions.
- Full local run before the final review follow-ups: **3,598 tests,
3,573 passed, 25 failed**. The 25 are unchanged upstream macOS
limitations: log-export tests requiring SecureDirectoryStream (24) and a
case-sensitive WoW add-on test (1). The global-reset regression also
passes. Earlier disk-exhausted attempts were discarded; the completed
run bounded temporary resources with one worker and JVM recycling,
without excluding tests or changing repository test configuration.
- APK build, runtime/session assets, native dependencies, alignment and
v1/v2/v3 signatures passed. Installed over the separate Input Test app
on **AYN Thor** with its environment retained. Local packaging omits
Rust store engines; the [full Build APK workflow for 08526f828
passed](https://github.com/Droid-Deck/DroidDeck/actions/runs/42295403480),
including Android/JVM, Python/native, Rust store-engine and Xbox checks.
- Review follow-ups keep migration IDs stable, preserve unreadable
supported-version libraries before recovery, retain forward-version
protection, release keyboard owners on focus loss, handle unavailable
presentation displays, and allow controller confirmation/cancellation
after key capture. Deck router cleanup checks ownership; BLE teardown
synchronously blocks late routing/publication, and shared Triton slot
ownership protects a replacement controller from stale instances. Legacy
Select-to-Steam migrates to Desktop without replacing saved bindings;
mouse backend transitions are serialized with publication. Profile
refresh now updates custom controls in place, preserving
terminal/dashboard state, the field keyboard and WoW chat. No physical
BLE-controller test or new latency measurement was performed.
- The latest 08526f828 APK is installed on Thor. Profile preferences
stayed byte-for-byte identical and the retained Steam environment
reached READY at 1280×720 / 60 Hz. The earlier capture-dialog fix was
also exercised on Thor. APK SHA-256:
`ed6ef888648468b4ebeb94e8f1ae74a195bb1f0a3f27e4fb3646d5462a4beb6b`.
- Upstream integration preserves the new WoW chat panel,
platform-pointer and PiP fixes. The fast-double-tap stick-click rule and
its six regressions were adapted to the shared renderer; WoW field
selection also preserves Ctrl held by a profile.
- Latest Thor UI pass: existing Setup navigation, profile/layout
previews, action persistence, centered element creation, main-screen
editing over Steam, secondary canvas with primary tools/properties, and
X returning from the docked menu to controls.
- Across the documented device sessions, the user tested native physical
buttons/sticks/triggers, Deck pads/grips, desktop
pointer/clicks/scrolling/arrows, Android keyboard with physical input,
Ctrl+F and Ctrl+A/X/V/S, simultaneous physical/touch holds, menu release
and Home/resume. These historical checks are distinguished from the
latest UI-only pass.

[Revision-specific results, APK hashes and
limitations](https://github.com/Delete228/DroidDeck/blob/codex/unified-controller-input/docs/development/unified-input-validation.md).

## Coordination and remaining work

- #1202 (jmarti326): shortcut capture/device identity and the
shared-assignment discussion informed this work.
- #1305 (kingokksa): shared PC-key definitions were adapted from that
PR; this does not absorb its entire feature set.
- #1414, #581, #1226 and #1150 remain relevant for external-device
input, calibration, keyboard routing and DualSense integration. The
DualSense coordination discussion in this PR describes adapter
boundaries and duplicate-stream suppression.

Import/export, automatic per-app selection, macros, multi-button
activation chords and automatic text-field keyboard detection remain out
of scope. A single binding emitting a key combination is implemented.

The configuration UI is now implemented and exercised on Thor. I am
happy to continue UX/accessibility/localization refinements here before
merge, or in follow-up PRs, according to maintainer feedback. The main
review questions remain the shared model, source ownership/lifecycle
contract, migration policy and integration with other input work.


## UI walkthrough on AYN Thor

Actual captures from the installed Input Test build. In paired images,
the main display is above the second display. The test application name
and local build badge are not production branding changes.

<details>
<summary>Controller settings: separate defaults for Desktop and Game,
followed by the profile library.</summary>

<img width="960" alt="Controller settings: separate defaults for Desktop
and Game, followed by the profile library."
src="https://github.com/user-attachments/assets/a4c156d6-9ded-43df-b0f8-e5f34028806d"
/>

</details>

<details>
<summary>Physical controller: bindings grouped by control type, with
each current action visible.</summary>

<img width="960" alt="Physical controller: bindings grouped by control
type, with each current action visible."
src="https://github.com/user-attachments/assets/a8a840e3-19ac-473f-9f55-b06ae9c637b5"
/>

</details>

<details>
<summary>Reusable layouts: bounded previews and separate screen
targets.</summary>

<img width="960" alt="Reusable layouts: bounded previews and separate
screen targets."
src="https://github.com/user-attachments/assets/cf0cf7d1-42f3-46cd-b50b-f01e1fa8ed41"
/>

</details>

<details>
<summary>Main-screen editor over the live Steam UI, with the movable
tools expanded. The background is Steam artwork, not a running
game.</summary>

<img width="960" alt="Main-screen editor over the live Steam UI, with
the movable tools expanded. The background is Steam artwork, not a
running game."
src="https://github.com/user-attachments/assets/0781f7c8-fd10-47e5-8a23-817f945a6289"
/>

</details>

<details>
<summary>Dual-screen editor: tools and selection on the main display,
full-size placement canvas on the second display.</summary>

<img width="720" alt="Dual-screen editor: tools and selection on the
main display, full-size placement canvas on the second display."
src="https://github.com/user-attachments/assets/f13d4ef6-be6d-4d95-9d42-e047e0a63b8a"
/>

</details>

<details>
<summary>The selected lower-screen trackpad stays visible while its
properties open on the main display.</summary>

<img width="720" alt="The selected lower-screen trackpad stays visible
while its properties open on the main display."
src="https://github.com/user-attachments/assets/26baf597-f037-419e-9601-e48f086c0d4f"
/>

</details>

<details>
<summary>Session menu: expand Profile to select the physical,
main-screen and second-screen parts independently.</summary>

<img width="720" alt="Session menu: expand Profile to select the
physical, main-screen and second-screen parts independently."
src="https://github.com/user-attachments/assets/27ac4d9c-68b3-4257-8353-23104e2343de"
/>

</details>
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-07 08:32:50 -05:00
commit 22a675a664
98 files changed
+10181 -4879

No files matched your search

@@ -0,0 +1,36 @@
package com.droiddeck.launcher.input
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class InputButtonIconsTest {
@Test fun commandSymbolsRenderUsingTheButtonTintAndHaveReadableNames() {
val context = RuntimeEnvironment.getApplication()
for (code in listOf(InputButtonIcons.MENU, InputButtonIcons.KEYBOARD, InputButtonIcons.STEAM, InputButtonIcons.QUICK_ACCESS)) {
val drawable = InputButtonIcons.drawable(context, code)
assertNotNull(drawable)
assertNotEquals(code.toString(), InputButtonIcons.label(context, code))
val bitmap = Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_8888)
try {
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.GREEN }
assertTrue(InputButtonIcons.draw(Canvas(bitmap), code, 32f, 32f, 48f, paint, drawable))
val pixels = IntArray(64 * 64)
bitmap.getPixels(pixels, 0, 64, 0, 0, 64, 64)
assertTrue(pixels.count { Color.alpha(it) > 0 } > 30)
assertTrue(pixels.filter { Color.alpha(it) > 0 }.all { Color.green(it) > 0 && Color.red(it) == 0 && Color.blue(it) == 0 })
} finally { bitmap.recycle() }
}
}
}
@@ -0,0 +1,394 @@
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 freshLibraryHasOnlyTheMainGamepadAndTwoLowerScreenLayouts() {
val library = InputLibraries.read(context)
assertEquals(listOf("game", "desktop"), library.profiles.map { it.id })
assertEquals(setOf(InputLibraries.OVERLAY, InputLibraries.DECK, InputLibraries.TRACKPAD), library.layouts.map { it.id }.toSet())
assertEquals(6, library.bindings.size)
assertEquals(InputLibraries.DECK, library.activeLayout(false, InputRole.SECONDARY)?.id)
assertEquals(InputLibraries.TRACKPAD, library.activeLayout(true, InputRole.SECONDARY)?.id)
assertEquals(InputAction.Pointer(), library.compileActive(true).action(InputRole.PHYSICAL, InputControl.LS))
assertEquals(InputAction.Native(), library.compileActive(false).action(InputRole.PHYSICAL, InputControl.LS))
val desktop = library.activeLayout(true, InputRole.SECONDARY)!!
val pad = desktop.elements.single { it.kind == InputElementKind.TRACKPAD }
assertTrue(pad.mouseGestures)
assertEquals(3, desktop.elements.size)
assertEquals(InputAction.Pointer(), library.compileActive(true).elementAction(InputRole.SECONDARY, pad.id, pad.control))
assertEquals(InputAction.MouseButton(272), library.compileActive(true).elementClickAction(InputRole.SECONDARY, pad))
val game = library.activeLayout(false, InputRole.SECONDARY)!!
assertEquals(9, game.elements.size)
assertEquals(setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD), game.elements.filter { it.kind == InputElementKind.TRACKPAD }.map { it.control }.toSet())
for (control in listOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5)) {
val element = game.elements.single { it.control == control }
assertEquals(InputAction.Native(), library.compileActive(false).elementAction(InputRole.SECONDARY, element.id, element.control))
}
for ((isDesktop, commands) in listOf(true to listOf(InputCommand.MENU, InputCommand.KEYBOARD),
false to listOf(InputCommand.STEAM, InputCommand.QUICK_ACCESS, InputCommand.MENU))) {
val elements = library.activeLayout(isDesktop, InputRole.SECONDARY)!!.elements.filter { it.id.startsWith("command:") }
assertEquals(commands.map { InputAction.Command(it) }, elements.map { library.compileActive(isDesktop).elementAction(InputRole.SECONDARY, it.id, it.control) })
assertTrue(elements.all { InputButtonIcons.has(it.icon) && it.icon > 255 })
}
assertEquals(library, InputLibraries.decode(InputLibraries.encode(library)))
}
@Test fun legacyLowerScreenBindingsKeepTheirOriginalControlsWithoutSavedGeometry() {
prefs.edit().putBoolean("migrated", true).putString("profile.game",
"""{"version":1,"bindings":[{"role":"SECONDARY","control":"a","action":{"type":"keys","codes":[57]}}]}""").commit()
val library = InputLibraries.read(context)
assertEquals(InputSurfaceLayout.defaults(), library.layout("game", InputRole.SECONDARY)?.elements)
assertEquals(InputAction.Keys(listOf(57)), library.compile("game").elementAction(InputRole.SECONDARY, "legacy:a", InputControl.A))
}
@Test fun existingLibrariesKeepTheirSavedLayoutsBindingsAndSelections() {
var original = InputLibraries.read(context).duplicateProfile("desktop", "Browser", "browser")
val layout = SavedInputLayout("builtin.left-pad", "My left pad", InputSurfaceLayout.defaults(), screen = InputLayoutScreen.SECONDARY)
original = original.withLayout(layout).withPreset(SavedInputBindings("preset.left-pad", "My left pad", false, layout.id,
controls = mapOf(InputControl.LEFT_PAD to InputAction.Pointer(700f))))
.selectProfile(true, "browser").selectPart(true, InputRole.SECONDARY, "preset.left-pad").validate()
val raw = org.json.JSONObject(InputLibraries.encode(original)).put("version", 6).toString()
prefs.edit().putString("library", raw).commit()
assertEquals(original, InputLibraries.read(context))
assertEquals(original, InputLibraries.read(context))
}
@Test fun resettingDefaultActionsKeepsTheMenuAndKeyboardCommands() {
val library = InputLibraries.read(context)
for (id in listOf("game", "desktop")) {
val reset = library.resetProfile(id).validate()
for (element in library.layout(id, InputRole.SECONDARY)!!.elements.filter { it.id.startsWith("command:") }) {
assertEquals(library.compile(id).elementAction(InputRole.SECONDARY, element.id, element.control),
reset.compile(id).elementAction(InputRole.SECONDARY, element.id, element.control))
}
}
}
@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 unreadableLibrariesKeepStableEditorReferencesUntilAnEditPreservesRecoveryData() {
val valid = InputLibraries.encode(InputLibraries.read(context))
val invalidValues = listOf("{broken", org.json.JSONObject(valid).put("selected", "missing").toString())
for (raw in invalidValues) {
prefs.edit().putString("library", raw).commit()
val first = InputLibraries.read(context)
val second = InputLibraries.read(context)
assertEquals(first, second)
val id = first.profile("game").binding(InputRole.PRIMARY)
assertEquals(first.preset(id), second.preset(id))
assertEquals(raw, prefs.getString("library", null))
val updated = InputLibraries.update(context) { it.copy(selected = "desktop") }
assertEquals("desktop", InputLibraries.read(context).selected)
assertEquals(updated, InputLibraries.read(context))
assertTrue(prefs.all.filterKeys { it.startsWith("library-recovery.") }.containsValue(raw))
}
assertTrue(InputLibraries.hasLibraryRecovery(context))
assertEquals(invalidValues.toSet(), prefs.all.filterKeys { it.startsWith("library-recovery.") }.values.toSet())
}
@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 explicitAutoSelectionStaysDistinctFromAnInheritedProfileAfterSaving() {
val original = InputLibraries.read(context)
val binding = original.profile("game").binding(InputRole.PHYSICAL)
val inherited = original.selectPart(false, InputRole.PHYSICAL, binding)
val explicit = original.selectProfile(false, InputProfiles.AUTO).selectPart(false, InputRole.PHYSICAL, binding)
assertFalse(InputLibraries.decode(InputLibraries.encode(inherited))!!.selection(false).profileSelected)
assertTrue(InputLibraries.decode(InputLibraries.encode(explicit))!!.selection(false).profileSelected)
assertEquals(inherited.compileActive(false), explicit.compileActive(false))
}
@Test fun versionSevenSelectionsRetainKnownProfileAndPartChoices() {
val original = InputLibraries.read(context)
val binding = original.profile("game").binding(InputRole.PHYSICAL)
val choices = listOf(
original.selectPart(false, InputRole.PHYSICAL, binding) to false,
original.selectProfile(false, InputProfiles.AUTO) to true,
original.selectProfile(false, "game").selectPart(false, InputRole.PHYSICAL, binding) to true,
original.selectPart(false, InputRole.SECONDARY, InputStockLayouts.TRACKPAD) to false,
)
for ((library, selected) in choices) {
val old = org.json.JSONObject(InputLibraries.encode(library)).put("version", 7)
old.getJSONObject("selections").getJSONObject("game").remove("profileSelected")
prefs.edit().putString("library", old.toString()).commit()
val restored = InputLibraries.read(context)
assertEquals(selected, restored.selection(false).profileSelected)
assertEquals(library, restored)
assertEquals(restored, InputLibraries.read(context))
}
}
@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.TRACKPAD)
assertThrows(IllegalArgumentException::class.java) { library.removeBindings(InputStockLayouts.TRACKPAD) }
assertThrows(IllegalArgumentException::class.java) { library.removeLayout(InputLibraries.TRACKPAD) }
assertThrows(IllegalArgumentException::class.java) { library.selectPart(false, InputRole.PHYSICAL, InputStockLayouts.TRACKPAD).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)))
}
}
@@ -0,0 +1,85 @@
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 InputProfilesTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit()
context.getSharedPreferences("controller", Context.MODE_PRIVATE).edit().clear().commit()
context.getSharedPreferences("input-surfaces", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun migrationKeepsLegacyTouchMappingSeparateFromPhysicalControls() {
ControllerPrefs.setTarget(context, "a", "b")
ControllerPrefs.setTarget(context, "x", "off")
ControllerPrefs.setSelectSteam(context, true)
val game = InputProfiles.read(context, InputProfile.GAME)
assertEquals(InputAction.Native(InputControl.B), game.action(InputRole.PRIMARY, InputControl.A))
assertEquals(InputAction.Disabled, game.action(InputRole.PRIMARY, InputControl.X))
assertEquals(InputAction.Native(), game.action(InputRole.PHYSICAL, InputControl.A))
assertEquals(InputAction.Native(InputControl.GUIDE), game.action(InputRole.PHYSICAL, InputControl.SELECT))
assertEquals(InputAction.Native(InputControl.GUIDE), InputProfiles.read(context, InputProfile.DESKTOP)
.action(InputRole.PHYSICAL, InputControl.SELECT))
InputProfiles.reset(context, InputProfile.GAME)
assertEquals(InputAction.Native(), InputProfiles.read(context, InputProfile.GAME).action(InputRole.PRIMARY, InputControl.A))
}
@Test fun migrationPreservesSavedDesktopSelectBinding() {
ControllerPrefs.setSelectSteam(context, true)
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().putString("profile.desktop",
"""{"version":1,"bindings":[{"role":"PHYSICAL","control":"select","action":{"type":"disabled"}}]}""").commit()
assertEquals(InputAction.Disabled, InputProfiles.read(context, InputProfile.DESKTOP)
.action(InputRole.PHYSICAL, InputControl.SELECT))
}
@Test fun migrationKeepsDesktopKeyboardWhenSelectToSteamIsOff() {
assertEquals(InputAction.Command(InputCommand.KEYBOARD), InputProfiles.read(context, InputProfile.DESKTOP)
.action(InputRole.PHYSICAL, InputControl.SELECT))
}
@Test fun bindingsAndDeviceKeysRoundTripWithoutAffectingOtherProfile() {
val game = InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.SECONDARY, InputControl.A, InputAction.Keys(listOf(29, 30)))
.copy(keys = listOf(PhysicalInputBinding(PhysicalInputKey("1:2:descriptor", "Thor", 131, 59), InputAction.Command(InputCommand.MENU))))
InputProfiles.save(context, game)
assertEquals(game, InputProfiles.read(context, InputProfile.GAME))
assertEquals(InputAction.Pointer(), InputProfiles.read(context, InputProfile.DESKTOP).action(InputRole.PHYSICAL, InputControl.LS))
}
@Test fun profileSelectionIsExplicitAndNeverDependsOnDisplayPresence() {
assertEquals(InputProfile.DESKTOP, InputProfiles.active(context, true).id)
assertEquals(InputProfile.GAME, InputProfiles.active(context, false).id)
InputProfiles.select(context, InputProfile.GAME)
assertEquals(InputProfile.GAME, InputProfiles.active(context, true).id)
}
@Test fun unknownVersionDoesNotExecuteBindings() {
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit()
.putString("profile.game", """{"version":999,"bindings":[]} """).commit()
val profile = InputProfiles.read(context, InputProfile.GAME)
assertEquals(InputProfile.defaults(InputProfile.GAME).bindings, profile.bindings)
assertEquals(mapOf(
InputRole.PRIMARY to mapOf("builtin:keyboard" to InputAction.Command(InputCommand.KEYBOARD)),
InputRole.SECONDARY to mapOf("command:0" to InputAction.Command(InputCommand.MENU),
"command:2" to InputAction.Command(InputCommand.STEAM), "command:3" to InputAction.Command(InputCommand.QUICK_ACCESS)),
), profile.elements)
}
@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(.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))
}
}
@@ -0,0 +1,241 @@
package com.droiddeck.launcher.input
import org.junit.Assert.*
import org.junit.Test
class InputRouterTest {
private class Output : InputOutput {
val events = mutableListOf<String>()
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 $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" }
}
private val output = Output()
private val router = InputRouter(output)
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) }
repeat(1000) { assertSame(state, source.route(state)) }
assertTrue(output.events.isEmpty())
}
@Test fun retainedPadReturnsToNativeFastPathAfterHeldControlsReachNeutral() {
val raw = PadState().apply { press(PadState.A, true); leftX = .8f }
val source = router.pad(InputRole.PHYSICAL, raw)
raw.press(PadState.B, true)
val blocked = source.route(raw)
assertFalse(blocked.isDown(PadState.A))
assertEquals(0f, blocked.leftX)
assertTrue(blocked.isDown(PadState.B))
raw.clear()
source.route(raw)
raw.press(PadState.A, true)
repeat(1000) { assertSame(raw, source.route(raw)) }
assertTrue(output.events.isEmpty())
}
@Test fun localBindingConsumesOnlyItsOwnNativeControlAndReleasesModifiersLast() {
router.setProfile(bind(InputControl.A, InputAction.Keys(listOf(29, 30))))
val source = router.pad(InputRole.PHYSICAL)
val state = PadState().apply { press(PadState.A, true); press(PadState.B, true); leftX = .4f }
val routed = source.route(state)
assertFalse(routed.isDown(PadState.A)); assertTrue(routed.isDown(PadState.B))
assertEquals(.4f, routed.leftX)
source.route(state)
state.press(PadState.A, false); source.route(state)
assertEquals(listOf("key 29 true", "key 30 true", "key 30 false", "key 29 false"), output.events)
}
@Test fun twoSourcesHoldingOneKeyDoNotReleaseEachOther() {
val p = bind(InputControl.A, InputAction.Keys(listOf(57)))
.withBinding(InputRole.SECONDARY, InputControl.B, InputAction.Keys(listOf(57)))
router.setProfile(p)
val physical = router.pad(InputRole.PHYSICAL)
val touch = router.pad(InputRole.SECONDARY)
physical.route(PadState().apply { press(PadState.A, true) })
touch.route(PadState().apply { press(PadState.B, true) })
touch.close()
assertEquals(listOf("key 57 true"), output.events)
physical.release()
assertEquals(listOf("key 57 true", "key 57 false"), output.events)
}
@Test fun remapCombinesHeldTargetsRatherThanLastButtonWinning() {
router.setProfile(bind(InputControl.A, InputAction.Native(InputControl.B)))
val source = router.pad(InputRole.PHYSICAL)
val raw = PadState().apply { press(PadState.A, true) }
assertTrue(source.route(raw).isDown(PadState.B))
raw.press(PadState.B, true); raw.press(PadState.A, false)
assertTrue(source.route(raw).isDown(PadState.B))
raw.press(PadState.B, false)
assertFalse(source.route(raw).isDown(PadState.B))
}
@Test fun profileChangeBlocksHeldNativeInputUntilNeutral() {
val source = router.pad(InputRole.PHYSICAL)
val raw = PadState().apply { press(PadState.A, true) }
source.route(raw)
router.setProfile(bind(InputControl.A, InputAction.Keys(listOf(1))))
source.route(raw)
assertTrue(output.events.isEmpty())
raw.press(PadState.A, false); source.route(raw)
raw.press(PadState.A, true); source.route(raw)
assertEquals(listOf("key 1 true"), output.events)
}
@Test fun changingLocalBindingReleasesOldKeyWithoutPressingNewOne() {
router.setProfile(bind(InputControl.A, InputAction.Keys(listOf(1))))
val source = router.pad(InputRole.PHYSICAL)
val raw = PadState().apply { press(PadState.A, true) }
source.route(raw)
router.setProfile(bind(InputControl.A, InputAction.Keys(listOf(28))))
source.route(raw)
assertEquals(listOf("key 1 true", "key 1 false"), output.events)
}
@Test fun triggersUseHysteresisAndCommandsFireOnce() {
router.setProfile(bind(InputControl.LT, InputAction.Command(InputCommand.MENU)))
val source = router.pad(InputRole.PHYSICAL)
val raw = PadState()
for (value in listOf(.6f, .5f, .4f, .6f, .3f, .6f)) { raw.leftTrigger = value; source.route(raw) }
assertEquals(listOf("MENU", "MENU"), output.events)
}
@Test fun pointerTicksOnlyWhileMovingAndOrdinaryKeysDoNotWaitForTick() {
router.setProfile(InputProfile.defaults(InputProfile.DESKTOP))
val source = router.pad(InputRole.PHYSICAL)
val raw = PadState().apply { leftX = 1f; press(PadState.X, true) }
source.route(raw)
assertTrue(output.events.contains("key 28 true"))
assertFalse(output.events.any { it.startsWith("pointer") })
assertTrue(router.tick(.01f)); assertTrue(output.events.contains("pointer 9.0 0.0"))
raw.clear(); source.route(raw)
assertFalse(router.tick(.01f))
}
@Test fun trackpadUsesContactRelativeDeltasWithoutFirstTouchJump() {
router.setProfile(bind(InputControl.RIGHT_PAD, InputAction.Pointer(1000f), InputRole.SECONDARY))
val channel = router.channel(InputRole.SECONDARY, InputControl.RIGHT_PAD)
assertNull(channel.update(.5f, .5f, true))
assertTrue(output.events.isEmpty())
channel.update(.6f, .6f, true)
assertEquals(1, output.events.size)
assertTrue(output.events[0].startsWith("pointer 100."))
channel.update(0f, 0f, false)
channel.update(-.9f, -.9f, true)
assertEquals(1, output.events.size)
}
@Test fun stickScrollFollowsUpAndDownForEveryInputRoleAndStopsOnRelease() {
for (role in InputRole.entries) {
router.setProfile(bind(InputControl.RS, InputAction.Scroll(10f), role))
val channel = router.channel(role, InputControl.RS)
output.events.clear()
channel.update(0f, -1f)
repeat(2) { assertTrue(router.tick(.05f)) }
assertEquals(listOf("motion", "scroll -1"), output.events)
channel.update(0f, 1f)
repeat(2) { assertTrue(router.tick(.05f)) }
assertEquals("scroll 1", output.events.last())
channel.release()
val count = output.events.size
assertFalse(router.tick(.05f))
assertEquals(count, output.events.size)
channel.close()
}
}
@Test fun trackpadScrollKeepsItsContactDirectionAndDoesNotScheduleStickMotion() {
router.setProfile(bind(InputControl.LEFT_PAD, InputAction.Scroll(10f), InputRole.SECONDARY))
val channel = router.channel(InputRole.SECONDARY, InputControl.LEFT_PAD)
channel.update(0f, 0f, true)
channel.update(0f, .5f, true)
channel.update(0f, 0f, true)
assertEquals(listOf("scroll 5", "scroll -5"), output.events)
assertFalse(router.tick(.05f))
}
@Test fun disablingRoutingReleasesKeysAndBlocksHeldInputOnResume() {
router.setProfile(bind(InputControl.A, InputAction.Keys(listOf(1))))
val source = router.pad(InputRole.PHYSICAL)
val raw = PadState().apply { press(PadState.A, true) }
source.route(raw); router.setEnabled(false); source.route(raw); router.setEnabled(true); source.route(raw)
assertEquals(listOf("key 1 true", "key 1 false"), output.events)
raw.clear(); source.route(raw); raw.press(PadState.A, true); source.route(raw)
assertEquals("key 1 true", output.events.last())
}
@Test fun disabledSourcesDoNotLeakNativeButtons() {
val source = router.pad(InputRole.PHYSICAL)
router.setEnabled(false)
assertFalse(source.route(PadState().apply { press(PadState.A, true) }).isDown(PadState.A))
}
@Test fun lifecycleReleaseAlsoBlocksNativeIdentityRoute() {
val source = router.pad(InputRole.PHYSICAL)
val raw = PadState().apply { press(PadState.A, true) }
source.route(raw); router.releaseAll()
assertFalse(source.route(raw).isDown(PadState.A))
}
@Test fun mergedPadKeepsPhysicalButtonAndWholeStickVector() {
val physical = PadState().apply { press(PadState.A, true); leftX = .8f; leftY = -.6f }
physical.merge(PadState().apply { leftX = -.2f; leftY = .1f })
assertTrue(physical.isDown(PadState.A)); assertEquals(.8f, physical.leftX); assertEquals(-.6f, physical.leftY)
}
@Test fun outputOwnershipKeepsKeyboardAndMappingHoldsIndependent() {
val held = HeldInput(output::key)
held.set(1, 29, true); held.set(4, 29, true); held.release(4)
assertEquals(listOf("key 29 true"), output.events)
held.clear(); assertEquals("key 29 false", output.events.last())
}
}
@@ -0,0 +1,291 @@
package com.droiddeck.launcher.input
import java.io.File
import org.junit.Assert.*
import org.junit.After
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.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class])
class InputSourceOwnershipTest {
private val bridge = PadBridge(File(RuntimeEnvironment.getApplication().cacheDir, "input-ownership"))
private fun state() = JoyConPadTest.RecordingWriter.pads[0]!!
@After fun close() { bridge.stop(); DeckControls.releaseAll(); DeckControls.setRouter(null) }
@Test fun profileAndEnableChangesLeaveRingClosedUntilInputArrives() {
bridge.setInputRouter(InputRouter(RecordingOutput()))
bridge.setInputProfile(InputProfile.defaults(InputProfile.DESKTOP))
bridge.setInputEnabled(false)
bridge.setInputEnabled(true)
assertFalse(ReflectionHelpers.getField<Boolean>(bridge, "open"))
bridge.applyExternal({ it.press(PadState.X, true) }, true)
assertTrue(ReflectionHelpers.getField<Boolean>(bridge, "open"))
}
@Test fun disablingRoutingPublishesReleaseToAnAlreadyOpenRing() {
bridge.setInputRouter(InputRouter(RecordingOutput()))
bridge.applyExternal({ it.press(PadState.A, true) }, true)
assertTrue(state().isDown(PadState.A))
bridge.setInputEnabled(false)
assertFalse(state().isDown(PadState.A))
bridge.setInputEnabled(true)
assertFalse(state().isDown(PadState.A))
}
@Test fun repeatedEnableStateDoesNotRepublishPadOrDeckReports() {
val router = InputRouter(RecordingOutput())
bridge.setInputRouter(router)
DeckControls.setRouter(router)
bridge.applyExternal({ it.press(PadState.A, true) }, true)
DeckControls.setGrip(DeckControls.L4, true)
for (enabled in listOf(true, false, true)) {
bridge.setInputEnabled(enabled)
val padWrites = JoyConPadTest.RecordingWriter.padWrites
val deckWrites = JoyConPadTest.RecordingWriter.deckWrites
repeat(10) { bridge.setInputEnabled(enabled) }
assertEquals(padWrites, JoyConPadTest.RecordingWriter.padWrites)
assertEquals(deckWrites, JoyConPadTest.RecordingWriter.deckWrites)
}
assertFalse(state().isDown(PadState.A))
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
bridge.applyExternal({ it.press(PadState.A, false) }, true)
DeckControls.setGrip(DeckControls.L4, false)
bridge.applyExternal({ it.press(PadState.A, true) }, true)
DeckControls.setGrip(DeckControls.L4, true)
assertTrue(state().isDown(PadState.A))
assertEquals(DeckControls.L4, JoyConPadTest.RecordingWriter.grips)
}
@Test fun replacingADisabledRouterAllowsTheNewRouterToBeDisabled() {
bridge.setInputRouter(InputRouter(RecordingOutput()))
bridge.setInputEnabled(false)
bridge.setInputRouter(InputRouter(RecordingOutput()))
bridge.applyExternal({ it.press(PadState.A, true) }, true)
assertTrue(state().isDown(PadState.A))
bridge.setInputEnabled(false)
assertFalse(state().isDown(PadState.A))
}
@Test fun attachingADisabledRouterAllowsItToBeEnabled() {
bridge.setInputRouter(InputRouter(RecordingOutput()).also { it.setEnabled(false) })
bridge.setInputEnabled(true)
bridge.applyExternal({ it.press(PadState.A, true) }, true)
assertTrue(state().isDown(PadState.A))
}
@Test fun replacingRouterReleasesRetainedPhysicalAndTouchHoldsUntilNeutral() {
val before = RecordingOutput()
val after = RecordingOutput()
val profile = InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Keys(listOf(29)))
.withBinding(InputRole.SECONDARY, InputControl.B, InputAction.Keys(listOf(29)))
bridge.setInputRouter(InputRouter(before).also { it.setProfile(profile) })
bridge.applyExternal({ it.press(PadState.A, true) }, true)
val touch = Any()
bridge.applyTouch(touch, InputRole.SECONDARY) { it.press(PadState.B, true) }
bridge.setInputRouter(InputRouter(after).also { it.setProfile(profile) })
bridge.applyExternal({ it.press(PadState.X, true) }, true)
assertEquals(listOf("key 29 true", "key 29 false"), before.events)
assertTrue(after.events.isEmpty())
bridge.applyExternal({ it.press(PadState.A, false) }, true)
bridge.applyExternal({ it.press(PadState.A, true) }, true)
assertEquals(listOf("key 29 true"), after.events)
bridge.applyExternal({ it.press(PadState.A, false) }, true)
assertEquals(listOf("key 29 true", "key 29 false"), after.events)
bridge.applyTouch(touch, InputRole.SECONDARY) { it.press(PadState.B, false) }
bridge.applyTouch(touch, InputRole.SECONDARY) { it.press(PadState.B, true) }
assertEquals("key 29 true", after.events.last())
}
@Test fun replacingRouterReleasesRetainedNativeButtonsAndStick() {
bridge.setInputRouter(InputRouter(RecordingOutput()))
bridge.applyExternal({ it.press(PadState.A, true); it.leftX = .8f }, true)
bridge.setInputRouter(InputRouter(RecordingOutput()))
assertFalse(state().isDown(PadState.A))
assertEquals(0f, state().leftX)
bridge.applyExternal({ it.press(PadState.B, true) }, true)
assertTrue(state().isDown(PadState.B))
assertFalse(state().isDown(PadState.A))
assertEquals(0f, state().leftX)
bridge.applyExternal({ it.press(PadState.A, false); it.leftX = 0f }, true)
bridge.applyExternal({ it.press(PadState.A, true); it.leftX = .8f }, true)
assertTrue(state().isDown(PadState.A))
assertEquals(.8f, state().leftX)
}
@Test fun replacingDeckRouterBlocksExistingGripAndContactUntilRelease() {
DeckControls.setRouter(InputRouter(RecordingOutput()))
val surface = DeckControls.source(InputRole.SECONDARY)
try {
surface.setGrip(DeckControls.L4, true)
surface.setPad(false, true, .3f, .4f)
DeckControls.setRouter(InputRouter(RecordingOutput()))
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
surface.setPad(false, true, .5f, .6f)
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
surface.setGrip(DeckControls.L4, false)
surface.setPad(false, false)
surface.setGrip(DeckControls.L4, true)
surface.setPad(false, true, .2f, .3f)
assertEquals(DeckControls.L4 or 16, JoyConPadTest.RecordingWriter.grips)
} finally { surface.close() }
}
@Test fun clearingOldDeckOwnerPreservesReplacementBindingsAndHeldKeys() {
val previous = InputRouter(RecordingOutput())
val output = RecordingOutput()
val replacement = InputRouter(output).also {
it.setProfile(InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.L4, InputAction.Keys(listOf(57))))
}
DeckControls.setRouter(previous)
DeckControls.setRouter(replacement)
DeckControls.setGrip(DeckControls.L4, true)
DeckControls.clearRouter(previous)
DeckControls.clearRouter(null)
assertEquals(listOf("key 57 true"), output.events)
DeckControls.setGrip(DeckControls.L4, false)
DeckControls.setGrip(DeckControls.L4, true)
assertEquals(listOf("key 57 true", "key 57 false", "key 57 true"), output.events)
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
}
@Test fun clearingCurrentDeckOwnerReleasesItsKeysAndRemovesBindings() {
val output = RecordingOutput()
val router = InputRouter(output).also {
it.setProfile(InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.L4, InputAction.Keys(listOf(57))))
}
DeckControls.setRouter(router)
DeckControls.setGrip(DeckControls.L4, true)
DeckControls.clearRouter(router)
DeckControls.clearRouter(router)
DeckControls.setGrip(DeckControls.L4, false)
DeckControls.setGrip(DeckControls.L4, true)
assertEquals(listOf("key 57 true", "key 57 false"), output.events)
assertEquals(DeckControls.L4, JoyConPadTest.RecordingWriter.grips)
}
@Test fun releasingAllKeepsPhysicalGripsBlockedUntilNeutral() {
val router = InputRouter(RecordingOutput())
bridge.setInputRouter(router)
DeckControls.setRouter(router)
DeckControls.setGrip(DeckControls.L4, true)
assertEquals(DeckControls.L4, JoyConPadTest.RecordingWriter.grips)
bridge.releaseAll()
DeckControls.setGrip(DeckControls.L4, true)
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
DeckControls.setGrip(DeckControls.L4, false)
DeckControls.setGrip(DeckControls.L4, true)
assertEquals(DeckControls.L4, JoyConPadTest.RecordingWriter.grips)
}
@Test fun cancellingHomeReleasesDeckOutputAndKeepsGripsBlockedUntilNeutral() {
val router = InputRouter(RecordingOutput())
bridge.setInputRouter(router)
DeckControls.setRouter(router)
bridge.setHomeGuidePressed(true)
DeckControls.setGrip(DeckControls.L4, true)
assertEquals(DeckControls.L4, JoyConPadTest.RecordingWriter.grips)
bridge.cancelHomeGuide()
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
DeckControls.setGrip(DeckControls.L4, true)
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
DeckControls.setGrip(DeckControls.L4, false)
DeckControls.setGrip(DeckControls.L4, true)
assertEquals(DeckControls.L4, JoyConPadTest.RecordingWriter.grips)
}
private class RecordingOutput : InputOutput {
val events = mutableListOf<String>()
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() { events += "motion" }
}
@Test fun removingLastTouchSurfaceReleasesLegacyMouseRoute() {
val routed = PadState()
bridge.setTouchRoute(object : PadBridge.TouchRoute {
override fun active() = true
override fun accept(state: PadState) { routed.copyFrom(state) }
})
val first = Any(); val second = Any()
bridge.applyTouch(first, InputRole.PRIMARY) { it.press(PadState.A, true) }
bridge.applyTouch(second, InputRole.SECONDARY) { it.press(PadState.A, true) }
bridge.releaseTouch(first)
assertTrue(routed.isDown(PadState.A))
bridge.releaseTouch(second)
assertFalse(routed.isDown(PadState.A))
}
@Test fun nativeTrackpadKeepsItsOwnerUntilThatContactEnds() {
val first = DeckControls.source(InputRole.PRIMARY)
val second = DeckControls.source(InputRole.SECONDARY)
try {
first.setPad(false, true, .25f, .5f)
val firstPosition = JoyConPadTest.RecordingWriter.deckPads.copyOf()
second.setPad(false, true, -.75f, -.5f)
assertArrayEquals(firstPosition, JoyConPadTest.RecordingWriter.deckPads)
first.setPad(false, false)
assertTrue(JoyConPadTest.RecordingWriter.deckPads[0] < 0)
second.close()
assertEquals(0, JoyConPadTest.RecordingWriter.grips and 16)
} finally { first.close(); second.close() }
}
@Test fun closingOneSurfaceDoesNotReleaseAnotherSurfaceOrPhysicalPad() {
val a = Any(); val b = Any()
bridge.applyExternal({ it.press(PadState.A, true) }, true)
bridge.applyTouch(a, InputRole.PRIMARY) { it.press(PadState.A, true); it.press(PadState.B, true) }
bridge.applyTouch(b, InputRole.SECONDARY) { it.press(PadState.X, true) }
bridge.releaseTouch(a)
assertTrue(state().isDown(PadState.A)); assertTrue(state().isDown(PadState.X)); assertFalse(state().isDown(PadState.B))
bridge.releaseTouch(b)
assertTrue(state().isDown(PadState.A)); assertFalse(state().isDown(PadState.X))
}
@Test fun disconnectingSecondaryDeckSurfaceKeepsPhysicalGripHeld() {
val surface = DeckControls.source(InputRole.SECONDARY)
DeckControls.setGrip(DeckControls.L4, true)
surface.setGrip(DeckControls.L4, true)
surface.close()
assertEquals(DeckControls.L4, JoyConPadTest.RecordingWriter.grips)
DeckControls.setGrip(DeckControls.L4, false)
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
}
@Test fun nativePadAndTouchMappingsUseDifferentRoles() {
val output = 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 router = InputRouter(output)
bridge.setInputRouter(router)
bridge.setInputProfile(InputProfile.defaults(InputProfile.GAME).withBinding(InputRole.SECONDARY, InputControl.A, InputAction.Disabled))
val touch = Any()
bridge.applyTouch(touch, InputRole.SECONDARY) { it.press(PadState.A, true) }
assertFalse(state().isDown(PadState.A))
bridge.applyExternal({ it.press(PadState.A, true) }, true)
assertTrue(state().isDown(PadState.A))
bridge.releaseAll()
assertFalse(state().isDown(PadState.A))
bridge.applyExternal({ it.press(PadState.B, true) }, true)
assertFalse(state().isDown(PadState.A))
assertTrue(state().isDown(PadState.B))
bridge.applyExternal({ it.press(PadState.A, false) }, true)
bridge.applyExternal({ it.press(PadState.A, true) }, true)
assertTrue(state().isDown(PadState.A))
}
}
@@ -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)
}
}
@@ -240,16 +240,26 @@ class JoyConPadTest {
@Implementation fun open(): Boolean = true
@Implementation fun close() = Unit
@Implementation fun destroy() = Unit
@Implementation fun writePad(state: PadState) { pads[slot] = PadState().apply { copyFrom(state) } }
@Implementation fun writePad(state: PadState) {
pads[slot] = PadState().apply { copyFrom(state) }
padWrites++
}
companion object {
val pads = HashMap<Int, PadState>()
var padWrites = 0
var deckWrites = 0
var grips = 0
var deckPads = ShortArray(4)
@JvmStatic @Implementation fun __staticInitializer__() = Unit
@JvmStatic @Implementation
fun writeDeckControls(slot: Int, controls: Int, pads: ShortArray, pressure: ShortArray) { grips = controls }
fun writeDeckControls(slot: Int, controls: Int, pads: ShortArray, pressure: ShortArray) {
grips = controls
deckPads = pads.copyOf()
deckWrites++
}
}
}
}
@@ -0,0 +1,95 @@
package com.droiddeck.launcher.input
import android.content.Context
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE)
class 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))
}
@Test fun failedScreenKeyMigrationKeepsUpgradedBindingIdsStableForEditorLookup() {
val original = InputLibraries.read(context).chooseLayout("game", InputRole.SECONDARY, InputLibraries.DECK)
val fixed = original.copy(layouts = original.layouts.map {
when (it.id) {
InputLibraries.OVERLAY -> it.copy(elements = emptyList(), template = InputLayoutTemplate.OVERLAY)
InputLibraries.DECK -> it.copy(elements = emptyList(), template = InputLayoutTemplate.DECK)
else -> it
}
}, bindings = original.bindings.map {
if (it.layoutId in setOf(InputLibraries.OVERLAY, InputLibraries.DECK)) it.copy(elements = emptyMap(), clicks = emptyMap()) else it
})
val raw = JSONObject(InputLibraries.encode(fixed)).put("version", 2).toString()
prefs.edit().putString("library", raw).commit()
ControllerPrefs.prefs(context).edit().putString("screenKeys", "28:NaN,0.5,44").commit()
val first = InputLibraries.read(context)
val second = InputLibraries.read(context)
assertEquals(first, second)
for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY)) {
val id = first.profile("game").binding(role)
assertEquals(first.preset(id), second.preset(id))
assertTrue(second.layout("game", role)!!.editable)
}
assertEquals(raw, prefs.getString("library", null))
assertTrue(InputLibraries.hasPendingScreenKeyMigration(context))
assertEquals("28:NaN,0.5,44", ControllerPrefs.prefs(context).getString("screenKeys", null))
}
}
@@ -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,506 +13,172 @@ 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 aCancelledSecondFingerDoesNotArmAStickClick() {
touch(MotionEvent.ACTION_DOWN, 7 to (660f to 400f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (660f to 400f), 9 to (540f to 400f))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 7 to (660f to 400f), 9 to (540f to 400f), flags = MotionEvent.FLAG_CANCELED)
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (660f to 400f), 9 to (540f to 400f))
assertEquals(false, field(control("ls"), "clicked"))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 7 to (660f to 400f), 9 to (540f to 400f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (660f to 400f), 9 to (540f to 400f))
assertEquals(true, field(control("ls"), "clicked"))
}
@Test fun movingTheStickAndTouchingItAgainDoesNotClickIt() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_MOVE, 1 to (600f to 400f))
touch(MotionEvent.ACTION_UP, 1 to (600f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(false, field(control("ls"), "clicked"))
}
@Test fun liftingFarFromTheTouchPointDoesNotArmAStickClick() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_UP, 1 to (600f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(false, field(control("ls"), "clicked"))
}
@Test fun aLongHoldThenAQuickTouchDoesNotClickTheStick() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
time += 600
touch(MotionEvent.ACTION_UP, 1 to (540f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(false, field(control("ls"), "clicked"))
}
@Test fun aFastDoubleTapClicksTheStickAndCanBeHeldWhileMoving() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_UP, 1 to (540f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_MOVE, 1 to (600f to 400f))
assertEquals(true, field(control("ls"), "clicked"))
touch(MotionEvent.ACTION_UP, 1 to (600f to 400f))
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(false, field(control("ls"), "clicked"))
}
@Test fun aSlowSecondTapDoesNotClickTheStick() {
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
touch(MotionEvent.ACTION_UP, 1 to (540f to 400f))
time += 400
touch(MotionEvent.ACTION_DOWN, 1 to (540f to 400f))
assertEquals(false, 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"))
measure(view)
assertFalse(state().isDown(PadState.A))
assertFalse(view.takesTouchAt(800f, 250f))
assertTrue(view.takesTouchAt(450f, 480f))
}
@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 aCancelledSecondFingerDoesNotArmAStickClick() {
touch(MotionEvent.ACTION_DOWN, 7 to (800f to 250f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (800f to 250f), 9 to (200f to 300f))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 7 to (800f to 250f), 9 to (200f to 300f), flags = MotionEvent.FLAG_CANCELED)
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (800f to 250f), 9 to (200f to 300f))
assertFalse(state().isDown(PadState.L3))
touch(MotionEvent.ACTION_POINTER_UP or (1 shl 8), 7 to (800f to 250f), 9 to (200f to 300f))
touch(MotionEvent.ACTION_POINTER_DOWN or (1 shl 8), 7 to (800f to 250f), 9 to (200f to 300f))
assertTrue(state().isDown(PadState.L3))
}
@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)
@Test fun movingTheStickAndTouchingItAgainDoesNotClickIt() {
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
touch(MotionEvent.ACTION_MOVE, 1 to (250f to 300f))
touch(MotionEvent.ACTION_UP, 1 to (250f to 300f))
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
assertFalse(state().isDown(PadState.L3))
}
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
@Test fun liftingFarFromTheTouchPointDoesNotArmAStickClick() {
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
touch(MotionEvent.ACTION_UP, 1 to (250f to 300f))
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
assertFalse(state().isDown(PadState.L3))
}
@Test fun aLongHoldThenAQuickTouchDoesNotClickTheStick() {
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
time += 600
touch(MotionEvent.ACTION_UP, 1 to (200f to 300f))
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
assertFalse(state().isDown(PadState.L3))
}
@Test fun aFastDoubleTapClicksTheStickAndCanBeHeldWhileMoving() {
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
touch(MotionEvent.ACTION_UP, 1 to (200f to 300f))
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
touch(MotionEvent.ACTION_MOVE, 1 to (250f to 300f))
assertTrue(state().isDown(PadState.L3))
touch(MotionEvent.ACTION_UP, 1 to (250f to 300f))
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
assertFalse(state().isDown(PadState.L3))
}
@Test fun aSlowSecondTapDoesNotClickTheStick() {
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
touch(MotionEvent.ACTION_UP, 1 to (200f to 300f))
time += 400
touch(MotionEvent.ACTION_DOWN, 1 to (200f to 300f))
assertFalse(state().isDown(PadState.L3))
}
private fun touch(action: Int, vararg pointers: Pair<Int, Pair<Float, Float>>, flags: Int = 0): Boolean {
val properties = pointers.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray()
val coords = pointers.map { (_, position) -> MotionEvent.PointerCoords().apply { x = position.first; y = position.second; pressure = 1f; size = 1f } }.toTypedArray()
val event = MotionEvent.obtain(1000L, time++, action, pointers.size, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, flags)
return try { view.onTouchEvent(event) } finally { event.recycle() }
return try { view.dispatchTouchEvent(event) } finally { event.recycle() }
}
}
@@ -375,6 +375,37 @@ class PadBridgeQamTest {
}
}
@Test fun playerSlotHomeGuidePreservesRemappedInputAndTheEnableGate() {
PadBridge.setFirstSlot(1)
try {
bridge.setBuiltinPad(false)
routed(InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Native(InputControl.B))
.withBinding(InputRole.PHYSICAL, InputControl.LS, InputAction.Native(InputControl.RS)))
val device = controller()
bridge.onKeyEvent(key(device, KeyEvent.KEYCODE_BUTTON_A))
motion(device, MotionEvent.AXIS_X, .6f)
bridge.setHomeGuidePressed(true)
val held = requireNotNull(JoyConPadTest.RecordingWriter.pads[1])
assertTrue(held.isDown(PadState.GUIDE))
assertTrue(held.isDown(PadState.B))
assertFalse(held.isDown(PadState.A))
assertEquals(0f, held.leftX)
assertEquals(.6f, held.rightX)
bridge.setInputEnabled(false)
val disabled = requireNotNull(JoyConPadTest.RecordingWriter.pads[1])
assertTrue(disabled.isDown(PadState.GUIDE))
assertFalse(disabled.isDown(PadState.A))
assertFalse(disabled.isDown(PadState.B))
assertEquals(0f, disabled.leftX)
assertEquals(0f, disabled.rightX)
bridge.cancelHomeGuide()
assertFalse(requireNotNull(JoyConPadTest.RecordingWriter.pads[1]).isDown(PadState.GUIDE))
} finally {
PadBridge.setFirstSlot(0)
}
}
@Test fun removingThePrimaryPlayerForgetsItsHomeGuide() {
PadBridge.setFirstSlot(1)
try {
@@ -440,6 +471,117 @@ class PadBridgeQamTest {
assertFalse(pad().isDown(PadState.GUIDE))
}
@Test fun ordinaryRoutedInputDoesNotWaitForTheChordQueue() {
routed(InputProfile.defaults(InputProfile.GAME))
bridge.applyExternal({ it.press(PadState.A, true); it.leftX = .6f }, true)
assertTrue(pad().isDown(PadState.A))
assertEquals(.6f, pad().leftX)
bridge.applyExternal({ it.press(PadState.A, false); it.leftX = 0f }, true)
assertFalse(pad().isDown(PadState.A))
assertEquals(0f, pad().leftX)
}
@Test fun routedQamDuringAnActiveChordPublishesOtherInputImmediately() {
ReflectionHelpers.setStaticField(FakeInputWriter::class.java, "padType", FakeInputWriter.PAD_TYPE_XBOX)
routed(InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.X, InputAction.Native(InputControl.QAM)))
bridge.triggerQam()
assertTrue(pad().isDown(PadState.GUIDE))
bridge.applyExternal({ it.press(PadState.X, true); it.press(PadState.B, true); it.leftX = .6f }, true)
assertTrue(pad().isDown(PadState.GUIDE))
assertTrue(pad().isDown(PadState.B))
assertEquals(.6f, pad().leftX)
assertFalse(pad().isDown(PadState.QAM))
bridge.applyExternal({ it.press(PadState.X, false); it.press(PadState.B, false); it.leftX = 0f }, true)
assertFalse(pad().isDown(PadState.B))
assertEquals(0f, pad().leftX)
advanceTime()
assertFalse(pad().isDown(PadState.GUIDE))
assertFalse(pad().isDown(PadState.A))
}
@Test fun queuedChordsKeepRoutedAndTouchAxesInsteadOfRawPhysicalAxes() {
routed(InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.LS, InputAction.Native(InputControl.RS)))
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.leftY = -.8f }, true)
val touch = Any()
bridge.applyTouch(touch, InputRole.SECONDARY) { it.leftX = .5f }
advance(20)
bridge.applyExternal({ it.leftY = -.25f }, true)
advance(60)
assertEquals(.5f, pad().leftX)
assertEquals(0f, pad().leftY)
assertEquals(-.25f, pad().rightY)
}
@Test fun queuedChordsDoNotLeakDesktopAxesToSteam() {
routed(InputProfile.defaults(InputProfile.DESKTOP))
bridge.setHomeGuidePressed(true)
bridge.applyExternal({ it.leftY = -1f; it.rightY = .8f }, true)
advance(80)
assertEquals(0f, pad().leftY)
assertEquals(0f, pad().rightY)
}
@Test fun disablingRoutingDiscardsQueuedNativeButtons() {
routed(InputProfile.defaults(InputProfile.GAME))
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.press(PadState.A, true) }, true)
advance(20)
bridge.setInputEnabled(false)
advance(60)
assertFalse(pad().isDown(PadState.A))
bridge.setInputEnabled(true)
assertFalse(pad().isDown(PadState.A))
}
@Test fun changingProfileDiscardsQueuedNativeButtons() {
routed(InputProfile.defaults(InputProfile.GAME))
bridge.setHomeGuidePressed(true)
bridge.applyExternal({ it.press(PadState.A, true) }, true)
advance(20)
bridge.setInputProfile(InputProfile.defaults(InputProfile.DESKTOP))
advance(60)
assertFalse(pad().isDown(PadState.A))
}
@Test fun cancellingHomeKeepsHeldInputBlockedUntilNeutral() {
routed(InputProfile.defaults(InputProfile.GAME))
bridge.setHomeGuidePressed(true)
bridge.applyExternal({ it.leftY = -1f }, true)
bridge.cancelHomeGuide()
bridge.applyExternal({ it.leftY = -.9f }, true)
assertEquals(0f, pad().leftY)
bridge.applyExternal({ it.leftY = 0f }, true)
bridge.applyExternal({ it.leftY = -.9f }, true)
assertEquals(-.9f, pad().leftY)
}
@Test fun cancellingBackKeepsHeldInputBlockedUntilNeutral() {
routed(InputProfile.defaults(InputProfile.GAME))
bridge.setBackQamPressed(true)
bridge.applyExternal({ it.leftY = -1f }, true)
bridge.cancelBackQam()
bridge.applyExternal({ it.leftY = -.9f }, true)
assertEquals(0f, pad().leftY)
bridge.applyExternal({ it.leftY = 0f }, true)
bridge.applyExternal({ it.leftY = -.9f }, true)
assertEquals(-.9f, pad().leftY)
}
private fun routed(profile: InputProfile) {
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() {}
}))
bridge.setInputProfile(profile)
}
@Test fun zeroDeadZoneDriftDoesNotKeepAxesBlockedAfterBackRelease() {
val device = controller()
bridge.setStickDeadZone(0)
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.input
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyEvent
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.InputDeviceBuilder
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
class PhysicalInputBindingsTest {
private val events = ArrayList<String>()
private val router = InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) { events += "$code $down" }
override fun button(code: Int, down: Boolean) {}
override fun pointer(dx: Float, dy: Float) {}
override fun scroll(steps: Int) {}
override fun command(command: InputCommand) { events += command.name }
override fun requestMotion() {}
})
private val bindings = PhysicalInputBindings(router)
private fun device(id: Int): InputDevice {
val device = InputDeviceBuilder.newBuilder().setId(id).setName("Thor extra keys").setDescriptor("keys-$id")
.setSources(InputDevice.SOURCE_KEYBOARD).setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC).build()
val manager = RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)
shadowOf(manager).addInputDevice(device)
return device
}
private fun event(id: Int, down: Boolean, code: Int = KeyEvent.KEYCODE_F1, repeat: Int = 0) =
KeyEvent(0L, 0L, if (down) KeyEvent.ACTION_DOWN else KeyEvent.ACTION_UP, code, repeat, 0, id, 59, 0, InputDevice.SOURCE_KEYBOARD)
@Test fun captureReservesSystemKeysButAcceptsKeyboardBackButtons() {
val device = device(40)
assertNotNull(PhysicalInputKey.capture(event(device.id, true)))
assertNull(PhysicalInputKey.capture(event(device.id, true, KeyEvent.KEYCODE_VOLUME_UP)))
assertNull(PhysicalInputKey.capture(event(device.id, true, KeyEvent.KEYCODE_HOME)))
}
@Test fun bindingMatchesOnlyItsDeviceAndReleasesAfterEditingProfile() {
val device = device(40); val other = device(41)
val key = PhysicalInputKey.capture(event(device.id, true))!!
bindings.configure(listOf(PhysicalInputBinding(key, InputAction.Keys(listOf(29, 30)))))
assertFalse(bindings.onKey(event(other.id, true), true))
assertTrue(bindings.onKey(event(device.id, true), true))
bindings.configure(listOf(PhysicalInputBinding(key, InputAction.Keys(listOf(28)))))
assertTrue(bindings.onKey(event(device.id, true, repeat = 1), true))
assertTrue(bindings.onKey(event(device.id, false), true))
assertEquals(listOf("29 true", "30 true", "30 false", "29 false"), events)
bindings.onKey(event(device.id, true), true)
assertEquals("28 true", events.last())
}
@Test fun releasesRemainConsumedAfterOpeningMenuAndVirtualKeysAreUntouched() {
val device = device(40)
val key = PhysicalInputKey.capture(event(device.id, true))!!
bindings.configure(listOf(PhysicalInputBinding(key, InputAction.Keys(listOf(57)))))
assertFalse(bindings.onKey(event(-1, true), true))
bindings.onKey(event(device.id, true), true)
bindings.release()
assertTrue(bindings.onKey(event(device.id, false), false))
assertEquals(listOf("57 true", "57 false"), events)
}
}
@@ -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()
}
}
}
@@ -26,6 +26,12 @@ class SecondScreenModeTest {
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false, dashboard = true))
}
@Test fun customControlsReopenWithEitherControllerType() {
for (deckPad in listOf(false, true)) {
assertEquals(SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.opening("custom-controls", deckPad))
}
}
@Test fun anUnknownOrClosedChoiceFallsBackToTheDefault() {
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("gone", deckPad = false, dashboard = true))
@@ -0,0 +1,168 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.hardware.display.DisplayManager
import android.view.Display
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.json.JSONObject
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 org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], shadows = [SessionInputPointerTest.WriterShadow::class])
class SecondScreenProfileMigrationTest {
private lateinit var activity: SessionActivity
private val previousMode = SessionState.mode
private val previousPanel = SessionState.secondScreenMode
private val previousDisplay = SessionState.secondScreenDisplay
@Before fun setUp() {
SessionState.secondScreenMode = SecondScreenMode.NONE
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val displays = activity.getSystemService(DisplayManager::class.java)
shadowOf(displays.getDisplay(Display.DEFAULT_DISPLAY)).setFlags(Display.FLAG_PRESENTATION)
ReflectionHelpers.setField(activity, "displayManager", displays)
ReflectionHelpers.setField(activity, "started", true)
val display: MutableState<Int> = ReflectionHelpers.getField(activity, "selectedSecondScreenDisplay\$delegate")
display.value = Display.DEFAULT_DISPLAY
}
@After fun tearDown() {
ReflectionHelpers.callInstanceMethod<Unit>(activity, "closeSecondScreen", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true))
SessionState.mode = previousMode
SessionState.secondScreenMode = previousPanel
SessionState.secondScreenDisplay = previousDisplay
}
@Test fun automaticOpeningKeepsCustomLayoutsAndBindingsInBothSessionModes() {
for (desktop in listOf(false, true)) for (deckPad in listOf(false, true)) {
val original = customLibrary(desktop)
open(null, deckPad)
assertEquals(original, InputLibraries.read(activity))
assertNull(SessionPrefs.secondScreenPanel(activity))
assertEquals(SecondScreenMode.CUSTOM_CONTROLS, SessionState.secondScreenMode)
}
}
@Test fun unavailableOrUnknownPanelsDoNotReplaceCustomControls() {
for (remembered in listOf("none", "gone", "dashboard", "desktop")) for (deckPad in listOf(false, true)) {
val original = customLibrary(desktop = false)
SessionPrefs.setSecondScreenPanel(activity, remembered)
open(remembered, deckPad)
assertEquals(original, InputLibraries.read(activity))
assertEquals(remembered, SessionPrefs.secondScreenPanel(activity))
assertEquals(SecondScreenMode.CUSTOM_CONTROLS, SessionState.secondScreenMode)
}
}
@Test fun explicitlySavedLegacyPanelsStillMigrateOnlyTheCurrentMode() {
for (desktop in listOf(false, true)) for (legacy in listOf(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.KEYBOARD_TRACKPAD)) {
val original = customLibrary(desktop)
SessionPrefs.setSecondScreenPanel(activity, legacy.id)
open(legacy.id, deckPad = true)
val preset = if (legacy == SecondScreenMode.DECK_CONTROLS) InputStockLayouts.DECK else InputStockLayouts.TRACKPAD
val expected = original.selectPart(desktop, InputRole.SECONDARY, preset)
assertEquals(expected, InputLibraries.read(activity))
assertEquals(SecondScreenMode.CUSTOM_CONTROLS.id, SessionPrefs.secondScreenPanel(activity))
open(SessionPrefs.secondScreenPanel(activity), deckPad = true)
assertEquals(expected, InputLibraries.read(activity))
}
}
@Test fun legacyPanelsDoNotReplaceAnExistingQuickSelection() {
customLibrary(desktop = true)
val original = InputLibraries.update(activity) { it.selectPart(true, InputRole.SECONDARY, "custom.bindings") }
SessionPrefs.setSecondScreenPanel(activity, SecondScreenMode.DECK_CONTROLS.id)
open(SecondScreenMode.DECK_CONTROLS.id, deckPad = true)
assertEquals(original, InputLibraries.read(activity))
assertEquals(SecondScreenMode.CUSTOM_CONTROLS.id, SessionPrefs.secondScreenPanel(activity))
}
@Test fun unrelatedPartSelectionsDoNotSkipTheSavedPanelMigration() {
for (desktop in listOf(false, true)) for (role in listOf(InputRole.PHYSICAL, InputRole.PRIMARY)) {
customLibrary(desktop)
val original = InputLibraries.update(activity) { it.selectPart(desktop, role, it.profile("game").binding(role)) }
SessionPrefs.setSecondScreenPanel(activity, SecondScreenMode.KEYBOARD_TRACKPAD.id)
open(SecondScreenMode.KEYBOARD_TRACKPAD.id, deckPad = true)
assertEquals(original.selectPart(desktop, InputRole.SECONDARY, InputStockLayouts.TRACKPAD), InputLibraries.read(activity))
assertEquals(SecondScreenMode.CUSTOM_CONTROLS.id, SessionPrefs.secondScreenPanel(activity))
}
}
@Test fun explicitProfilesIncludingAutoKeepTheirSecondaryLayoutAfterOtherPartChanges() {
for (desktop in listOf(false, true)) for (profile in listOf(InputProfiles.AUTO, InputProfile.GAME, InputProfile.DESKTOP)) {
for (role in listOf(null, InputRole.PHYSICAL, InputRole.PRIMARY)) {
customLibrary(desktop)
val original = InputLibraries.update(activity) { library ->
val selected = library.selectProfile(desktop, profile)
if (role == null) selected else selected.selectPart(desktop, role, selected.profile("game").binding(role))
}
SessionPrefs.setSecondScreenPanel(activity, SecondScreenMode.DECK_CONTROLS.id)
open(SecondScreenMode.DECK_CONTROLS.id, deckPad = true)
assertEquals(original, InputLibraries.read(activity))
assertEquals(SecondScreenMode.CUSTOM_CONTROLS.id, SessionPrefs.secondScreenPanel(activity))
}
}
}
@Test fun unavailableDeckPanelKeepsItsSavedChoiceUntilItCanMigrate() {
for (desktop in listOf(false, true)) {
val original = customLibrary(desktop)
SessionPrefs.setSecondScreenPanel(activity, SecondScreenMode.DECK_CONTROLS.id)
open(SecondScreenMode.DECK_CONTROLS.id, deckPad = false)
assertEquals(original, InputLibraries.read(activity))
assertEquals(SecondScreenMode.DECK_CONTROLS.id, SessionPrefs.secondScreenPanel(activity))
open(SessionPrefs.secondScreenPanel(activity), deckPad = true)
assertEquals(original.selectPart(desktop, InputRole.SECONDARY, InputStockLayouts.DECK), InputLibraries.read(activity))
assertEquals(SecondScreenMode.CUSTOM_CONTROLS.id, SessionPrefs.secondScreenPanel(activity))
}
}
@Test fun failedMigrationKeepsTheSavedPanelAndCanBeRetried() {
val original = customLibrary(desktop = false)
val prefs = activity.getSharedPreferences("input-profiles", Context.MODE_PRIVATE)
val valid = prefs.getString("library", null)!!
val unsupported = JSONObject(valid).put("version", 999).toString()
prefs.edit().putString("library", unsupported).commit()
SessionPrefs.setSecondScreenPanel(activity, SecondScreenMode.KEYBOARD_TRACKPAD.id)
open(SecondScreenMode.KEYBOARD_TRACKPAD.id, deckPad = true)
assertEquals(unsupported, prefs.getString("library", null))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD.id, SessionPrefs.secondScreenPanel(activity))
prefs.edit().putString("library", valid).commit()
open(SessionPrefs.secondScreenPanel(activity), deckPad = true)
assertEquals(original.selectPart(false, InputRole.SECONDARY, InputStockLayouts.TRACKPAD), InputLibraries.read(activity))
assertEquals(SecondScreenMode.CUSTOM_CONTROLS.id, SessionPrefs.secondScreenPanel(activity))
}
private fun customLibrary(desktop: Boolean): InputLibrary {
SessionState.mode = if (desktop) SessionService.MODE_DESKTOP else SessionService.MODE_STEAM
return InputLibraries.update(activity) { library ->
val id = if (desktop) InputProfile.DESKTOP else InputProfile.GAME
val element = InputSurfaceElement(InputControl.A, .3f, .2f, .2f, .2f, "custom.button")
val layout = SavedInputLayout("custom.layout", "Custom controls", listOf(element), screen = InputLayoutScreen.SECONDARY)
val bindings = SavedInputBindings("custom.bindings", "Custom actions", false, layout.id,
elements = mapOf(element.id to InputAction.Keys(listOf(57))))
val profile = library.profile(id)
library.withLayout(layout).withPreset(bindings)
.withProfile(profile.copy(parts = profile.parts + (InputRole.SECONDARY to InputPart(bindings.id, layout.id))))
.copy(selections = emptyMap())
}
}
private fun open(remembered: String?, deckPad: Boolean) {
val mode = SecondScreenMode.opening(remembered, deckPad)
ReflectionHelpers.callInstanceMethod<Unit>(activity, "showSecondScreen", ReflectionHelpers.ClassParameter.from(SecondScreenMode::class.java, mode))
}
}
@@ -0,0 +1,110 @@
package com.droiddeck.launcher.input
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyEvent
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.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.InputDeviceBuilder
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class,
PadBridgeRoutingTest.RegisteredKeyEvent::class])
class SelectProfileRoutingTest {
private val context get() = RuntimeEnvironment.getApplication()
private val bridge = PadBridge(File(context.cacheDir, "select-profile"))
private val events = mutableListOf<String>()
private val output = object : InputOutput {
override fun key(code: Int, down: Boolean) { events += "key $code $down" }
override fun button(code: Int, down: Boolean) = Unit
override fun pointer(dx: Float, dy: Float) = Unit
override fun scroll(steps: Int) = Unit
override fun command(command: InputCommand) { events += command.name }
override fun requestMotion() = Unit
}
private val device = InputDeviceBuilder.newBuilder().setId(42).setName("Select test pad")
.setDescriptor("select-test").setSources(InputDevice.SOURCE_GAMEPAD).build()
@Before fun setUp() {
context.getSharedPreferences("input-profiles", 0).edit().clear().commit()
context.getSharedPreferences("controller", 0).edit().clear().commit()
ControllerPrefs.setSelectSteam(context, true)
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
bridge.setInputRouter(InputRouter(output))
bridge.setInputProfile(InputProfiles.active(context, desktop = false))
}
@After fun close() { bridge.stop() }
@Test fun migratedSteamSelectReachesGuideAndReleasesWithoutReleasingPhysicalGuide() {
key(KeyEvent.KEYCODE_BUTTON_SELECT, true)
assertTrue(state().isDown(PadState.GUIDE))
assertFalse(state().isDown(PadState.SELECT))
key(KeyEvent.KEYCODE_BUTTON_MODE, true)
key(KeyEvent.KEYCODE_BUTTON_SELECT, false)
assertTrue(state().isDown(PadState.GUIDE))
key(KeyEvent.KEYCODE_BUTTON_MODE, false)
assertFalse(state().isDown(PadState.GUIDE))
}
@Test fun profileResetAndExplicitNativeBindingOverrideTheMigratedSetting() {
val migrated = InputProfiles.active(context, desktop = false)
InputProfiles.save(context, migrated.withBinding(InputRole.PHYSICAL, InputControl.SELECT, InputAction.Native()))
bridge.setInputProfile(InputProfiles.active(context, desktop = false))
assertNativeSelect()
InputProfiles.reset(context, InputProfile.GAME)
bridge.setInputProfile(InputProfiles.active(context, desktop = false))
assertNativeSelect()
assertTrue(ControllerPrefs.read(context).selectSteam)
}
@Test fun disabledAndLocalSelectBindingsDoNotLeakGuide() {
for (action in listOf(InputAction.Disabled, InputAction.Keys(listOf(28)), InputAction.Command(InputCommand.KEYBOARD))) {
bridge.setInputProfile(InputProfile.defaults(InputProfile.GAME).withBinding(InputRole.PHYSICAL, InputControl.SELECT, action))
key(KeyEvent.KEYCODE_BUTTON_SELECT, true)
assertFalse(state().isDown(PadState.GUIDE))
assertFalse(state().isDown(PadState.SELECT))
key(KeyEvent.KEYCODE_BUTTON_SELECT, false)
}
assertEquals(listOf("key 28 true", "key 28 false", "KEYBOARD"), events)
}
@Test fun replacingOrRemovingRouterWhileSelectIsHeldNeverLeavesGuideStuck() {
key(KeyEvent.KEYCODE_BUTTON_SELECT, true)
bridge.setInputRouter(null)
assertFalse(state().isDown(PadState.GUIDE))
key(KeyEvent.KEYCODE_BUTTON_SELECT, false)
assertFalse(state().isDown(PadState.SELECT))
key(KeyEvent.KEYCODE_BUTTON_SELECT, true)
bridge.setInputRouter(InputRouter(output).also { it.setProfile(InputProfiles.active(context, desktop = false)) })
assertFalse(state().isDown(PadState.GUIDE))
key(KeyEvent.KEYCODE_BUTTON_SELECT, false)
assertFalse(state().isDown(PadState.GUIDE))
key(KeyEvent.KEYCODE_BUTTON_SELECT, true)
assertTrue(state().isDown(PadState.GUIDE))
key(KeyEvent.KEYCODE_BUTTON_SELECT, false)
assertFalse(state().isDown(PadState.GUIDE))
}
private fun assertNativeSelect() {
key(KeyEvent.KEYCODE_BUTTON_SELECT, true)
assertTrue(state().isDown(PadState.SELECT))
assertFalse(state().isDown(PadState.GUIDE))
key(KeyEvent.KEYCODE_BUTTON_SELECT, false)
}
private fun key(code: Int, down: Boolean) {
assertTrue(bridge.onKeyEvent(KeyEvent(0, 0, if (down) KeyEvent.ACTION_DOWN else KeyEvent.ACTION_UP,
code, 0, 0, device.id, 0, 0, InputDevice.SOURCE_GAMEPAD)))
}
private fun state() = JoyConPadTest.RecordingWriter.pads[0]!!
}
@@ -0,0 +1,141 @@
package com.droiddeck.launcher.input
import android.hardware.input.InputManager
import android.os.Looper
import android.view.InputDevice
import android.view.KeyEvent
import androidx.compose.runtime.MutableState
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.LoadingState
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import java.io.File
import java.time.Duration
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 org.robolectric.shadows.InputDeviceBuilder
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class,
PadBridgeRoutingTest.RegisteredKeyEvent::class])
class SessionBackBindingTest {
private val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
private val bridge = PadBridge(File(activity.cacheDir, "back-binding"))
private val events = mutableListOf<Pair<Int, Boolean>>()
private val router = InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) { events += code to 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() {}
})
private val bindings = PhysicalInputBindings(router)
private val previousMode = SessionState.mode
private val previousRunning = SessionState.running
private val previousFrame = SessionState.firstFrameSeen
private val previousDeck = SessionState.deckPad
private val previousSuspended = SessionState.suspended
@Before fun setUp() {
SessionState.mode = SessionService.MODE_STEAM
SessionState.running = true
SessionState.firstFrameSeen = true
SessionState.deckPad = true
SessionState.suspended = false
ReflectionHelpers.setStaticField(FakeInputWriter::class.java, "padType", FakeInputWriter.PAD_TYPE_DECK)
ReflectionHelpers.setField(activity, "padBridge", bridge)
ReflectionHelpers.setField(activity, "physicalInputBindings", bindings)
ReflectionHelpers.setField(activity, "loading", LoadingState(activity).apply { visible = false })
ReflectionHelpers.getField<MutableState<Boolean>>(activity, "resumed\$delegate").value = true
val device = InputDeviceBuilder.newBuilder().setId(42).setName("Back key").setDescriptor("back-key")
.setSources(InputDevice.SOURCE_KEYBOARD).setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC).build()
shadowOf(activity.getSystemService(InputManager::class.java)).addInputDevice(device)
bridge.setInputRouter(router)
bridge.start()
}
@After fun close() {
ReflectionHelpers.getField<BackQamInput>(activity, "backQamInput").cancel()
bindings.close()
bridge.stop()
SessionState.mode = previousMode
SessionState.running = previousRunning
SessionState.firstFrameSeen = previousFrame
SessionState.deckPad = previousDeck
SessionState.suspended = previousSuspended
}
@Test fun capturedBackBindingTakesPrecedenceOverTheDefaultQamShortcut() {
bindings.configure(listOf(PhysicalInputBinding(PhysicalInputKey.capture(event(true))!!, InputAction.Keys(listOf(28)))))
assertTrue(activity.dispatchKeyEvent(event(true)))
assertEquals(listOf(28 to true), events)
advance(700)
assertFalse(JoyConPadTest.RecordingWriter.pads[0]?.isDown(PadState.QAM) == true)
assertTrue(activity.dispatchKeyEvent(event(false)))
assertEquals(listOf(28 to true, 28 to false), events)
}
@Test fun anUnmappedBackKeyStillHoldsAndReleasesQam() {
assertTrue(activity.dispatchKeyEvent(event(true)))
advance(700)
assertTrue(JoyConPadTest.RecordingWriter.pads[0]!!.isDown(PadState.QAM))
assertTrue(activity.dispatchKeyEvent(event(false)))
advance(1000)
assertFalse(JoyConPadTest.RecordingWriter.pads[0]!!.isDown(PadState.QAM))
assertTrue(events.isEmpty())
}
@Test fun capturedProfileBindingTakesPrecedenceOverGlobalShortcut() {
assignMenuShortcut()
bindings.configure(listOf(PhysicalInputBinding(PhysicalInputKey.capture(event(true))!!, InputAction.Keys(listOf(28)))))
assertTrue(activity.dispatchKeyEvent(event(true)))
assertTrue(activity.dispatchKeyEvent(event(false)))
assertEquals(listOf(28 to true, 28 to false), events)
assertFalse(drawerOpen())
}
@Test fun globalShortcutOverridesDefaultBackQamAndConsumesReleaseAcrossMenuChange() {
assignMenuShortcut()
assertTrue(activity.dispatchKeyEvent(event(true)))
assertTrue(drawerOpen())
advance(700)
assertFalse(JoyConPadTest.RecordingWriter.pads[0]?.isDown(PadState.QAM) == true)
assertTrue(activity.dispatchKeyEvent(event(false)))
assertTrue(drawerOpen())
assertTrue(activity.dispatchKeyEvent(event(true)))
assertFalse(drawerOpen())
assertTrue(activity.dispatchKeyEvent(event(false)))
assertTrue(events.isEmpty())
}
@Test fun inputSettingsDoNotExecuteGlobalShortcuts() {
assignMenuShortcut()
ReflectionHelpers.getField<MutableState<Boolean>>(activity, "inputSettingsOpen\$delegate").value = true
activity.dispatchKeyEvent(event(true))
activity.dispatchKeyEvent(event(false))
assertFalse(drawerOpen())
assertTrue(events.isEmpty())
}
private fun assignMenuShortcut() {
ReflectionHelpers.getField<PhysicalShortcutRouter>(activity, "physicalShortcuts").bindings =
listOf(PhysicalShortcuts.Binding(PhysicalShortcuts.button(event(true))!!, PhysicalShortcuts.Action.DROIDDECK))
}
private fun drawerOpen(): Boolean =
ReflectionHelpers.getField<MutableState<Boolean>>(activity, "drawerOpenState\$delegate").value
private fun event(down: Boolean) = KeyEvent(0L, 0L, if (down) KeyEvent.ACTION_DOWN else KeyEvent.ACTION_UP,
KeyEvent.KEYCODE_BACK, 0, 0, 42, 158, 0, InputDevice.SOURCE_KEYBOARD)
private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
}
@@ -0,0 +1,302 @@
package com.droiddeck.launcher.input
import android.os.Looper
import android.view.SurfaceView
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.geometry.Offset
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.wayland.WaylandCompositor
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 org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
import java.util.Collections
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE, shadows = [SessionInputPointerTest.CompositorShadow::class, SessionInputPointerTest.WriterShadow::class])
class SessionInputPointerTest {
private lateinit var activity: SessionActivity
private lateinit var output: InputOutput
private var previousSize = SessionState.outputSize
private var previousMode = SessionState.mode
@Before fun setUp() {
activity = Robolectric.buildActivity(SessionActivity::class.java).get()
output = ReflectionHelpers.getField(activity, "inputOutput")
ReflectionHelpers.setField(activity, "surfaceView", SurfaceView(activity).apply { layout(0, 0, 1000, 600) })
SessionState.outputSize = 1600 to 900
SessionState.mode = SessionService.MODE_DESKTOP
InputProfiles.resetAll(activity)
InputProfiles.select(activity, InputProfile.DESKTOP)
refresh()
CompositorShadow.pointers.clear()
CompositorShadow.events.clear()
CompositorShadow.keys.clear()
WriterShadow.mouse.clear()
WriterShadow.beforeWheel = null
}
@After fun tearDown() {
shadowOf(Looper.getMainLooper()).idle()
SessionState.outputSize = previousSize
SessionState.mode = previousMode
}
@Test fun desktopMouseButtonsKeepTheVisibleCursorAndDeliverImmediately() {
state<Offset>("cursorPos").value = Offset(500f, 300f)
state<Boolean>("cursorVisible").value = true
output.button(272, true)
invoke("onPadInput")
output.button(272, false)
assertTrue(state<Boolean>("cursorVisible").value)
assertEquals(listOf(Triple(3, 272, 1), Triple(3, 272, 0)), CompositorShadow.events)
}
@Test fun nativeGameInputStillHidesCursor() {
InputProfiles.select(activity, InputProfile.GAME)
refresh()
state<Boolean>("cursorVisible").value = true
invoke("onPadInput")
assertFalse(state<Boolean>("cursorVisible").value)
}
@Test fun lowerScreenPointerBindingAlsoKeepsCursorVisible() {
InputProfiles.save(activity, InputProfile(InputProfile.GAME).withBinding(InputRole.SECONDARY, InputControl.RIGHT_PAD, InputAction.Pointer()))
InputProfiles.select(activity, InputProfile.GAME)
refresh()
state<Boolean>("cursorVisible").value = true
invoke("onPadInput")
assertTrue(state<Boolean>("cursorVisible").value)
}
@Test fun stickContinuesFromTrackpadPositionAndUpdatesVisibleAndGuestCoordinates() {
output.pointer(-400f, -225f)
output.pointer(160f, 90f)
invoke("onPadInput")
assertEquals(Offset(350f, 215.625f), state<Offset>("cursorPos").value)
assertTrue(state<Boolean>("cursorVisible").value)
assertEquals(Triple(1, InputSpace.x(350f, 1000), InputSpace.y(215.625f, 600)), CompositorShadow.pointers.last())
}
@Test fun firstStickMovementStartsAtCenterAndClampsToPictureBounds() {
output.pointer(160f, 90f)
assertEquals(Offset(600f, 356.25f), state<Offset>("cursorPos").value)
output.pointer(10000f, -10000f)
assertEquals(Offset(1000f, 18.75f), state<Offset>("cursorPos").value)
}
@Test fun stickFrameNotifiesCursorDrawingBeforeReturningToTheLooper() {
val position = state<Offset>("cursorPos")
Snapshot.sendApplyNotifications()
var changed = false
val observer = Snapshot.registerApplyObserver { objects, _ ->
if (position in objects) changed = true
}
try {
output.pointer(20f, 10f)
assertTrue(changed)
} finally { observer.dispose() }
}
@Test fun pointerLockKeepsRelativeMotionAndHiddenCursor() {
ReflectionHelpers.setField(activity, "pointerLocked", true)
state<Boolean>("cursorVisible").value = true
output.pointer(2.5f, -1.25f)
assertEquals(listOf(Triple(6, 640, -320)), CompositorShadow.events)
assertTrue(CompositorShadow.pointers.isEmpty())
assertFalse(state<Boolean>("cursorVisible").value)
}
@Test fun clientRequestedHiddenCursorStaysHidden() {
ReflectionHelpers.setField(activity, "clientHidesCursor", true)
output.pointer(1f, 1f)
assertFalse(state<Boolean>("cursorVisible").value)
}
@Test fun mappedPointerStaysVisibleWithDirectTouchSelected() {
ReflectionHelpers.setField(activity, "routedTouchMode", com.droiddeck.launcher.session.SessionPrefs.TOUCH_DIRECT)
state<Boolean>("directCursorOn").value = false
output.pointer(20f, 10f)
assertTrue(state<Boolean>("cursorVisible").value)
}
@Test fun touchpadZoomDoesNotReleaseCtrlHeldByTheProfileOrScreenKeys() {
val held = ReflectionHelpers.getField<HeldInput>(activity, "heldKeys")
output.key(29, true)
held.set(64, 29, true)
ReflectionHelpers.getField<PointerGestures.Listener>(activity, "pointerListener").onZoom(1)
assertEquals(listOf(29 to 1), CompositorShadow.keys)
output.key(29, false)
assertEquals(listOf(29 to 1), CompositorShadow.keys)
held.set(64, 29, false)
assertEquals(listOf(29 to 1, 29 to 0), CompositorShadow.keys)
assertEquals(listOf(Triple(4, 1, 0)), CompositorShadow.events)
}
@Test fun desktopRightCtrlUsesUpstreamAliasWithoutReleasingTheProfileHold() {
fun hardwareCtrl(down: Boolean) = ReflectionHelpers.callInstanceMethod<Unit>(activity, "sendGuestKey",
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 97),
ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, down),
ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 8))
output.key(29, true)
hardwareCtrl(true)
hardwareCtrl(false)
assertEquals(listOf(29 to 1), CompositorShadow.keys)
output.key(29, false)
assertEquals(listOf(29 to 1, 29 to 0), CompositorShadow.keys)
}
@Test fun routedMouseUsesRawBackendAndKeepsSharedButtonOwnership() {
ReflectionHelpers.setField(activity, "mouseWriter", FakeInputWriter(activity.cacheDir.path, FakeInputWriter.MOUSE_SLOT))
ReflectionHelpers.setField(activity, "evdevMouseActive", true)
ReflectionHelpers.setField(activity, "pointerLocked", true)
val held = ReflectionHelpers.getField<HeldInput>(activity, "heldButtons")
output.button(272, true)
held.set(2, 272, true)
output.button(272, false)
assertEquals(listOf("button:272:true"), WriterShadow.mouse)
held.set(2, 272, false)
output.pointer(2.5f, -1.25f)
output.scroll(2)
assertEquals(listOf("button:272:true", "button:272:false", "delta:2.5:-1.25", "wheel:-2:0:120"), WriterShadow.mouse)
assertTrue(CompositorShadow.events.isEmpty())
}
@Test fun focusCleanupReleasesHardwareAndKeyboardKeysWithoutReleasingAnotherOwner() {
val held = ReflectionHelpers.getField<HeldInput>(activity, "heldKeys")
output.key(29, true)
for ((owner, code) in listOf(8 to 30, 16 to 31, 32 to 32, 16 to 29)) held.set(owner, code, true)
ReflectionHelpers.callInstanceMethod<Unit>(activity, "releaseHeldGuestInput")
assertEquals(setOf(30 to 0, 31 to 0, 32 to 0), CompositorShadow.keys.filter { it.second == 0 }.toSet())
output.key(29, false)
assertEquals(29 to 0, CompositorShadow.keys.last())
}
@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)
output.button(272, true)
invoke("closeEvdevMouse")
output.button(272, false)
assertEquals(listOf("button:272:true", "button:272:false", "release"), WriterShadow.mouse)
assertTrue(CompositorShadow.events.isEmpty())
output.button(272, true)
output.button(272, false)
assertEquals(listOf(Triple(3, 272, 1), Triple(3, 272, 0)), CompositorShadow.events)
}
@Test fun wowFieldSelectionPreservesCtrlHeldByTheInputProfile() {
output.key(29, true)
ReflectionHelpers.callInstanceMethod<Unit>(activity, "selectGameField",
ReflectionHelpers.ClassParameter.from(IntArray::class.java, intArrayOf(46)))
assertEquals(listOf(29 to 1, 30 to 1, 30 to 0, 46 to 1, 46 to 0), CompositorShadow.keys)
output.key(29, false)
assertEquals(29 to 0, CompositorShadow.keys.last())
}
@Test fun horizontalWheelFinishesBeforeRawMouseDestruction() {
checkWheelTransition(horizontal = true, transition = "releaseEvdevMouse", marker = "destroy")
}
@Test fun verticalWheelFinishesBeforeRawMouseSoftRelease() {
checkWheelTransition(horizontal = false, transition = "closeEvdevMouse", marker = "release")
}
private fun checkWheelTransition(horizontal: Boolean, transition: String, marker: String) {
ReflectionHelpers.setField(activity, "mouseWriter", FakeInputWriter(activity.cacheDir.path, FakeInputWriter.MOUSE_SLOT))
ReflectionHelpers.setField(activity, "evdevMouseActive", true)
val entered = CountDownLatch(1)
val continueWrite = CountDownLatch(1)
val transitioning = CountDownLatch(1)
val finished = CountDownLatch(1)
WriterShadow.beforeWheel = {
entered.countDown()
check(continueWrite.await(5, TimeUnit.SECONDS))
}
val executor = Executors.newFixedThreadPool(2)
fun scroll() { if (horizontal) output.scrollHorizontal(2) else output.scroll(2) }
try {
val writing = executor.submit { scroll() }
assertTrue(entered.await(5, TimeUnit.SECONDS))
val closing = executor.submit {
transitioning.countDown()
invoke(transition)
finished.countDown()
}
assertTrue(transitioning.await(5, TimeUnit.SECONDS))
assertFalse(finished.await(100, TimeUnit.MILLISECONDS))
continueWrite.countDown()
writing.get(5, TimeUnit.SECONDS)
closing.get(5, TimeUnit.SECONDS)
assertEquals(listOf(if (horizontal) "wheel:0:2:120" else "wheel:-2:0:120", marker), WriterShadow.mouse)
scroll()
assertEquals(2, WriterShadow.mouse.size)
assertEquals(listOf(if (horizontal) Triple(11, 0, 240) else Triple(4, 2, 0)), CompositorShadow.events)
} finally {
continueWrite.countDown()
executor.shutdownNow()
executor.awaitTermination(5, TimeUnit.SECONDS)
WriterShadow.beforeWheel = null
}
}
private fun refresh() = invoke("refreshInputProfile")
private fun invoke(name: String) = ReflectionHelpers.callInstanceMethod<Unit>(activity, name)
private fun <T> state(name: String): MutableState<T> = ReflectionHelpers.getField(activity, "$name\$delegate")
@Implements(value = WaylandCompositor::class, isInAndroidSdk = false)
class CompositorShadow {
companion object {
val pointers = mutableListOf<Triple<Int, Int, Int>>()
val events = mutableListOf<Triple<Int, Int, Int>>()
val keys = mutableListOf<Pair<Int, Int>>()
@JvmStatic @Implementation fun __staticInitializer__() {}
@JvmStatic @Implementation fun nativeSendPointer(action: Int, x: Int, y: Int) { pointers += Triple(action, x, y) }
@JvmStatic @Implementation fun nativeSendSceneInput(type: Int, code: Int, value: Int) { events += Triple(type, code, value) }
@JvmStatic @Implementation fun nativeSendKey(code: Int, value: Int) { keys += code to value }
}
}
@Implements(value = FakeInputWriter::class, isInAndroidSdk = false)
class WriterShadow {
@Implementation fun writeMouseButton(code: Short, down: Boolean) { mouse += "button:$code:$down" }
@Implementation fun writeMouseDelta(dx: Float, dy: Float) { mouse += "delta:$dx:$dy" }
@Implementation fun writeMouseWheel(vertical: Int, horizontal: Int, value120: Int) {
beforeWheel?.invoke()
mouse += "wheel:$vertical:$horizontal:$value120"
}
@Implementation fun softRelease() { mouse += "release" }
@Implementation fun destroy() { mouse += "destroy" }
companion object {
val mouse: MutableList<String> = Collections.synchronizedList(mutableListOf())
@Volatile var beforeWheel: (() -> Unit)? = null
@JvmStatic @Implementation fun __staticInitializer__() {}
@JvmStatic @Implementation fun writeDeckControls(index: Int, mask: Int, pads: ShortArray, pressure: ShortArray) {}
}
}
}
@@ -0,0 +1,90 @@
package com.droiddeck.launcher.input
import android.os.Handler
import android.os.Looper
import com.droiddeck.launcher.SessionActivity
import java.io.File
import java.time.Duration
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
import org.robolectric.util.ReflectionHelpers
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class])
@LooperMode(LooperMode.Mode.PAUSED)
class SessionSystemInputTest {
private val bridge = PadBridge(File(RuntimeEnvironment.getApplication().cacheDir, "system-input"))
private val activity = Robolectric.buildActivity(SessionActivity::class.java).get().also {
ReflectionHelpers.setField(it, "padBridge", bridge)
}
private val output = RecordingOutput()
private val router = InputRouter(output).also {
bridge.setInputRouter(it)
bridge.setInputProfile(InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PRIMARY, InputControl.GUIDE, InputAction.Disabled)
.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.Keys(listOf(29)))
.withBinding(InputRole.PRIMARY, InputControl.R3, InputAction.Command(InputCommand.MENU)))
}
@After fun close() { bridge.stop(); advance(500) }
@Test fun steamMenuBypassesPrimaryBindingsAndDisabledRouting() {
bridge.setInputEnabled(false)
invoke("sendSteamGuide")
assertTrue(state().isDown(PadState.GUIDE))
advance(90)
assertFalse(state().isDown(PadState.GUIDE))
assertTrue(output.events.isEmpty())
}
@Test fun vrStickSwitchBypassesPrimaryBindingsAndPreservesPhysicalHold() {
bridge.applyExternal({ it.press(PadState.L3, true) }, true)
invoke("switchVrSticks")
assertTrue(state().isDown(PadState.L3))
assertTrue(state().isDown(PadState.R3))
advance(120)
assertTrue(state().isDown(PadState.L3))
assertFalse(state().isDown(PadState.R3))
assertTrue(output.events.isEmpty())
}
@Test fun releasingSystemActionsCancelsOldVrReleaseWithoutEndingNewTap() {
invoke("switchVrSticks")
advance(60)
bridge.releaseAll()
assertFalse(state().isDown(PadState.L3))
assertFalse(state().isDown(PadState.R3))
invoke("switchVrSticks")
advance(60)
assertTrue(state().isDown(PadState.L3))
assertTrue(state().isDown(PadState.R3))
advance(60)
assertFalse(state().isDown(PadState.L3))
assertFalse(state().isDown(PadState.R3))
}
private fun state() = JoyConPadTest.RecordingWriter.pads[0]!!
private fun invoke(name: String) = ReflectionHelpers.callInstanceMethod<Unit>(activity, name)
private fun advance(ms: Long) {
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms))
shadowOf(ReflectionHelpers.getStaticField<Handler>(PadBridge::class.java, "chordHandler").looper).idle()
}
private class RecordingOutput : InputOutput {
val events = mutableListOf<String>()
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() { events += "motion" }
}
}
@@ -0,0 +1,177 @@
package com.droiddeck.launcher.input
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.os.Handler
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.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.Implementation
import org.robolectric.annotation.Implements
import org.robolectric.util.ReflectionHelpers
import org.robolectric.shadows.ShadowBluetoothGatt
import java.util.UUID
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [SteamControllerBleTest.Writer::class])
class SteamControllerBleTest {
private val keys = ArrayList<Pair<Int, Boolean>>()
private val router = InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) { keys += code to 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() {}
})
private lateinit var controller: SteamControllerBle
private lateinit var handler: Handler
@Before fun setUp() {
Writer.reports.clear()
Writer.connections.clear()
Writer.features = 0
router.setProfile(InputProfile.defaults(InputProfile.GAME)
.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Keys(listOf(57))))
controller = SteamControllerBle(RuntimeEnvironment.getApplication(), router)
handler = ReflectionHelpers.getField(controller, "handler")
shadowOf(handler.looper).pause()
controller.start()
}
@After fun close() {
controller.stop()
handler.looper.quit()
}
@Test fun stopReleasesAndDetachesInputBeforeQueuedCallbacksCanPublish() {
state(ByteArray(45).apply { this[1] = 1 })
assertEquals(listOf(57 to true), keys)
handler.post { state(ByteArray(45).apply { this[1] = 1 }) }
controller.stop()
assertEquals(listOf(57 to true, 57 to false), keys)
assertNull(ReflectionHelpers.getField<Any?>(controller, "routedInput"))
assertTrue(Writer.reports.last().all { it == 0.toByte() })
val reports = Writer.reports.size
val connections = Writer.connections.toList()
shadowOf(handler.looper).idle()
state(ByteArray(45))
state(ByteArray(45).apply { this[1] = 1 })
ReflectionHelpers.callInstanceMethod<Unit>(controller, "release")
ReflectionHelpers.setField(controller, "featureRead", 7L)
ReflectionHelpers.callInstanceMethod<Unit>(controller, "onFeatureRead", ReflectionHelpers.ClassParameter.from(ByteArray::class.java, ByteArray(2)))
controller.stop()
assertEquals(reports, Writer.reports.size)
assertEquals(connections, Writer.connections)
assertEquals(0, Writer.features)
assertEquals(listOf(57 to true, 57 to false), keys)
}
@Test fun stoppingBeforeQueuedStartPreservesAnotherSourcesHeldKey() {
val other = router.channel(InputRole.PRIMARY, InputControl.B, InputAction.Keys(listOf(57)))
other.update(1f)
state(ByteArray(45).apply { this[1] = 1 })
controller.start()
controller.stop()
shadowOf(handler.looper).idle()
assertFalse(ReflectionHelpers.getField<Boolean>(controller, "running"))
assertEquals(listOf(57 to true), keys)
other.close()
assertEquals(listOf(57 to true, 57 to false), keys)
}
@Test fun staleControllerCannotClearOrPublishIntoItsReplacementsSlot() {
state(ByteArray(45).apply { this[1] = 1 })
assertEquals(listOf(57 to true), keys)
val replacement = SteamControllerBle(RuntimeEnvironment.getApplication())
val replacementHandler = ReflectionHelpers.getField<Handler>(replacement, "handler")
shadowOf(replacementHandler.looper).pause()
try {
replacement.start()
subscribe(replacement)
val report = ByteArray(45).apply { this[1] = 2 }
state(report, replacement)
val reports = Writer.reports.size
val connections = Writer.connections.toList()
controller.start()
shadowOf(handler.looper).idle()
subscribe(controller)
state(ByteArray(45))
ReflectionHelpers.setField(controller, "featureRead", 7L)
ReflectionHelpers.callInstanceMethod<Unit>(controller, "onFeatureRead",
ReflectionHelpers.ClassParameter.from(ByteArray::class.java, ByteArray(2)))
ReflectionHelpers.callInstanceMethod<Unit>(controller, "disconnect",
ReflectionHelpers.ClassParameter.from(String::class.java, "old link lost"))
controller.stop()
shadowOf(handler.looper).idle()
assertTrue(SteamControllerBle.connected)
assertEquals(connections, Writer.connections)
assertEquals(reports, Writer.reports.size)
assertArrayEquals(report, Writer.reports.last())
assertEquals(0, Writer.features)
assertEquals(listOf(57 to true, 57 to false), keys)
assertNull(ReflectionHelpers.getField<Any?>(controller, "routedInput"))
replacement.stop()
assertFalse(SteamControllerBle.connected)
assertFalse(Writer.connections.last())
assertTrue(Writer.reports.last().all { it == 0.toByte() })
} finally {
replacement.stop()
replacementHandler.looper.quit()
}
}
@Test fun stoppingAnUnstartedControllerPreservesTheActiveSlot() {
subscribe(controller)
val unused = SteamControllerBle(RuntimeEnvironment.getApplication())
try {
val reports = Writer.reports.size
val connections = Writer.connections.toList()
unused.stop()
assertTrue(SteamControllerBle.connected)
assertEquals(connections, Writer.connections)
assertEquals(reports, Writer.reports.size)
} finally {
unused.stop()
ReflectionHelpers.getField<Handler>(unused, "handler").looper.quit()
}
}
private fun subscribe(target: SteamControllerBle) {
val device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("00:11:22:33:44:55")
val gatt = ShadowBluetoothGatt.newInstance(device)
val input = UUID.fromString("100F6C7A-1735-4313-B402-38567131E5F3")
val characteristic = BluetoothGattCharacteristic(input, BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0)
val descriptor = BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"), 0)
characteristic.addDescriptor(descriptor)
ReflectionHelpers.setField(target, "gatt", gatt)
ReflectionHelpers.setField(target, "input", input)
ReflectionHelpers.setField(target, "reportId", 0x45)
ReflectionHelpers.getField<BluetoothGattCallback>(target, "callback")
.onDescriptorWrite(gatt, descriptor, BluetoothGatt.GATT_SUCCESS)
}
private fun state(bytes: ByteArray, target: SteamControllerBle = controller) = ReflectionHelpers.callInstanceMethod<Unit>(target, "onState",
ReflectionHelpers.ClassParameter.from(ByteArray::class.java, bytes))
@Implements(FakeInputWriter::class)
class Writer {
companion object {
val reports = ArrayList<ByteArray>()
val connections = ArrayList<Boolean>()
var features = 0
@JvmStatic @Implementation fun writeTritonState(slot: Int, reportId: Int, report: ByteArray) { reports += report.copyOf() }
@JvmStatic @Implementation fun setTritonConnected(slot: Int, connected: Boolean) { connections += connected }
@JvmStatic @Implementation fun writeTritonFeatureReply(slot: Int, request: Long, report: ByteArray?) { features++ }
}
}
}
@@ -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() }
}
}
}
@@ -0,0 +1,47 @@
package com.droiddeck.launcher.input
import org.junit.Assert.*
import org.junit.Test
class TritonInputRouterTest {
private val events = ArrayList<String>()
private val router = InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) { events += "$code $down" }
override fun button(code: Int, down: Boolean) {}
override fun pointer(dx: Float, dy: Float) {}
override fun scroll(steps: Int) {}
override fun command(command: InputCommand) {}
override fun requestMotion() {}
})
@Test fun nativeReportIsPassedThroughWithoutCopyingOrReencoding() {
val adapter = TritonInputRouter(router)
val bytes = ByteArray(64) { (it * 11).toByte() }
assertSame(bytes, adapter.route(bytes))
assertTrue(events.isEmpty())
adapter.close()
}
@Test fun consumedButtonDoesNotChangeOtherBitsAxesPressureMotionOrExtension() {
router.setProfile(InputProfile.defaults(InputProfile.GAME).withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Keys(listOf(57))))
val adapter = TritonInputRouter(router)
val bytes = ByteArray(64) { (it * 7).toByte() }
bytes[1] = (bytes[1].toInt() or 1).toByte()
val expected = bytes.copyOf().apply { this[1] = (this[1].toInt() and 1.inv()).toByte() }
assertArrayEquals(expected, adapter.route(bytes))
assertEquals(listOf("57 true"), events)
adapter.release()
assertEquals(listOf("57 true", "57 false"), events)
}
@Test fun switchingProfileWhileNativeButtonHeldRequiresRelease() {
val adapter = TritonInputRouter(router)
val held = ByteArray(45).apply { this[1] = 1 }
adapter.route(held)
router.setProfile(InputProfile.defaults(InputProfile.GAME).withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Keys(listOf(57))))
adapter.route(held)
assertTrue(events.isEmpty())
adapter.route(ByteArray(45)); adapter.route(held)
assertEquals(listOf("57 true"), events)
}
}
@@ -4,6 +4,12 @@ import android.content.Context
import com.droiddeck.launcher.core.AppUiPrefs
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.input.ControllerPrefs
import com.droiddeck.launcher.input.InputAction
import com.droiddeck.launcher.input.InputControl
import com.droiddeck.launcher.input.InputProfile
import com.droiddeck.launcher.input.InputProfiles
import com.droiddeck.launcher.input.InputRole
import com.droiddeck.launcher.input.InputSurfaceLayout
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
@@ -20,7 +26,7 @@ class SettingsResetTest {
private val session get() = prefs("session")
@Before fun clear() {
listOf("session", "controller", "app-ui", "frame_gen", "steam_touch", "agent").forEach {
listOf("session", "controller", "input-profiles", "input-surfaces", "app-ui", "frame_gen", "steam_touch", "agent").forEach {
prefs(it).edit().clear().commit()
}
}
@@ -119,6 +125,24 @@ class SettingsResetTest {
assertEquals("a:1,2", prefs("steam_touch").getString("copiedLayout", null))
}
@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)
.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.Disabled))
InputSurfaceLayout.save(app, InputProfile.DESKTOP, emptyList())
assertTrue(SettingsReset.resetAll(app, gameProfiles = false))
assertEquals(InputProfiles.AUTO, InputProfiles.selection(app))
assertEquals(defaultGame, InputProfiles.read(app, InputProfile.GAME))
assertEquals(defaultDesktop, InputProfiles.read(app, InputProfile.DESKTOP))
assertEquals(defaultSurface, InputSurfaceLayout.read(app, InputProfile.DESKTOP))
}
@Test fun gameTextureFilteringIsKeptUnlessGameProfilesAreReset() {
session.edit().putString("gameTextureFiltering", """{"440":{"anisotropy":16}}""").commit()
SettingsReset.resetAll(app, gameProfiles = false)
@@ -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
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.ui
import android.hardware.input.InputManager
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.*
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.PadBridgeRoutingTest
import com.droiddeck.launcher.input.PhysicalInputKey
import org.junit.Assert.*
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.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.shadows.InputDeviceBuilder
import org.robolectric.shadows.ShadowDialog
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], qualifiers = "w960dp-h640dp-land", shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
class InputCaptureDialogTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
private val open = mutableStateOf(true)
private var selected: PhysicalInputKey? = null
private lateinit var device: InputDevice
@Before fun setUp() {
device = InputDeviceBuilder.newBuilder().setId(10).setName("Thor buttons")
.setDescriptor("thor-extra").setSources(InputDevice.SOURCE_KEYBOARD)
.setKeyboardType(InputDevice.KEYBOARD_TYPE_ALPHABETIC)
.setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)).build()
shadowOf(context.getSystemService(InputManager::class.java)).addInputDevice(device)
compose.setContent { DroidDeckTheme {
if (open.value) InputCaptureDialog({ open.value = false }) { selected = it; open.value = false }
} }
}
@Test fun physicalBackCanBeCapturedAndConfirmedWithControllerA() {
send(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_DOWN)
compose.onNodeWithText(context.getString(R.string.ctrl_edit)).assertIsNotEnabled()
assertTrue(open.value)
send(KeyEvent.KEYCODE_BACK, KeyEvent.ACTION_UP)
compose.onNodeWithText(context.getString(R.string.ctrl_edit)).assertIsEnabled()
assertNull(selected)
send(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN)
assertEquals(KeyEvent.KEYCODE_BACK, selected?.keyCode)
assertFalse(open.value)
}
@Test fun controllerBCanBeCapturedAndAnotherPressCancelsWithoutSaving() {
send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_DOWN)
send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_UP)
assertTrue(open.value)
send(KeyEvent.KEYCODE_BUTTON_B, KeyEvent.ACTION_DOWN)
assertFalse(open.value)
assertNull(selected)
}
@Test fun retryAllowsAnotherButtonAndConsumesItsReleaseBeforeConfirmation() {
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_DOWN)
send(KeyEvent.KEYCODE_F1, KeyEvent.ACTION_UP)
compose.onNodeWithText(context.getString(R.string.input_capture_retry)).performClick()
send(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN)
send(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_UP)
assertNull(selected)
assertTrue(open.value)
send(KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN)
assertEquals(KeyEvent.KEYCODE_BUTTON_A, selected?.keyCode)
}
private fun send(code: Int, action: Int) {
compose.runOnIdle {
assertTrue(ShadowDialog.getLatestDialog().window!!.callback.dispatchKeyEvent(
KeyEvent(100L, 100L, action, code, 0, 0, device.id, 700, 0, InputDevice.SOURCE_KEYBOARD)))
}
compose.waitForIdle()
}
}
@@ -0,0 +1,382 @@
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
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
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w1000dp-h900dp")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class InputSettingsTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit()
context.getSharedPreferences("input-surfaces", Context.MODE_PRIVATE).edit().clear().commit()
context.getSharedPreferences("controller", Context.MODE_PRIVATE).edit().clear().commit()
}
@Test fun commandSymbolsAreSelectableForAnyCustomButton() {
val element = mutableStateOf(InputSurfaceElement(InputControl.A, .1f, .1f, .2f, .2f, name = "Custom button"))
compose.setContent { DroidDeckTheme {
androidx.compose.foundation.layout.Column { InputElementProperties(element.value) { element.value = it } }
} }
var current = context.getString(R.string.input_button_text)
for (code in listOf(InputButtonIcons.MENU, InputButtonIcons.KEYBOARD, InputButtonIcons.STEAM, InputButtonIcons.QUICK_ACCESS)) {
compose.onNodeWithText(current).performClick()
current = InputButtonIcons.label(context, code)
compose.onNodeWithText(current).performScrollTo().performClick()
compose.runOnIdle { assertEquals(code, element.value.icon) }
}
}
@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("Deck grips + trackpads").performScrollTo().performClick()
compose.runOnIdle {
val changed = InputLibraries.read(context)
assertEquals(InputStockLayouts.DECK, changed.activePart(true, InputRole.SECONDARY).bindings)
assertEquals(original.profiles, changed.profiles)
assertEquals(original.compileActive(false), changed.compileActive(false))
}
compose.onNodeWithText(context.getString(R.string.input_save_combination)).performClick()
compose.onNode(hasSetTextAction()).performTextInput("Reading")
compose.onNodeWithText(context.getString(R.string.gesture_save_changes)).performClick()
compose.runOnIdle {
val saved = InputLibraries.read(context)
assertEquals("Reading", saved.profile(saved.activeId(true)).name)
assertTrue(saved.selection(true).parts.isEmpty())
assertEquals(original.profile("desktop"), saved.profile("desktop"))
}
}
@Test fun actionDraftSurvivesRouteAndTypeChanges() {
var saved: InputAction? = null
compose.setContent { DroidDeckTheme { InputActionEditor(InputControl.RS, InputAction.Scroll(27f, true), "Right stick", {}, { saved = it }) } }
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)
assertEquals(InputAction.Disabled, profile.action(InputRole.PHYSICAL, InputControl.A))
assertEquals(InputAction.Native(), profile.action(InputRole.SECONDARY, InputControl.A))
}
}
@Test fun addingCreatesAnUnassignedElementAtTheCanvasCenterWithoutAnotherTouch() {
var changed = false
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)
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 unavailableDisplayDismissesSettingsWithoutCrashing() {
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)
ShadowDisplayManager.removeDisplay(displayId)
val open = mutableStateOf(true)
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({}) }
} }
compose.runOnIdle {
assertFalse(open.value)
assertTrue(ShadowDialog.getShownDialogs().none { it.isShowing })
}
}
@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)))
}
}
@@ -0,0 +1,148 @@
package com.droiddeck.launcher.ui
import androidx.activity.ComponentActivity
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import com.droiddeck.launcher.input.JoyConPadTest
import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import java.io.File
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], shadows = [JoyConPadTest.RecordingWriter::class])
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: InputSurfaceView
private val previousDeckPad = SessionState.deckPad
@Before fun setUp() {
SessionState.deckPad = true
DeckControls.releaseAll()
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 = InputSurfaceView(activity, bridge, elements)
root.addView(panel)
val trackpad = child("TrackpadView")
trackpad.layout(0, 0, 300, 300)
touch(trackpad, MotionEvent.ACTION_DOWN, 200f, 100f)
touch(trackpad, MotionEvent.ACTION_POINTER_DOWN or (1 shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), 200f, 100f, fingers = 2)
assertEquals(32 or 128, JoyConPadTest.RecordingWriter.grips)
}
@After fun close() {
root.removeAllViews()
bridge.stop()
DeckControls.releaseAll()
controller.pause().stop().destroy()
SessionState.deckPad = previousDeckPad
}
@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()
(stick.parent as ViewGroup).removeView(stick)
assertEquals(0f, state().leftX)
assertTrackpadStillHeld(position)
root.removeView(panel)
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
}
@Test fun removingDirectionPadReleasesOnlyItsOwnInput() {
val dpad = child("DirectionPad")
dpad.layout(0, 0, 300, 300)
touch(dpad, MotionEvent.ACTION_DOWN, 150f, 30f)
assertTrue(state().up)
val position = JoyConPadTest.RecordingWriter.deckPads.copyOf()
(dpad.parent as ViewGroup).removeView(dpad)
assertFalse(state().up)
assertTrackpadStillHeld(position)
}
@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))
val position = JoyConPadTest.RecordingWriter.deckPads.copyOf()
(buttons.parent as ViewGroup).removeView(buttons)
assertFalse(state().isDown(PadState.A))
assertTrackpadStillHeld(position)
}
@Test fun replacingTheLayoutReleasesEveryOldControl() {
holdFaceButton()
assertTrue(state().isDown(PadState.A))
panel.updateCustomLayout(emptyList())
assertFalse(state().isDown(PadState.A))
assertEquals(0, JoyConPadTest.RecordingWriter.grips)
bridge.applyExternal({ it.press(PadState.B, true) }, true)
assertTrue(state().isDown(PadState.B))
assertFalse(state().isDown(PadState.A))
}
@Test fun removingThePanelLeavesNoTouchSourceForLaterPhysicalInput() {
holdFaceButton()
root.removeView(panel)
assertFalse(state().isDown(PadState.A))
bridge.applyExternal({ it.press(PadState.B, true) }, true)
assertTrue(state().isDown(PadState.B))
}
private fun holdFaceButton() {
val buttons = child("HoldButton")
buttons.layout(0, 0, 300, 300)
touch(buttons, MotionEvent.ACTION_DOWN, 150f, 240f)
}
private fun assertTrackpadStillHeld(position: ShortArray) {
assertEquals(32 or 128, JoyConPadTest.RecordingWriter.grips)
assertArrayEquals(position, JoyConPadTest.RecordingWriter.deckPads)
}
private fun state() = JoyConPadTest.RecordingWriter.pads[0]!!
private fun child(name: String) = descendants(panel).first { it.javaClass.simpleName == name }
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)))
}
private fun touch(view: View, action: Int, x: Float, y: Float, fingers: Int = 1) {
val properties = Array(fingers) { i -> MotionEvent.PointerProperties().apply { id = i; toolType = MotionEvent.TOOL_TYPE_FINGER } }
val coords = Array(fingers) { MotionEvent.PointerCoords().apply { this.x = x; this.y = y; pressure = 1f; size = 1f } }
val event = MotionEvent.obtain(1000, 1010, action, fingers, properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0)
try { assertTrue(view.onTouchEvent(event)) } finally { event.recycle() }
}
}
@@ -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()
}
}
}
@@ -66,10 +66,11 @@ class PhysicalShortcutsDialogTest {
}
}
@Test fun buttonMappingPageOpensPhysicalShortcutAssignments() {
@Test fun inputSettingsPageOpensPhysicalShortcutAssignments() {
compose.setContent {
DroidDeckTheme { ControllerMappingPage(emptyMap(), { _, _ -> }, {}, {}) }
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()
}
@@ -5,12 +5,14 @@ import android.hardware.input.InputManager
import android.view.Display
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.compose.ui.test.*
import androidx.compose.ui.semantics.SemanticsProperties.StateDescription
import androidx.compose.runtime.MutableState
import androidx.compose.ui.geometry.Offset
import com.droiddeck.launcher.R
import com.droiddeck.launcher.SessionActivity
import com.droiddeck.launcher.gpu.FrameGen
@@ -21,6 +23,14 @@ import com.droiddeck.launcher.input.PadBridgeRoutingTest
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import org.junit.After
import com.droiddeck.launcher.input.InputLibraries
import com.droiddeck.launcher.input.InputRole
import com.droiddeck.launcher.input.InputElementKind
import com.droiddeck.launcher.input.InputSurfaceElement
import com.droiddeck.launcher.input.InputSurfaceStyle
import com.droiddeck.launcher.input.InputControl
import org.junit.Assert.assertSame
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
@@ -61,6 +71,28 @@ class SessionSecondScreenTest {
@Test fun steamMenuKeepsTheExistingTrackpadAndTerminal() = checkModes(steam = true)
@Test fun desktopQuickMenuChangesTheRunningDesktopLayout() = checkQuickSelection(steam = false, desktop = true, direct = true)
@Test fun steamQuickMenuLeavesTheDesktopSelectionAlone() = checkQuickSelection(steam = true, desktop = false, direct = false)
@Test fun directGameQuickMenuLeavesTheDesktopSelectionAlone() = checkQuickSelection(steam = false, desktop = false, direct = true)
@Test fun closingTheDockedDrawerKeepsTheSelectedControlsPanel() {
SessionState.mode = SessionService.MODE_STEAM
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
@@ -104,7 +136,7 @@ class SessionSecondScreenTest {
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)
@@ -123,6 +155,74 @@ class SessionSecondScreenTest {
}
}
@Test fun profileRefreshLeavesTerminalAndDashboardIntact() {
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val panel = SecondScreenPresentation(activity, display, {}, {}, {}, dashboard = { androidx.compose.material3.Text("Dashboard") })
try {
panel.show()
for (mode in listOf(SecondScreenMode.TERMINAL, SecondScreenMode.DASHBOARD)) {
panel.showMode(mode)
val root = panel.window!!.decorView
val before = descendants(root).toList()
val terminal: Any? = ReflectionHelpers.getField(panel, "terminalPanel")
panel.refreshControls()
assertEquals(before, descendants(root).toList())
assertSame(terminal, ReflectionHelpers.getField<Any?>(panel, "terminalPanel"))
}
} finally { panel.closeControls() }
}
@Test fun profileRefreshUpdatesControlsWithoutClosingTheFieldKeyboard() {
SessionState.mode = SessionService.MODE_STEAM
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
var closed = 0
val panel = SecondScreenPresentation(activity, display, {}, {}, {}, onKeyboardClosed = { closed++ })
try {
panel.show()
panel.showMode(SecondScreenMode.CUSTOM_CONTROLS)
panel.requestKeyboard(forField = true)
val host: Any = ReflectionHelpers.getField(panel, "keyboardHost")
val shown: MutableState<Boolean> = ReflectionHelpers.getField(panel, "keyboardShown")
shown.value = true
ReflectionHelpers.setField(panel, "imeSeen", true)
val controls = descendants(panel.window!!.decorView).filterIsInstance<InputSurfaceView>().single()
val element = InputSurfaceElement(InputControl.A, .3f, .2f, .2f, .2f, "updated")
InputLibraries.update(activity) { library ->
val layout = library.activeLayout(false, InputRole.SECONDARY)!!
library.withLayout(layout.copy(elements = listOf(element), style = InputSurfaceStyle(opacity = 35)))
}
panel.refreshControls()
assertSame(controls, descendants(panel.window!!.decorView).filterIsInstance<InputSurfaceView>().single())
val child = descendants(controls).single { it.tag == element }
assertEquals(.35f, child.alpha, .001f)
assertSame(host, ReflectionHelpers.getField<Any>(panel, "keyboardHost"))
assertTrue(panel.fieldKeyboardOpen)
assertTrue(shown.value)
assertTrue(ReflectionHelpers.getField<Boolean>(panel, "imeSeen"))
assertEquals(0, closed)
} finally { panel.closeControls() }
}
@Test fun profileRefreshPreservesTheLowerScreenChatPanel() {
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
var lost = 0
val panel = SecondScreenPresentation(activity, display, {}, {}, {})
try {
panel.show()
panel.showMode(SecondScreenMode.CUSTOM_CONTROLS)
panel.showChat(onLost = { lost++ }) { androidx.compose.material3.Text("Chat draft") }
val chat: View? = ReflectionHelpers.getField(panel, "chatView")
assertNotNull(chat)
panel.refreshControls()
assertSame(chat, ReflectionHelpers.getField<View?>(panel, "chatView"))
assertTrue(descendants(panel.window!!.decorView).any { it === chat })
assertEquals(0, lost)
} finally { panel.closeControls() }
}
@Test
@Config(sdk = [34], shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class])
fun controllerBumpersReachTheSecondScreenInBothSessionModes() {
@@ -208,6 +308,43 @@ class SessionSecondScreenTest {
compose.onNodeWithText(context.getString(R.string.mode_mic)).assertDoesNotExist()
}
private fun checkQuickSelection(steam: Boolean, desktop: Boolean, direct: Boolean) {
SessionState.mode = if (desktop) SessionService.MODE_DESKTOP else if (steam) SessionService.MODE_STEAM else SessionService.MODE_RUN
val original = InputLibraries.update(context) { it.chooseLayout("desktop", InputRole.SECONDARY, InputLibraries.DECK) }
val activity = Robolectric.buildActivity(SessionActivity::class.java).get()
val display = activity.getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
val panel = SecondScreenPresentation(activity, display, {}, {}, {})
val open = androidx.compose.runtime.mutableStateOf(true)
try {
panel.show()
panel.showMode(SecondScreenMode.CUSTOM_CONTROLS)
compose.setContent {
DroidDeckTheme {
SessionDrawer(open.value, SessionDrawerPage.CONTROLLER, false, {},
actions(steam, emptyList(), desktop = desktop, direct = direct,
onInputSelection = { panel.refreshControls() }, onClose = { open.value = false }))
}
}
compose.onNodeWithTag("setting-input-profile").performScrollTo().performClick()
compose.onNodeWithText("Desktop").performScrollTo().performClick()
compose.onNodeWithTag("input-profile-expand").performScrollTo().performClick()
compose.onNodeWithTag("setting-input-part-SECONDARY").performScrollTo().performClick()
compose.onNodeWithText("Trackpad + keyboard").performScrollTo().performClick()
compose.onNode(hasContentDescription(context.getString(R.string.common_close)) and
SemanticsMatcher.expectValue(androidx.compose.ui.semantics.SemanticsProperties.Role, androidx.compose.ui.semantics.Role.Button)).performClick()
compose.runOnIdle {
val updated = InputLibraries.read(context)
assertEquals("desktop", updated.selection(desktop).profile)
assertEquals(InputLibraries.TRACKPAD, updated.activeLayout(desktop, InputRole.SECONDARY)?.id)
assertEquals(original.selection(!desktop), updated.selection(!desktop))
assertEquals(original.profiles, updated.profiles)
val controls = descendants(panel.window!!.decorView).filterIsInstance<InputSurfaceView>().single()
val pads = descendants(controls).mapNotNull { it.tag as? InputSurfaceElement }.filter { it.kind == InputElementKind.TRACKPAD }.toList()
assertEquals(1, pads.size)
}
} finally { panel.closeControls() }
}
private fun checkModes(steam: Boolean) {
SessionState.mode = if (steam) SessionService.MODE_STEAM else SessionService.MODE_DESKTOP
val selected = mutableListOf<SecondScreenMode>()
@@ -217,11 +354,12 @@ class SessionSecondScreenTest {
SessionDrawer(true, SessionDrawerPage.SECOND_SCREEN, false, {}, actions(steam, displays) { selected += it })
}
}
for (mode in listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL)) {
val modes = listOf(SecondScreenMode.CUSTOM_CONTROLS, SecondScreenMode.TERMINAL)
for (mode in modes) {
compose.onNodeWithText(context.getString(mode.label)).performScrollTo().assertIsDisplayed().performClick()
}
compose.onNodeWithText(context.getString(SecondScreenMode.DECK_CONTROLS.label)).assertDoesNotExist()
assertEquals(listOf(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL), selected)
assertEquals(modes, selected)
}
private fun descendants(view: View): Sequence<View> = sequence {
@@ -231,8 +369,11 @@ class SessionSecondScreenTest {
private fun actions(steam: Boolean, displays: List<SecondScreenDisplay>,
micAvailable: Boolean = false, micEnabled: Boolean = false, onMic: (Boolean) -> Unit = {},
desktop: Boolean = !steam, direct: Boolean = false, onInputSelection: (InputRole?) -> Unit = {},
onClose: () -> Unit = {},
select: (SecondScreenMode) -> Unit = {}) =
DrawerActions(steam = steam, isHomeApp = false, androidApps = emptyList(), hudOn = false,
DrawerActions(steam = steam, desktop = desktop, direct = direct, onInputSelection = onInputSelection,
isHomeApp = false, androidApps = emptyList(), hudOn = false,
micAvailable = micAvailable, micEnabled = micEnabled, onMicEnabled = onMic,
frameGen = FrameGen.Mode.OFF, lossless = Lossless.State.NONE, oscMode = "never",
onScreenButtonsVisible = false, suspendPolicy = "auto", backActionsInverted = false,
@@ -241,5 +382,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)
}