Merge upstream PC input and dual-screen updates

This commit is contained in:
Delete228 committed 2026-11-05 00:00:34 +03:00
commit 68b0396dfe
819 files changed
+43953 -6186

No files matched your search

@@ -5,7 +5,8 @@ import android.os.Handler
import android.os.Looper
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit,
private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {}) {
private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {},
private val holds: () -> Boolean = { true }) {
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
private val handler = Handler(Looper.getMainLooper())
private val presses = mutableMapOf<Int, Press>()
@@ -20,6 +21,11 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
fun onChordInput() {
if (presses.isEmpty()) return
if (!holds()) {
presses.values.forEach { handler.removeCallbacks(it.hold); it.used = true }
cancelTap()
return
}
val alreadyHeld = presses.values.any { it.held }
presses.values.forEach {
handler.removeCallbacks(it.hold)
@@ -43,6 +49,7 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
handler.removeCallbacks(singleTap)
val hold = Runnable {
val press = presses[device] ?: return@Runnable
if (!holds()) { press.used = true; cancelTap(); return@Runnable }
val alreadyHeld = presses.values.any { it.held }
press.held = true
presses.values.forEach { it.used = true }
@@ -0,0 +1,149 @@
package com.droiddeck.launcher.input
import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.hardware.display.DisplayManager
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.view.Display
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityWindowInfo
import android.view.inputmethod.InputMethodManager
import java.util.concurrent.ConcurrentHashMap
object BottomScreenGuests {
enum class Top { HOME, GUEST, NONE }
internal const val MIN_COVER = 0.5f
internal fun classify(pkg: String?, homes: Set<String>): Top = when (pkg) {
null -> Top.NONE
in homes -> Top.HOME
else -> Top.GUEST
}
internal fun holder(topPkg: String?, arrival: String?, homes: Set<String>): String? = when {
topPkg != null -> topPkg.takeIf { classify(it, homes) == Top.GUEST }
arrival != null -> arrival.takeIf { classify(it, homes) == Top.GUEST }
else -> null
}
internal fun ignorable(type: Int): Boolean = type == AccessibilityWindowInfo.TYPE_INPUT_METHOD ||
type == AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY ||
type == AccessibilityWindowInfo.TYPE_SPLIT_SCREEN_DIVIDER ||
type == AccessibilityWindowInfo.TYPE_MAGNIFICATION_OVERLAY
fun supported(model: String = Build.MODEL, sdk: Int = Build.VERSION.SDK_INT): Boolean =
sdk >= 33 && DualScreen.yieldsBottom(model)
}
class BottomScreenWatch(private val service: AccessibilityService) {
private class Arrival(val pkg: String)
private val thread = HandlerThread("bottom-screen").apply { start() }
private val handler = Handler(thread.looper)
private val own = service.packageName
private val arrivals = ConcurrentHashMap<Int, Arrival>()
private var homes: Set<String> = emptySet()
private var keyboards: Set<String> = emptySet()
private var holders: Map<Int, String?> = emptyMap()
private val check = Runnable { evaluate() }
fun start() {
current = this
service.serviceInfo = service.serviceInfo?.apply {
eventTypes = eventTypes or AccessibilityEvent.TYPE_WINDOWS_CHANGED or AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
}
handler.post {
homes = homePackages()
keyboards = keyboardPackages()
evaluate()
}
}
fun onEvent(event: AccessibilityEvent) {
when (event.eventType) {
AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
val pkg = event.packageName?.toString() ?: return
if (event.displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
arrivals[event.displayId] = Arrival(pkg)
}
AccessibilityEvent.TYPE_WINDOWS_CHANGED -> Unit
else -> return
}
handler.removeCallbacks(check)
handler.postDelayed(check, 150)
}
fun stop() {
handler.removeCallbacksAndMessages(null)
handler.post {
if (current === this) {
current = null
DualScreen.setTaken(emptySet())
}
}
thread.quitSafely()
}
private fun evaluate() {
val seen = HashMap(arrivals)
val all = runCatching { service.windowsOnAllDisplays }.getOrNull() ?: return
val displays = service.getSystemService(DisplayManager::class.java) ?: return
val taken = mutableMapOf<Int, String?>()
for (i in 0 until all.size()) {
val id = all.keyAt(i)
if (id == Display.DEFAULT_DISPLAY) continue
val display = displays.getDisplay(id)?.takeIf(DualScreen::builtIn) ?: continue
val windows = all.valueAt(i)
val topPkg = windows.asSequence()
.filter { !BottomScreenGuests.ignorable(it.type) && cover(it, display) >= BottomScreenGuests.MIN_COVER }
.sortedByDescending { it.layer }
.firstNotNullOfOrNull { packageOf(it)?.takeUnless { pkg -> pkg == own } }
val arrival = seen[id]
if (topPkg != null && arrival != null) arrivals.remove(id, arrival)
BottomScreenGuests.holder(topPkg, arrival?.pkg?.takeUnless { it in keyboards }, homes)?.let { taken[id] = it }
}
if (current !== this) return
if (taken != holders) Log.i(TAG, "bottom screen holders: $taken")
holders = taken
DualScreen.setTaken(taken.keys)
}
private fun cover(window: AccessibilityWindowInfo, display: Display): Float {
val bounds = Rect().also(window::getBoundsInScreen)
val area = display.mode.physicalWidth.toFloat() * display.mode.physicalHeight
return if (area <= 0f) 0f else bounds.width().toFloat() * bounds.height() / area
}
private fun packageOf(window: AccessibilityWindowInfo): String? =
runCatching { window.getRoot(0)?.packageName?.toString() }.getOrNull()
private fun homePackages(): Set<String> {
val pm = service.packageManager
return listOf(Intent.CATEGORY_HOME, Intent.CATEGORY_SECONDARY_HOME).flatMap { category ->
runCatching {
pm.queryIntentActivities(Intent(Intent.ACTION_MAIN).addCategory(category), PackageManager.MATCH_ALL)
.filter { it.priority >= 0 }
.mapNotNull { it.activityInfo?.packageName }
}.getOrDefault(emptyList())
}.toSet()
}
private fun keyboardPackages(): Set<String> =
runCatching {
service.getSystemService(InputMethodManager::class.java)?.inputMethodList.orEmpty().map { it.packageName }.toSet()
}.getOrDefault(emptySet())
private companion object {
@Volatile var current: BottomScreenWatch? = null
const val TAG = "BottomScreen"
const val SYSTEM_UI = "com.android.systemui"
}
}
@@ -66,6 +66,10 @@ class DirectTouchHold(
held = false
}
fun cancelPendingHold() {
handler.removeCallbacks(hold)
}
fun onTouch(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
if (liftPending) {
@@ -4,7 +4,11 @@ import android.content.Context
import android.hardware.display.DisplayManager
import android.os.Build
import android.view.Display
import android.view.InputDevice
import android.view.MotionEvent
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.roundToInt
object DualScreen {
const val MODE_AUTO = "auto"
@@ -13,27 +17,86 @@ object DualScreen {
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
private const val TYPE_INTERNAL = 1
private val knownModels = setOf("retroid pocket duo", "ayn thor")
private val touchedDisplays = mutableSetOf<Int>()
private val takenListeners = java.util.concurrent.CopyOnWriteArraySet<() -> Unit>()
@Volatile private var takenDisplays: Set<Int> = emptySet()
private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) }
fun taken(displayId: Int): Boolean = displayId in takenDisplays
fun setTaken(ids: Set<Int>) {
if (ids == takenDisplays) return
takenDisplays = ids
main.post { takenListeners.forEach { it() } }
}
fun watchTaken(listener: () -> Unit) { takenListeners += listener }
fun unwatchTaken(listener: () -> Unit) { takenListeners -= listener }
fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? {
val primary = displayManager.getDisplay(primaryDisplayId)
val awake = primary?.state != Display.STATE_OFF
val panels = if (awake) touchPanels() else emptyList()
return internalDisplay(displayManager, primaryDisplayId) {
if (awake && it.state == Display.STATE_OFF) return@internalDisplay false
synchronized(touchedDisplays) {
if (awake && hasOwnTouchPanel(size(it), primary?.let(::size), panels)) touchedDisplays += it.displayId
it.displayId in touchedDisplays
}
}
}
private fun internalDisplay(displayManager: DisplayManager, primaryDisplayId: Int, accept: (Display) -> Boolean = { true }): Display? =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 &&
isBuiltIn(displayType(it), Build.MODEL)
isBuiltIn(displayType(it), Build.MODEL) && accept(it)
}
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
when (SessionPrefs.dualScreenMode(context)) {
MODE_OFF -> null
MODE_ON -> builtInDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
else -> builtInDisplay(displayManager, primaryDisplayId)
internal fun hasOwnTouchPanel(display: Pair<Int, Int>, primary: Pair<Int, Int>?, panels: List<Pair<Int, Int>>): Boolean {
val matching = panels.count { covers(it, display) }
return if (primary != null && covers(primary, display)) matching >= 2 else matching >= 1
}
private fun covers(panel: Pair<Int, Int>, display: Pair<Int, Int>): Boolean =
(near(panel.first, display.first) && near(panel.second, display.second)) ||
(near(panel.first, display.second) && near(panel.second, display.first))
private fun near(a: Int, b: Int) = abs(a - b) <= 2
private fun size(display: Display): Pair<Int, Int> =
display.mode.let { it.physicalWidth to it.physicalHeight }
private fun touchPanels(): List<Pair<Int, Int>> =
InputDevice.getDeviceIds().toList().mapNotNull { id ->
val device = InputDevice.getDevice(id) ?: return@mapNotNull null
if (device.isVirtual || !device.supportsSource(InputDevice.SOURCE_TOUCHSCREEN)) return@mapNotNull null
val x = device.getMotionRange(MotionEvent.AXIS_X, InputDevice.SOURCE_TOUCHSCREEN) ?: return@mapNotNull null
val y = device.getMotionRange(MotionEvent.AXIS_Y, InputDevice.SOURCE_TOUCHSCREEN) ?: return@mapNotNull null
(x.max - x.min + 1f).roundToInt() to (y.max - y.min + 1f).roundToInt()
}
fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context))
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
when (mode) {
MODE_OFF -> null
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
else -> builtInDisplay(displayManager, primaryDisplayId)
}?.takeUnless { taken(it.displayId) }
fun anyDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0
}
fun builtIn(display: Display): Boolean = isBuiltIn(displayType(display), Build.MODEL)
internal fun isBuiltIn(type: Int?, model: String): Boolean =
if (type != null) type == TYPE_INTERNAL else model.trim().lowercase() in knownModels
if (type != null) type == TYPE_INTERNAL else yieldsBottom(model)
private fun displayType(display: Display): Int? =
runCatching { Display::class.java.getMethod("getType").invoke(display) as Int }.getOrNull()
@@ -612,7 +612,6 @@ public class FakeInputWriter {
for (int i = 0; i < length; i++) output[9 + i] = ring.get(TRITON_OUTPUT_OFFSET + i);
nativeStoreFence();
if (seq != ring.getLong(TRITON_OUTPUT_SEQ_OFFSET)) return null;
// Acknowledge the exact report sequence taken so a concurrent timeout overwrite cannot lose its length.
ring.putInt(TRITON_OUTPUT_ACK_OFFSET, (int) seq);
nativeStoreFence();
return output;
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.input
import android.content.Context
/** Global defaults with optional overrides for the currently focused game. */
object GesturePrefs {
private fun prefs(context: Context) = context.getSharedPreferences("touch_gestures", Context.MODE_PRIVATE)
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.input
import android.view.MotionEvent
/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
internal class GestureTouchStreamGate {
enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
@@ -0,0 +1,35 @@
package com.droiddeck.launcher.input
import android.view.KeyEvent
object GuestKeys {
/** Sends [event] as evdev presses, with Shift around characters typed by a keyboard that has no Shift key; false when it has no evdev code. */
fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean {
val down = event.action == KeyEvent.ACTION_DOWN
if (!down && event.action != KeyEvent.ACTION_UP) return false
var evdev = if (isKeyboardEscape(event.keyCode, event.scanCode)) KEY_ESC else EvdevKeys.fromKeyCode(event.keyCode)
val ch = event.unicodeChar
val plain = if (ch > 0) EvdevKeys.unshiftedChar(ch) else 0
if (evdev <= 0 && ch > 0) {
val code = EvdevKeys.fromKeyCode(EvdevKeys.keycodeForChar(if (plain != 0) plain else ch))
if (code > 0) evdev = code
}
val shiftEvdev = if (evdev > 0 && plain != 0 && event.deviceId <= 0) KEY_LEFTSHIFT else 0
if (evdev <= 0 && event.scanCode > 0) evdev = event.scanCode
if (evdev <= 0) return false
if (down) {
if (shiftEvdev != 0) sendKey(shiftEvdev, true)
sendKey(evdev, true)
} else {
sendKey(evdev, false)
if (shiftEvdev != 0) sendKey(shiftEvdev, false)
}
return true
}
fun isKeyboardEscape(keyCode: Int, scanCode: Int): Boolean =
keyCode == KeyEvent.KEYCODE_BACK && scanCode == KEY_ESC
private const val KEY_ESC = 1
private const val KEY_LEFTSHIFT = 42
}
@@ -37,7 +37,6 @@ object HomeButtonShortcuts {
}
fun onKeyEvent(context: Context, event: KeyEvent): Boolean {
// AYN maps its system-assistant key (gpio-keys KEY_F24) to HOME too; only the pad's Home is Guide.
if (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false
return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context))
}
@@ -46,13 +45,78 @@ object HomeButtonShortcuts {
fun onDeviceRemoved(device: Int) = input.onDeviceRemoved(device)
}
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
override fun onServiceConnected() {
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
object SystemKeyCapture {
private var owner: Any? = null
private var active: () -> Boolean = { false }
private var send: (KeyEvent) -> Unit = {}
private val held = HashMap<Pair<Int, Int>, KeyEvent>()
private val releasing = HashSet<Pair<Int, Int>>()
internal var isKeyboard: (KeyEvent) -> Boolean = ::fromKeyboard
fun attach(owner: Any, active: () -> Boolean, send: (KeyEvent) -> Unit) {
this.owner = owner
this.active = active
this.send = send
}
override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event)
override fun onAccessibilityEvent(event: AccessibilityEvent?) {}
fun detach(owner: Any) {
if (this.owner !== owner) return
held.values.forEach { send(KeyEvent.changeAction(it, KeyEvent.ACTION_UP)) }
releasing += held.keys
held.clear()
this.owner = null
active = { false }
send = {}
}
internal fun captures(keyCode: Int, metaState: Int): Boolean = when {
keyCode == KeyEvent.KEYCODE_META_LEFT || keyCode == KeyEvent.KEYCODE_META_RIGHT -> true
metaState and KeyEvent.META_META_ON != 0 -> true
metaState and KeyEvent.META_ALT_ON != 0 -> keyCode == KeyEvent.KEYCODE_TAB || keyCode == KeyEvent.KEYCODE_ESCAPE
else -> false
}
private fun fromKeyboard(event: KeyEvent): Boolean =
event.device?.let { !it.isVirtual && it.keyboardType == android.view.InputDevice.KEYBOARD_TYPE_ALPHABETIC } == true
fun onKeyEvent(event: KeyEvent): Boolean {
val key = event.deviceId to event.keyCode
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
releasing -= key
} else if (key in releasing) {
if (event.action == KeyEvent.ACTION_UP) releasing -= key
return true
}
val taken = when (event.action) {
KeyEvent.ACTION_DOWN -> {
val take = key in held || (event.repeatCount == 0 && active() && isKeyboard(event) && captures(event.keyCode, event.metaState))
if (take) held[key] = KeyEvent(event)
take
}
KeyEvent.ACTION_UP -> held.remove(key) != null
else -> false
}
if (taken) send(event)
return taken
}
}
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
private var bottomScreen: BottomScreenWatch? = null
override fun onServiceConnected() {
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
if (bottomScreen == null && BottomScreenGuests.supported()) bottomScreen = BottomScreenWatch(this).also { it.start() }
}
private fun stopBottomScreen() {
bottomScreen?.stop()
bottomScreen = null
}
override fun onKeyEvent(event: KeyEvent) =
SystemKeyCapture.onKeyEvent(event) || HomeButtonShortcuts.onKeyEvent(this, event)
override fun onAccessibilityEvent(event: AccessibilityEvent?) { event?.let { bottomScreen?.onEvent(it) } }
override fun onInterrupt() { HomeButtonShortcuts.release() }
override fun onInputDeviceAdded(deviceId: Int) {}
override fun onInputDeviceChanged(deviceId: Int) {}
@@ -60,11 +124,14 @@ class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListen
override fun onUnbind(intent: Intent?): Boolean {
HomeButtonShortcuts.release()
stopBottomScreen()
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
return super.onUnbind(intent)
}
override fun onDestroy() {
HomeButtonShortcuts.release()
stopBottomScreen()
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
super.onDestroy()
}
@@ -46,7 +46,6 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa
}
companion object {
// The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME.
fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME
private const val DUO_QUICK_MENU_SCAN_CODE = 194
@@ -13,6 +13,7 @@ import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import com.droiddeck.launcher.session.SessionPrefs
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
@@ -59,15 +60,20 @@ class OnScreenControls(
return dx * dx + dy * dy <= hit * hit
}
fun drag(x: Float, y: Float) {
fun drag(x: Float, y: Float): Boolean {
var dx = x - ax
var dy = y - ay
val d = sqrt(dx * dx + dy * dy)
if (d > radius) { dx = dx / d * radius; dy = dy / d * radius }
val atLimit = d > radius
if (atLimit) { dx = dx / d * radius; dy = dy / d * radius }
if (!atLimit && abs(dx - kx) < MIN_STICK_MOVE_PX && abs(dy - ky) < MIN_STICK_MOVE_PX) return false
kx = dx; ky = dy; dirty = true
return true
}
}
private val stickRedraw = ThrottledRedraw(this, STICK_REDRAW_MS)
private val controls = listOf(
Control("up", "dpad", -1, 26f, 0f, -52f),
Control("right", "dpad", -1, 26f, 52f, 0f),
@@ -211,6 +217,7 @@ class OnScreenControls(
}
override fun onDetachedFromWindow() {
stickRedraw.cancel()
releaseAll()
pad?.releaseTouch(this)
super.onDetachedFromWindow()
@@ -513,6 +520,7 @@ class OnScreenControls(
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (editing) return onEditTouch(event)
if (event.getToolType(event.actionIndex) == MotionEvent.TOOL_TYPE_MOUSE) return false
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
val index = event.actionIndex
@@ -543,7 +551,7 @@ class OnScreenControls(
control.ay = if (adaptive) event.getY(index) else control.cy
control.drag(event.getX(index), event.getY(index))
}
requestUnbufferedDispatch(event)
if (SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
apply()
return true
}
@@ -552,13 +560,14 @@ class OnScreenControls(
if (keyboardPressedBy != -1) return true
if (quickPressedBy != -1) return true
var changed = false
var stickMoved = false
for (index in 0 until event.pointerCount) {
val pointer = event.getPointerId(index)
if (forwardedPointerBits and (1 shl pointer) != 0) continue
val x = event.getX(index)
val y = event.getY(index)
val stick = controls.firstOrNull { it.stick >= 0 && it.pressedBy == pointer }
if (stick != null) { stick.drag(x, y); changed = true; continue }
if (stick != null) { stickMoved = stick.drag(x, y) || stickMoved; continue }
val over = controlAt(x, y)?.takeIf { it.stick < 0 }
for (control in controls) {
if (control.stick < 0 && control.pressedBy == pointer && control !== over) {
@@ -571,7 +580,7 @@ class OnScreenControls(
changed = true
}
}
if (changed) apply()
if (changed) apply() else if (stickMoved) apply(stickOnly = true)
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
@@ -673,7 +682,6 @@ class OnScreenControls(
private fun closestSnap(position: Float, targets: List<Float>): Float? =
targets.minByOrNull { abs(position - it) }?.takeIf { abs(position - it) <= dp(SNAP_DP) }
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean =
editing || keyboardContains(x, y) || (!buttonsOnly && quickContains(x, y)) ||
(!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null)
@@ -706,7 +714,7 @@ class OnScreenControls(
else -> control.target != ControllerPrefs.OFF
}
private fun apply() {
private fun apply(stickOnly: Boolean = false) {
val bridge = pad
if (bridge == null || editing) { invalidate(); return }
if (bridge.hasInputRouter()) {
@@ -721,7 +729,7 @@ class OnScreenControls(
} else write(state, control.id, control.pressedBy != -1)
}
}
invalidate()
if (stickOnly) stickRedraw.request() else invalidate()
return
}
val qamHeld = controls.any { it.id == "qam" && it.pressedBy != -1 }
@@ -753,7 +761,7 @@ class OnScreenControls(
for (target in used) write(state, target, target in held)
}
}
invalidate()
if (stickOnly) stickRedraw.request() else invalidate()
}
private fun write(state: PadState, target: String, down: Boolean) {
@@ -796,6 +804,8 @@ class OnScreenControls(
private companion object {
const val DOUBLE_TAP_MS = 300L
const val STICK_REDRAW_MS = 33L
const val MIN_STICK_MOVE_PX = 1f
const val MIN_FACE_MM = 9.5f
const val FULL_SIZE_HEIGHT_MM = 85f
const val BOTTOM_MARGIN_MM = 5f
@@ -313,11 +313,6 @@ public final class PadBridge {
|| device.supportsSource(InputDevice.SOURCE_JOYSTICK));
}
public static boolean isControllerKey(KeyEvent event) {
return isFromController(event.getDevice())
&& isPadKey(event.getKeyCode(), event.getDevice().getKeyboardType());
}
public static boolean isPadKey(int keyCode, int keyboardType) {
if ((keyCode >= KeyEvent.KEYCODE_BUTTON_A && keyCode <= KeyEvent.KEYCODE_BUTTON_MODE)
|| (keyCode >= KeyEvent.KEYCODE_BUTTON_1 && keyCode <= KeyEvent.KEYCODE_BUTTON_16)) return true;
@@ -706,7 +701,6 @@ public final class PadBridge {
liveReport.copyFrom(report);
if (backQamAxesBlocked && !hasAxes(liveReport)) backQamAxesBlocked = false;
long at = android.os.SystemClock.uptimeMillis();
// Steam must see the modifier before a partner; preserve quick press/release pairs in order.
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
writeBackQamReport(report, at);
}
@@ -51,6 +51,15 @@ val PC_KEY_ROWS: List<List<PcKey>> = listOf(
val PC_MODIFIERS: Set<Int> = setOf(42, 54, 29, 97, 56, 100, 125)
// Sticky modifiers are excluded: hiding a locked modifier would leave it pressed forever.
val PC_KEY_HIDDEN_GROUPS: Map<String, Set<Int>> = mapOf(
"function" to ((59..68).toSet() + setOf(1, 87, 88)),
"nav" to setOf(110, 111, 102, 107, 104, 109),
"arrows" to setOf(103, 105, 108, 106),
)
val PC_KEY_GROUP_IDS: Map<Int, String> = mapOf(0 to "function", 1 to "nav", 2 to "arrows")
val PC_KEYS: Map<Int, PcKey> = PC_KEY_ROWS.flatten().associateBy { it.code }
fun pcKeyLabel(context: Context, code: Int): String {
@@ -11,6 +11,7 @@ class PointerGestures {
fun onScroll(dx: Float, dy: Float) {}
fun onScrollEnd() {}
fun onZoom(steps: Int) {}
fun onThreeFingerTap(): Boolean = false
}
companion object {
@@ -36,12 +36,6 @@ fun screenKeyDirections(shape: Int): List<String> = when (shape) {
else -> emptyList()
}
val SCREEN_KEY_SHAPES =
listOf(
SCREEN_KEY_PILL, SCREEN_KEY_ROUND, SCREEN_KEY_CIRCLE, SCREEN_KEY_RECT,
SCREEN_KEY_TRIGGER, SCREEN_KEY_DPAD, SCREEN_KEY_STICK,
)
data class ScreenKey(
val codes: List<Int>,
val x: Float,
@@ -55,9 +49,4 @@ data class ScreenKey(
val toggle: Boolean = false,
val labels: Boolean = true,
) {
fun shownLabel(context: Context): String = when {
text.isNotEmpty() -> text
glyph.isNotEmpty() -> glyph
else -> screenKeyLabel(context, codes)
}
}
@@ -56,6 +56,7 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
private var guideY = -1f
private val addPress = Runnable { addX = pressX; addY = pressY; onAdd?.invoke() }
private var editing = false
val isEditing get() = editing
private var selected: Entry? = null
private var dragX = 0f
private var dragY = 0f
@@ -609,7 +610,6 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
else -> entry.halfH
}
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean = editing || entryAt(x, y) != null
private fun entryAt(x: Float, y: Float): Entry? = entries.lastOrNull { entry ->
@@ -812,6 +812,7 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
override fun onTouchEvent(event: MotionEvent): Boolean = if (editing) editTouch(event) else playTouch(event)
private fun playTouch(event: MotionEvent): Boolean {
if (event.getToolType(event.actionIndex) == MotionEvent.TOOL_TYPE_MOUSE) return false
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
val index = event.actionIndex
@@ -10,11 +10,23 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
TERMINAL("terminal", R.string.second_mode_terminal),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
CUSTOM_CONTROLS("custom-controls", R.string.input_custom_controls);
CUSTOM_CONTROLS("custom-controls", R.string.input_custom_controls),
DASHBOARD("dashboard", R.string.second_mode_dashboard),
DESKTOP("desktop", R.string.second_mode_desktop);
companion object {
fun opening(remembered: String?, deckPad: Boolean): SecondScreenMode =
entries.firstOrNull { it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) } ?: if (deckPad) DECK_CONTROLS else KEYBOARD_TRACKPAD
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, desktop: Boolean = false): SecondScreenMode {
entries.firstOrNull {
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) &&
(it != DESKTOP || desktop)
}?.let { return it }
val picked = entries.any { it != NONE && it.id == remembered }
return when {
deckPad -> DECK_CONTROLS
dashboard && !picked -> DASHBOARD
else -> KEYBOARD_TRACKPAD
}
}
}
}
@@ -107,12 +107,12 @@ class SteamTouchControls(
var onTouchMiss: ((MotionEvent) -> Unit)? = null
private var editing = false
var onEditingChanged: ((Boolean) -> Unit)? = null
private var editElements: MutableList<Element> = mutableListOf()
private var hidden: MutableList<Element> = mutableListOf()
private var selected = -1
private var dragOffset = 0f to 0f
private var pinchStart = 0f
private var pinchScale = 1f
private var saving = false
private val pendingBindings = HashMap<SteamTouchBindings.Ref, SteamTouchBindings.Binding>()
private var pendingColor: FloatArray? = null
@@ -140,6 +140,7 @@ class SteamTouchControls(
override fun onDetachedFromWindow() {
handler.removeCallbacks(poll)
moveRedraw.cancel()
sensors.unregisterListener(shakeListener)
releaseAll()
super.onDetachedFromWindow()
@@ -244,7 +245,6 @@ class SteamTouchControls(
private fun hit(list: List<Element>, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
/** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean = editing || menuOpen || hit(live(), x, y) != null
private fun live(): List<Element> =
@@ -350,17 +350,6 @@ class SteamTouchControls(
canvas.restore()
}
private fun drawSteamMark(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND }
p.strokeWidth = r * 0.16f
canvas.drawCircle(x + r * 0.28f, y - r * 0.18f, r * 0.27f, p)
canvas.drawCircle(x + r * 0.28f, y - r * 0.18f, r * 0.1f, Paint(p).apply { style = Paint.Style.FILL })
canvas.drawCircle(x - r * 0.3f, y + r * 0.3f, r * 0.17f, p)
p.strokeWidth = r * 0.2f
canvas.drawLine(x + r * 0.1f, y - r * 0.02f, x - r * 0.2f, y + r * 0.22f, p)
canvas.drawLine(x - r * 0.45f, y + r * 0.28f, x - r * 0.95f, y + r * 0.1f, p)
}
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
alpha: Int, pressed: Boolean) {
val square = isSquare(type)
@@ -559,7 +548,7 @@ class SteamTouchControls(
return bits
}
private fun publish() {
private fun publish(moving: Boolean = false) {
var buttons = 0L
val sticks = ShortArray(4)
val pads = ShortArray(6)
@@ -590,7 +579,7 @@ class SteamTouchControls(
}
}
device.setControls(buttons, sticks, pads)
invalidate()
if (moving) moveRedraw.request() else invalidate()
}
fun releaseAll() {
@@ -599,6 +588,8 @@ class SteamTouchControls(
invalidate()
}
private val moveRedraw = ThrottledRedraw(this, MOVE_REDRAW_MS)
private fun keepHeldFingers() {
val moved = SteamTouchConfig.remapHeld(fingers.mapValues { it.value.element?.type }, live())
fingers.keys.retainAll(moved.keys)
@@ -627,6 +618,7 @@ class SteamTouchControls(
}
return true
}
if (event.getToolType(event.actionIndex) == MotionEvent.TOOL_TYPE_MOUSE) return false
val index = event.actionIndex
lastTouchMs = android.os.SystemClock.uptimeMillis()
if (faded) { faded = false; invalidate() }
@@ -647,7 +639,7 @@ class SteamTouchControls(
if (forwardedPointerBits != 0) forwardPointers(event, forwardedPointerBits)
fingers[event.getPointerId(index)] = Finger(e, x, y)
if (feedback) performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
requestUnbufferedDispatch(event)
if (com.droiddeck.launcher.session.SessionPrefs.lowLatency(context)) requestUnbufferedDispatch(event)
publish()
return true
}
@@ -666,7 +658,7 @@ class SteamTouchControls(
}
}
}
publish()
publish(moving = true)
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP, MotionEvent.ACTION_CANCEL -> {
@@ -715,6 +707,7 @@ class SteamTouchControls(
fun startEditing() {
releaseAll()
editing = true
onEditingChanged?.invoke(true)
editSets.clear()
selected = -1
pendingBindings.clear()
@@ -765,8 +758,13 @@ class SteamTouchControls(
actionSet = saved
}
fun cancelEditing() {
if (editing) stopEditing()
}
private fun stopEditing() {
editing = false
onEditingChanged?.invoke(false)
trayOpen = false
trayDrag = null
selected = -1
@@ -855,19 +853,6 @@ class SteamTouchControls(
invalidate()
}
private fun controlName(type: Int) = when (type) {
SteamTouchConfig.DPAD -> context.getString(R.string.touch_dpad)
SteamTouchConfig.JOYSTICK_LEFT -> context.getString(R.string.touch_left_stick)
SteamTouchConfig.JOYSTICK_RIGHT -> context.getString(R.string.touch_right_stick)
SteamTouchConfig.TRACKPAD_LEFT -> context.getString(R.string.deck_left_trackpad)
SteamTouchConfig.TRACKPAD_RIGHT -> context.getString(R.string.deck_right_trackpad)
SteamTouchConfig.TRACKPAD_CENTER -> context.getString(R.string.deck_surface_trackpad)
SteamTouchConfig.STEAM -> "Steam"
SteamTouchConfig.THUMB -> context.getString(R.string.touch_menu)
SteamTouchConfig.KEYBOARD -> context.getString(R.string.touch_keyboard)
else -> label(type)
}
private fun moreMenu() {
val host = parent as? android.view.ViewGroup ?: return
val density = resources.displayMetrics.density
@@ -1495,6 +1480,7 @@ class SteamTouchControls(
companion object {
private const val TAG = "SteamTouch"
private const val POLL_MS = 150L
private const val MOVE_REDRAW_MS = 33L
const val BIG_PICTURE = 769
private const val ICON_PX = 128
private const val MARK_D = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z" +
@@ -74,8 +74,6 @@ class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
Log.i(TAG, "steam touch: " + if (value) "plugged in" else "unplugged")
}
fun setBattery(percent: Int) = buffer.putInt(OFF_BATTERY, percent.coerceIn(0, 100))
fun state(): State {
repeat(8) {
val seq = buffer.getLong(OFF_STATE_SEQ)
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.input
import android.media.AudioManager
import android.view.KeyEvent
/** Use Steam's PulseAudio bridge for feedback instead of requesting Android's volume UI. */
internal object SteamVolumeKeys {
fun dispatch(event: KeyEvent, enabled: Boolean, adjust: (Int) -> Unit): Boolean {
val direction = when (event.keyCode) {
@@ -0,0 +1,21 @@
package com.droiddeck.launcher.input
import android.os.SystemClock
import android.view.View
internal class ThrottledRedraw(private val view: View, private val intervalMs: Long) {
private var last = 0L
private val redraw = Runnable {
last = SystemClock.uptimeMillis()
view.invalidate()
}
fun request() {
view.removeCallbacks(redraw)
view.postDelayed(redraw, (last + intervalMs - SystemClock.uptimeMillis()).coerceAtLeast(0L))
}
fun cancel() {
view.removeCallbacks(redraw)
}
}
@@ -39,6 +39,7 @@ data class TouchGestureConfig(
val showGestureDebugOverlay: Boolean = false,
val gestureThreshold: Int = DEFAULT_GESTURE_THRESHOLD,
val mouseDragMovementMode: String = MOUSE_DRAG_MOVEMENT_DIRECT,
val relativeMouseMode: Int = RELATIVE_MOUSE_AUTO,
) {
fun toJson(): String {
@@ -75,6 +76,7 @@ data class TouchGestureConfig(
put(KEY_SHOW_GESTURE_DEBUG_OVERLAY, showGestureDebugOverlay)
put(KEY_GESTURE_THRESHOLD, gestureThreshold)
put(KEY_MOUSE_DRAG_MOVEMENT_MODE, mouseDragMovementMode)
put(KEY_RELATIVE_MOUSE_MODE, relativeMouseMode)
}.toString()
}
@@ -91,6 +93,10 @@ data class TouchGestureConfig(
const val MOUSE_DRAG_MOVEMENT_DIRECT = "direct"
const val MOUSE_DRAG_MOVEMENT_RELATIVE = "relative"
const val RELATIVE_MOUSE_AUTO = 0
const val RELATIVE_MOUSE_ON = 1
const val RELATIVE_MOUSE_OFF = 2
const val ACTION_SHOW_KEYBOARD = "show_keyboard"
const val ACTION_KEY_ESC = "key_ESC"
const val ACTION_KEY_TILDE = "key_TILDE"
@@ -114,6 +120,7 @@ data class TouchGestureConfig(
private const val KEY_LONG_PRESS_MOUSE_BEHAVIOR = "longPressMouseBehavior"
private const val KEY_LONG_PRESS_DELAY = "longPressDelay"
private const val KEY_DIRECT_HOLD_BEHAVIOR = "directHoldBehavior"
private const val KEY_RELATIVE_MOUSE_MODE = "relativeMouseMode"
private const val KEY_DOUBLE_TAP_ENABLED = "doubleTapEnabled"
private const val KEY_DOUBLE_TAP_DELAY = "doubleTapDelay"
private const val KEY_TWO_FINGER_DRAG_ENABLED = "twoFingerDragEnabled"
@@ -191,6 +198,7 @@ data class TouchGestureConfig(
mouseDragMovementMode = normalizeMouseDragMovementMode(
obj.optString(KEY_MOUSE_DRAG_MOVEMENT_MODE, MOUSE_DRAG_MOVEMENT_DIRECT),
),
relativeMouseMode = normalizeRelativeMouseMode(obj.optInt(KEY_RELATIVE_MOUSE_MODE, RELATIVE_MOUSE_AUTO)),
)
} catch (_: Exception) {
fallbackDefaults()
@@ -205,6 +213,10 @@ data class TouchGestureConfig(
return if (value == MOUSE_BEHAVIOR_CLICK) MOUSE_BEHAVIOR_CLICK else MOUSE_BEHAVIOR_HOLD
}
private fun normalizeRelativeMouseMode(mode: Int): Int {
return if (mode in RELATIVE_MOUSE_AUTO..RELATIVE_MOUSE_OFF) mode else RELATIVE_MOUSE_AUTO
}
private fun normalizeMouseDragMovementMode(mode: String?): String {
return if (mode == MOUSE_DRAG_MOVEMENT_RELATIVE) {
MOUSE_DRAG_MOVEMENT_RELATIVE
@@ -240,7 +240,8 @@ class TouchpadGestures(
}
if (desktop && scrolled && event.pointerCount == 2) listener.onScrollEnd()
if (fingers >= 3) {
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2)
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2 &&
!listener.onThreeFingerTap())
click(PointerGestures.BTN_MIDDLE)
if (event.pointerCount == 2) secondWasTap = false
} else if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TouchTiming.TAP_MS && !scrolled) {
@@ -28,7 +28,6 @@ public final class TouchscreenGestures {
void key(int code, boolean down);
void wheel(int steps);
void showKeyboard();
/** Establish the pointer origin before a relative middle-mouse pan begins. */
default void prepareRelativePan() {}
default void gesture(Gesture gesture) {}
}
@@ -97,12 +96,10 @@ public final class TouchscreenGestures {
final int code;
MouseButton(int code) { this.code = code; }
}
// Long-press detection
private Runnable longPressRunnable;
private boolean longPressTriggered;
private boolean longPressActionHeld, twoFingerHoldActionHeld, threeFingerHoldActionHeld;
// Double-tap detection
private long lastTapTime;
private float lastTapX;
private float lastTapY;
@@ -110,76 +107,54 @@ public final class TouchscreenGestures {
private float doubleTapAnchorX, doubleTapAnchorY;
private long singleFingerDownTime;
// Drag tracking (box selection)
private boolean isDragging;
private boolean dragButtonPressed;
// Two-finger tracking
private boolean twoFingerDragging;
private float twoFingerLastX0, twoFingerLastY0;
private float twoFingerLastX1, twoFingerLastY1;
private boolean twoFingerMiddleButtonDown;
// Pinch tracking
private float pinchLastDistance;
private float pinchZoomRemainder;
private float keyPanRemainderX, keyPanRemainderY;
private static final float PINCH_STEP_PX = 10f;
// Two-finger tap detection
private boolean twoFingerTapPossible;
private boolean twoFingerTapFired;
// Track which WASD/arrow keys are currently held
private boolean panKeyUp, panKeyDown, panKeyLeft, panKeyRight;
// True when finger has moved beyond tap tolerance (prevents spurious tap on lift)
private boolean movedBeyondTapThreshold;
// True after a multi-finger gesture has been active — prevents the remaining
// finger from starting a spurious single-finger drag on lift sequence.
private boolean multiFingerGestureUsed;
// Remember which keycodes were actually pressed so releasePanKeys releases only those
private Integer panLeftKey, panRightKey, panUpKey, panDownKey;
// Long-press movement tolerance (pixels of raw finger movement before cancelling long-press)
private static final float LONG_PRESS_MOVE_TOLERANCE = 50f;
// Raw touch-down coordinates for measuring finger travel
private float touchDownRawX, touchDownRawY;
// Last raw coordinates for single-finger drag delta
private float singleFingerLastRawX, singleFingerLastRawY;
// Two-finger gesture mutual exclusion (only pan OR pinch, not both)
private static final int TWO_FINGER_GESTURE_NONE = 0;
private static final int TWO_FINGER_GESTURE_PAN = 1;
private static final int TWO_FINGER_GESTURE_ZOOM = 2;
private int twoFingerGestureMode = TWO_FINGER_GESTURE_NONE;
// Accumulated deltas for deciding which two-finger gesture to lock into
private float accumulatedPinchDelta, accumulatedPanDelta;
// Settle window: ignore movement for first N ms after second finger lands (#1)
// Also serves as a grace period for a third finger to arrive before 2F locks in
private static final long TWO_FINGER_SETTLE_MS = 120;
private static final long THREE_FINGER_SETTLE_MS = 50;
private long twoFingerDownTime;
private long threeFingerDownTime;
// Velocity gating for two-finger hold vs drag (#2)
private long twoFingerLastMoveTime;
private static final float MIN_DRAG_VELOCITY = 0.3f; // px/ms to commit to drag
private static final float MIN_DRAG_VELOCITY = 0.3f;
// Pinch vs drag ratio: pinch delta must exceed pan by this factor to classify as pinch (#4)
private static final float PINCH_RATIO_THRESHOLD = 1.5f;
// Cancel-and-reclassify: allow reclassification within this window after lock-in (#5)
private static final long RECLASSIFY_WINDOW_MS = 100;
private long twoFingerLockTime;
private float reclassifyPinchDelta, reclassifyPanDelta;
// Gesture pointer ownership tracking (prevents d-pad/button pointer conflicts)
private int gestureFingerCount = 0;
private final ArrayList<Integer> gestureOwnedPointerIds = new ArrayList<>();
private final int[] multiFingerStartIds = new int[3];
private final float[] multiFingerStartX = new float[3], multiFingerStartY = new float[3];
private int multiFingerStartCount;
// Two-finger hold detection
private Runnable twoFingerHoldRunnable;
private boolean twoFingerHoldTriggered;
// Three-finger tracking
private boolean threeFingerTapPossible;
private boolean threeFingerTapFired;
private boolean threeFingerDragging;
@@ -199,9 +174,7 @@ public final class TouchscreenGestures {
switch (action) {
case MotionEvent.ACTION_DOWN:
// A new touch must not shorten or discard an already recognized click.
handleTsCancel(true);
// First pointer overall — gesture system claims it
gestureOwnedPointerIds.clear();
gestureOwnedPointerIds.add(pointerId);
gestureFingerCount = 1;
@@ -209,13 +182,11 @@ public final class TouchscreenGestures {
break;
case MotionEvent.ACTION_POINTER_DOWN:
// New pointer arrived — gesture system claims it
if (!gestureOwnedPointerIds.contains(pointerId)) {
gestureOwnedPointerIds.add(pointerId);
gestureFingerCount++;
}
if (gestureFingerCount == 1) {
// First gesture finger (controls own earlier pointers)
handleTsDown(event, actionIndex);
} else if (gestureFingerCount == 2) {
handleTsPointerDown(event);
@@ -242,15 +213,12 @@ public final class TouchscreenGestures {
gestureOwnedPointerIds.remove(Integer.valueOf(pointerId));
gestureFingerCount = Math.max(0, gestureFingerCount - 1);
if (prevCount == 3 && gestureFingerCount == 2) {
// Three-finger gesture ending
handleTsThreeFingerUp(event);
} else if (prevCount == 2 && gestureFingerCount == 1) {
// Two-finger gesture ending (2→1)
handleTsPointerUp(event);
} else if (prevCount >= 4) {
if (removedIndex < 3) rebaseThreeFingerMovement(event);
} else if (prevCount >= 1 && gestureFingerCount == 0) {
// Last gesture finger lifted while controls still hold pointers
handleTsUp(event, actionIndex);
}
}
@@ -261,9 +229,6 @@ public final class TouchscreenGestures {
int prevCount = gestureFingerCount;
gestureOwnedPointerIds.remove(Integer.valueOf(pointerId));
gestureFingerCount = Math.max(0, gestureFingerCount - 1);
// Clean up multi-finger state if needed, routing by previous
// gesture mode so a 3-finger gesture isn't ended via the
// two-finger cleanup path.
if (prevCount >= 3) {
handleTsThreeFingerUp(event);
} else if (prevCount == 2) {
@@ -271,7 +236,6 @@ public final class TouchscreenGestures {
}
handleTsUp(event, actionIndex);
}
// ACTION_UP = last pointer overall — full cleanup
gestureOwnedPointerIds.clear();
gestureFingerCount = 0;
break;
@@ -309,15 +273,12 @@ public final class TouchscreenGestures {
threeFingerHoldTriggered = false;
accumulatedThreeFingerDelta = 0;
// Store raw touch coordinates for long-press movement tolerance
touchDownRawX = event.getX(actionIndex);
touchDownRawY = event.getY(actionIndex);
singleFingerDownTime = SystemClock.uptimeMillis();
singleFingerLastRawX = touchDownRawX;
singleFingerLastRawY = touchDownRawY;
// Keep a nearby re-tap undecided until UP: it can still become a drag,
// long press, or multi-finger gesture instead of a double click.
if (isDoubleTap(event, actionIndex)) {
secondTapCandidate = true;
doubleTapAnchorX = lastTapX;
@@ -327,7 +288,6 @@ public final class TouchscreenGestures {
if (!secondTapCandidate && delayedPress == null && pendingTapPress == null) moveCursorTo(x, y);
// Schedule long-press
if (gestureConfig.getLongPressEnabled()) {
longPressRunnable = () -> {
secondTapCandidate = false;
@@ -342,7 +302,6 @@ public final class TouchscreenGestures {
postDelayed(longPressRunnable, gestureConfig.getLongPressDelay());
}
// Tap: immediate cursor move (press is deferred to UP for click, or MOVE for drag)
}
private void handleTsPointerDown(MotionEvent event) {
@@ -351,11 +310,6 @@ public final class TouchscreenGestures {
flushPendingTapRelease();
lastTapTime = 0;
flushPendingHoldClickRelease();
// Cancel any single-finger long-press. cancelLongPressTimer only
// clears the pending runnable; if the long-press has already fired
// we must also release the held action before we transition into a
// multi-finger gesture, otherwise the long-press button/key stays
// down for the rest of the touch sequence.
if (longPressTriggered) {
longPressActionHeld = releaseHoldAction(longPressActionHeld, gestureConfig.getLongPressAction());
longPressTriggered = false;
@@ -388,7 +342,6 @@ public final class TouchscreenGestures {
event.getY(idx0) - event.getY(idx1));
recordMultiFingerOrigins(event, 2);
}
// Schedule two-finger hold
if (gestureConfig.getTwoFingerHoldEnabled()) {
twoFingerHoldRunnable = () -> {
twoFingerHoldTriggered = true;
@@ -404,33 +357,26 @@ public final class TouchscreenGestures {
}
private void handleTsMove(MotionEvent event, int pointerIndex) {
// After a multi-finger gesture, ignore single-finger movement until all fingers lift
if (multiFingerGestureUsed) return;
int x = (int) event.getX(pointerIndex);
int y = (int) event.getY(pointerIndex);
// If long press already triggered, ignore movement (right-click already sent)
if (longPressTriggered) return;
// Measure raw finger travel from initial touch point
float rawTravel = maxFingerTravel(event, pointerIndex, touchDownRawX, touchDownRawY);
if (secondTapCandidate && (rawTravel > doubleTapSlop
|| maxFingerTravel(event, pointerIndex, doubleTapAnchorX, doubleTapAnchorY) >= doubleTapSlop)) {
secondTapCandidate = false;
}
// The threshold decides when a drag starts. An active drag must keep
// following the finger even when it returns through the touch origin.
if (!isDragging && rawTravel <= LONG_PRESS_MOVE_TOLERANCE) {
return;
}
// Beyond tolerance — cancel long press
cancelLongPressTimer();
movedBeyondTapThreshold = true;
// Detect drag start
if (!isDragging && gestureConfig.getDragEnabled()) {
flushPendingTapRelease();
String dragAction = gestureConfig.getDragAction();
@@ -438,14 +384,7 @@ public final class TouchscreenGestures {
dragButtonPressed = true;
singleFingerLastRawX = event.getX(pointerIndex);
singleFingerLastRawY = event.getY(pointerIndex);
// Send the configured drag press immediately so that a short
// move followed straight by UP still produces a press+release
// pair. A zero-delta performPanAction just presses the button
// (or is a no-op for the key-pan variants, which press per
// direction on their next move frame).
if (isClickDragAction(dragAction)) {
// The candidate's cursor stayed at the previous click. Start
// a drag at this touch's own origin before pressing its button.
moveCursorTo((int) touchDownRawX, (int) touchDownRawY);
if (useRelativeMouseDragMovement()) {
pressClickDragAction(dragAction);
@@ -456,7 +395,6 @@ public final class TouchscreenGestures {
performPanAction(0f, 0f, dragAction);
}
notifyGesture(Gesture.DRAG);
// Non-click pan actions continue with real deltas on the next frame.
return;
}
@@ -481,14 +419,11 @@ public final class TouchscreenGestures {
return;
}
// Move cursor
moveCursorTo(x, y);
}
private void handleTsTwoFingerMove(MotionEvent event) {
if (multiFingerGestureUsed) return;
// If a two-finger hold has already fired, ignore subsequent jitter so
// it can't lock into a pan/zoom gesture mid-hold.
if (twoFingerHoldTriggered) return;
if (gestureFingerCount < 2 || gestureOwnedPointerIds.size() < 2) return;
@@ -496,20 +431,15 @@ public final class TouchscreenGestures {
int idx1 = event.findPointerIndex(gestureOwnedPointerIds.get(1));
if (idx0 < 0 || idx1 < 0) return;
// Settling delays recognition, not movement tracking. A swipe or pinch
// must stop being a tap/hold even when it finishes inside that delay.
if (multiFingerMovementExceeded(event)) {
twoFingerTapPossible = false;
cancelTwoFingerHoldTimer();
}
// Slow deliberate travel can cross touch slop before reaching the
// pan/zoom threshold. It must not turn into a stationary hold first.
if (multiFingerMovementExceeded(event, true)) cancelTwoFingerHoldTimer();
float x0 = event.getX(idx0), y0 = event.getY(idx0);
float x1 = event.getX(idx1), y1 = event.getY(idx1);
// Compute per-frame pan and pinch deltas
float currDist = (float) Math.hypot(x0 - x1, y0 - y1);
float framePinchDelta = Math.abs(currDist - pinchLastDistance);
@@ -523,7 +453,6 @@ public final class TouchscreenGestures {
long now = SystemClock.uptimeMillis();
if (now - twoFingerDownTime < TWO_FINGER_SETTLE_MS) {
// Still settling — update stored positions but don't accumulate deltas
twoFingerLastX0 = x0; twoFingerLastY0 = y0;
twoFingerLastX1 = x1; twoFingerLastY1 = y1;
pinchLastDistance = currDist;
@@ -531,14 +460,12 @@ public final class TouchscreenGestures {
}
long frameTime = now - twoFingerLastMoveTime;
twoFingerLastMoveTime = now;
float velocity = (frameTime > 0) ? framePanDelta / frameTime : 0; // px/ms
float velocity = (frameTime > 0) ? framePanDelta / frameTime : 0;
// Accumulate deltas until we have enough movement to decide gesture type
if (twoFingerGestureMode == TWO_FINGER_GESTURE_NONE) {
accumulatedPinchDelta += framePinchDelta;
accumulatedPanDelta += framePanDelta;
if (accumulatedPinchDelta + accumulatedPanDelta > (float) gestureConfig.getGestureThreshold()) {
// Enough movement to lock into a gesture — no longer a tap or hold
twoFingerTapPossible = false;
cancelTwoFingerHoldTimer();
if (accumulatedPinchDelta > accumulatedPanDelta * PINCH_RATIO_THRESHOLD
@@ -551,7 +478,6 @@ public final class TouchscreenGestures {
twoFingerLockTime = now;
notifyGesture(Gesture.TWO_FINGER_DRAG);
} else if (accumulatedPanDelta >= accumulatedPinchDelta && gestureConfig.getTwoFingerDragEnabled()) {
// Fallback: pan is dominant but velocity was too low — still drag
twoFingerGestureMode = TWO_FINGER_GESTURE_PAN;
twoFingerLockTime = now;
notifyGesture(Gesture.TWO_FINGER_DRAG);
@@ -571,7 +497,7 @@ public final class TouchscreenGestures {
reclassifyPinchDelta += framePinchDelta;
reclassifyPanDelta += framePanDelta;
float reclassifyTotal = reclassifyPinchDelta + reclassifyPanDelta;
if (reclassifyTotal > 20f) { // enough post-lock data to reclassify
if (reclassifyTotal > 20f) {
boolean shouldBeZoom = reclassifyPinchDelta > reclassifyPanDelta * PINCH_RATIO_THRESHOLD;
if (shouldBeZoom && twoFingerGestureMode == TWO_FINGER_GESTURE_PAN
&& gestureConfig.getPinchEnabled()) {
@@ -585,7 +511,7 @@ public final class TouchscreenGestures {
resetSmallMovement();
notifyGesture(Gesture.TWO_FINGER_DRAG);
}
twoFingerLockTime = 0; // done reclassifying
twoFingerLockTime = 0;
reclassifyPinchDelta = 0;
reclassifyPanDelta = 0;
}
@@ -595,12 +521,10 @@ public final class TouchscreenGestures {
pinchZoomRemainder = accumulateSignedMovement(pinchZoomRemainder, delta);
if (Math.abs(pinchZoomRemainder) >= PINCH_STEP_PX) {
performZoomAction(pinchZoomRemainder > 0);
// Keep the fractional travel, without queuing a burst of old
// zoom actions after a large move or a direction reversal.
pinchZoomRemainder %= PINCH_STEP_PX;
}
}
pinchLastDistance = currDist; // Always update baseline to avoid stale deltas
pinchLastDistance = currDist;
if (twoFingerGestureMode == TWO_FINGER_GESTURE_PAN) {
String twoFingerDragAction = gestureConfig.getTwoFingerDragAction();
if (isClickDragAction(twoFingerDragAction)) {
@@ -627,14 +551,11 @@ public final class TouchscreenGestures {
private void handleTsPointerUp(MotionEvent event) {
cancelTwoFingerHoldTimer();
if (multiFingerMovementExceeded(event)) twoFingerTapPossible = false;
// Two-finger hold release
if (twoFingerHoldTriggered) {
twoFingerHoldActionHeld = releaseHoldAction(twoFingerHoldActionHeld, gestureConfig.getTwoFingerHoldAction());
twoFingerHoldTriggered = false;
}
// Two-finger tap detection
else if (twoFingerTapPossible && !twoFingerDragging && gestureConfig.getTwoFingerTapEnabled()) {
// Move cursor to midpoint between the two fingers
float midX = (twoFingerLastX0 + twoFingerLastX1) / 2f;
float midY = (twoFingerLastY0 + twoFingerLastY1) / 2f;
queueTapClick(gestureConfig.getTwoFingerTapAction(), midX, midY);
@@ -652,7 +573,6 @@ public final class TouchscreenGestures {
reclassifyPinchDelta = 0;
reclassifyPanDelta = 0;
twoFingerLockTime = 0;
// Suppress single-finger tap/drag when last finger lifts after any 2F gesture
movedBeyondTapThreshold = true;
multiFingerGestureUsed = true;
}
@@ -661,7 +581,6 @@ public final class TouchscreenGestures {
cancelLongPressTimer();
if (longPressTriggered) {
// Release the long-press action
longPressActionHeld = releaseHoldAction(longPressActionHeld, gestureConfig.getLongPressAction());
longPressTriggered = false;
return;
@@ -671,7 +590,6 @@ public final class TouchscreenGestures {
float y = event.getY(actionIndex);
if (isDragging && dragButtonPressed) {
// End drag (release any held drag buttons/keys)
releaseDragInput();
dragButtonPressed = false;
isDragging = false;
@@ -685,8 +603,6 @@ public final class TouchscreenGestures {
? gestureConfig.getLongPressDelay() : ViewConfiguration.getLongPressTimeout();
if (SystemClock.uptimeMillis() - singleFingerDownTime < tapLimit
&& Math.hypot(x - doubleTapAnchorX, y - doubleTapAnchorY) < doubleTapSlop) {
// A normal left tap already supplied the first click. Other
// single-tap mappings need a complete synthesized double click.
boolean firstTapClicked = gestureConfig.getTapEnabled()
&& TouchGestureConfig.ACTION_LEFT_CLICK.equals(gestureConfig.getTapAction());
int clicks = firstTapClicked ? 1 : 2;
@@ -697,26 +613,21 @@ public final class TouchscreenGestures {
}
}
// Two-finger tap already sent its click on POINTER_UP — skip the tap on UP
if (twoFingerTapFired) {
twoFingerTapFired = false;
return;
}
// Three-finger tap already sent its click — skip the tap on UP
if (threeFingerTapFired) {
threeFingerTapFired = false;
return;
}
// Simple tap — only if finger stayed within tap tolerance
if (gestureConfig.getTapEnabled() && !movedBeyondTapThreshold) {
queueTapClick(gestureConfig.getTapAction(), x, y);
notifyGesture(Gesture.TAP);
}
// Record for double-tap detection (even if tap itself is disabled,
// so double-tap can still prime from single touch-ups)
if (!movedBeyondTapThreshold && (gestureConfig.getTapEnabled() || gestureConfig.getDoubleTapEnabled())) {
lastTapTime = SystemClock.uptimeMillis();
lastTapX = x;
@@ -776,13 +687,10 @@ public final class TouchscreenGestures {
cancelLongPressTimer();
cancelDrag();
cancelTwoFingerHoldTimer();
// If a two-finger hold already injected its action, release it before
// transitioning so the held button/key doesn't stay down.
if (twoFingerHoldTriggered) {
twoFingerHoldActionHeld = releaseHoldAction(twoFingerHoldActionHeld, gestureConfig.getTwoFingerHoldAction());
twoFingerHoldTriggered = false;
}
// Clean up two-finger state
releaseDragInput();
resetSmallMovement();
twoFingerDragging = false;
@@ -797,7 +705,6 @@ public final class TouchscreenGestures {
threeFingerDragOffsetX = threeFingerDragOffsetY = 0f;
threeFingerDownTime = SystemClock.uptimeMillis();
// Compute midpoint of three gesture fingers
if (gestureOwnedPointerIds.size() >= 3) {
float sumX = 0, sumY = 0;
int validCount = 0;
@@ -809,13 +716,12 @@ public final class TouchscreenGestures {
validCount++;
}
}
if (validCount < 3) return; // Can't proceed without all 3 pointers
if (validCount < 3) return;
threeFingerLastMidX = sumX / 3f;
threeFingerLastMidY = sumY / 3f;
recordMultiFingerOrigins(event, 3);
}
// Schedule three-finger hold
if (gestureConfig.getThreeFingerHoldEnabled()) {
threeFingerHoldRunnable = () -> {
threeFingerHoldTriggered = true;
@@ -831,8 +737,6 @@ public final class TouchscreenGestures {
private void handleTsThreeFingerMove(MotionEvent event) {
if (gestureFingerCount < 3 || gestureOwnedPointerIds.size() < 3) return;
// If a three-finger hold has already fired, ignore subsequent jitter so
// it can't lock into a pan gesture mid-hold.
if (threeFingerHoldTriggered) return;
if (multiFingerMovementExceeded(event)) {
threeFingerTapPossible = false;
@@ -877,8 +781,6 @@ public final class TouchscreenGestures {
}
if (threeFingerGestureMode == THREE_FINGER_GESTURE_PAN) {
// Once recognized, retain small mouse movements. Keyboard panning
// accumulates its own direction threshold in performKeyPan.
String threeFingerDragAction = gestureConfig.getThreeFingerDragAction();
if (isClickDragAction(threeFingerDragAction)) {
if (useRelativeMouseDragMovement()) {
@@ -919,7 +821,6 @@ public final class TouchscreenGestures {
multiFingerStartCount = 0;
resetSmallMovement();
threeFingerGestureMode = THREE_FINGER_GESTURE_NONE;
// Suppress single-finger tap/drag when last finger lifts after any 3F gesture
movedBeyondTapThreshold = true;
multiFingerGestureUsed = true;
}
@@ -966,7 +867,6 @@ public final class TouchscreenGestures {
}
x /= 3f;
y /= 3f;
// Replacing a tracked finger changes the centroid without moving the cursor.
if (threeFingerDragging) {
threeFingerDragOffsetX += threeFingerLastMidX - x;
threeFingerDragOffsetY += threeFingerLastMidY - y;
@@ -1030,9 +930,6 @@ public final class TouchscreenGestures {
private void startPendingTapClick() {
if (delayedPress != null || pendingTapPress != null || pendingTapClicks.isEmpty()) return;
TapClick click = pendingTapClicks.peekFirst();
// Games that poll button state need an observable UP interval too.
// Reuse the first tap's location: normal finger drift must not turn
// this into two clicks on different targets or a tiny drag.
long delay = Math.max(0, CLICK_DELAYED_TIME - (SystemClock.uptimeMillis() - lastInputReleaseTime));
pendingTapPress = () -> {
pendingTapPress = null;
@@ -1224,9 +1121,6 @@ public final class TouchscreenGestures {
pressButton(MouseButton.BUTTON_MIDDLE);
twoFingerMiddleButtonDown = true;
}
// Pan from the client's current pointer. Games can recenter the mouse
// when the middle button goes down; replaying our old absolute touch
// anchor after that warp causes a large, unintended camera movement.
moveCursorByRelativeDelta(dx, dy);
}
@@ -1287,10 +1181,6 @@ public final class TouchscreenGestures {
}
private void performKeyPan(float dx, float dy, Integer leftKey, Integer rightKey, Integer upKey, Integer downKey) {
// When fingers are actively moving, update key states to match the
// swipe direction. When fingers stop moving but stay on screen,
// keep the current keys held — movement continues until finger-up
// calls releasePanKeys().
keyPanRemainderX = accumulateSignedMovement(keyPanRemainderX, dx);
keyPanRemainderY = accumulateSignedMovement(keyPanRemainderY, dy);
@@ -1300,9 +1190,6 @@ public final class TouchscreenGestures {
dy = keyPanRemainderY;
keyPanRemainderX = keyPanRemainderY = 0f;
// --- Significant movement detected: update each axis ---
// Horizontal: determine desired state from this frame's delta
boolean wantLeft = dx < -3f;
boolean wantRight = dx > 3f;
@@ -1311,7 +1198,6 @@ public final class TouchscreenGestures {
if (wantLeft && !panKeyLeft) { pressKey(leftKey); panKeyLeft = true; panLeftKey = leftKey; }
if (wantRight && !panKeyRight) { pressKey(rightKey); panKeyRight = true; panRightKey = rightKey; }
// Vertical: determine desired state from this frame's delta
boolean wantUp = dy < -3f;
boolean wantDown = dy > 3f;
@@ -6,7 +6,6 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
/** What SteamVR sees for the game pad. The driver reads the file once, when SteamVR starts. */
object VrControllers {
enum class Emulate(val key: String) { OFF("off"), INDEX("index"), TOUCH("touch"), VIVE("vive") }
@@ -46,7 +45,6 @@ object VrControllers {
fun encode(settings: Settings): String =
"emulate=${settings.emulate.key}\nsticks=${if (settings.sticksMoveHands) "hands" else "game"}\n"
/** Writes into the session's runtime dir, which the guest sees as /run/droiddeck. */
fun publish(context: Context) {
runCatching {
val dir = File(context.filesDir, ".wayland-rt").apply { mkdirs() }