diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 306e459b33..2e346f6b83 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -254,8 +254,6 @@ jobs: - name: Build libfakeinput.so and libblsession.so (glibc aarch64) if: steps.preloads.outputs.cache-hit != 'true' - env: - GH_TOKEN: ${{ github.token }} run: | set -euo pipefail sudo apt-get -o Dir::Etc::sourcelist=sources.list.d/ubuntu.sources \ @@ -292,7 +290,7 @@ jobs: done if [ -f tools/gamescope/release.env ]; then . tools/gamescope/release.env - gh release download "${GAMESCOPE_TAG}" -R "${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}" -p gamescope.tzst -O gamescope.tzst + curl -fsSL --retry 3 -o gamescope.tzst "https://github.com/${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}/releases/download/${GAMESCOPE_TAG}/gamescope.tzst" echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c - tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D" test -f "$D/usr/local/bin/gamescope" @@ -395,18 +393,17 @@ jobs: ls -l app/src/main/assets/linuxfs/x86_64 app/src/main/assets/linuxfs/i386 - name: Bundle the droiddeck-esync packs - env: - GH_TOKEN: ${{ github.token }} run: | set -euo pipefail if [ -f tools/droiddeck-esync/release.env ]; then . tools/droiddeck-esync/release.env - gh release download "$SYNC_BUNDLE_TAG" -R "$SYNC_BUNDLE_REPO" -p "$SYNC_BUNDLE_ASSET" -O sync-bundle.tzst + release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}" + curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET" echo "$SYNC_BUNDLE_SHA256 sync-bundle.tzst" | sha256sum -c - mkdir -p app/src/main/assets/droiddeck-esync tar --use-compress-program=unzstd -xf sync-bundle.tzst -C app/src/main/assets/droiddeck-esync rm sync-bundle.tzst - gh release download "$SYNC_BUNDLE_TAG" -R "$SYNC_BUNDLE_REPO" -p index.json -O sync-index.json + curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json" revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' sync-index.json) for id in $revoked; do if [ -e "app/src/main/assets/droiddeck-esync/packs/$id.tzst" ]; then diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 014c0d1910..99bbbef024 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -2593,7 +2593,11 @@ static void pointer_input(double x, double y, int relative, uint32_t button, int uint32_t t = now_ms(); pointer_focus(target->resource, fx, fy); - if (!(k && k->is_lock)) + // A button-only input must not replay a cached absolute position. A game + // may have warped its cursor since the last motion (before taking lock, + // or while releasing it), so that replay can become an unintended pan. + // Absolute touch events still carry their position, including on clicks. + if (!(k && k->is_lock) && (!relative || dx != 0 || dy != 0)) for_each_pointer_of(client, sp) wl_pointer_send_motion(sp->ptr, t, fx, fy); send_relative_motion(client, dx, dy); for_each_pointer_of(client, sp) { diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 8f4de11678..510fd7795f 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -81,6 +81,7 @@ import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenDisplays import com.droiddeck.launcher.input.SecondScreenMode import com.droiddeck.launcher.input.TouchpadGestures +import com.droiddeck.launcher.input.TouchscreenGestures import com.droiddeck.launcher.input.ScrollTouchGestures import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.LoadingState @@ -191,6 +192,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private lateinit var touchpad: TouchpadGestures private lateinit var directTouchHold: DirectTouchHold private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap + private lateinit var touchscreenGestures: TouchscreenGestures + private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig() + private var gestureGame: String? = null + private var gestureSettingsOpen by mutableStateOf(false) + private var recognizedGesture by mutableStateOf(null) + private var gesturePointerX = 0f + private var gesturePointerY = 0f + private var gesturePointerReady = false + private val clearRecognizedGesture = Runnable { recognizedGesture = null } + private val gestureKeysDown = mutableSetOf() private lateinit var scrollTouch: ScrollTouchGestures private lateinit var padMouse: PadMouse @Volatile private var padMouseOn = false @@ -211,6 +222,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private val pointerLockListener = WaylandCompositor.PointerLockListener { locked, _, _ -> uiHandler.post { if (pointerLocked == locked) return@post + gesturePointerReady = false pointerLocked = locked Log.i(TAG, "pointer lock " + if (locked) "taken by a program" else "released") padMouseCheckedAt = 0L @@ -489,6 +501,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { WaylandCompositor.nativeSendTouch(3, -1, 0, 0) } threeFingerTap = com.droiddeck.launcher.input.ThreeFingerTap(PointerGestures.slop(this) * 2) + touchscreenGestures = TouchscreenGestures( + ViewConfiguration.get(this).scaledTouchSlop.toFloat(), gestureOutput, + ) + refreshGestureConfig() + // A real touch target lets FrameLayout split fingers between the + // game surface and on-screen buttons, in either finger-down order. + root.isMotionEventSplittingEnabled = true + surfaceView.setOnTouchListener { _, event -> + routedTouchMode == SessionPrefs.TOUCH_GESTURES && onTouchEvent(event) + } padMouse = PadMouse(padMouseListener) bridge.setTouchRoute(object : PadBridge.TouchRoute { override fun active(): Boolean = if (Looper.myLooper() == Looper.getMainLooper()) padMouseMode() else padMouseOn @@ -648,6 +670,32 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK)) }, ) + LaunchedEffect(AgentGuest.focusRevision) { + val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { + if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" } + else { + val snapshot = AgentGuest.focus(this@SessionActivity) + val focused = snapshot?.optLong("focusedApp")?.takeIf { it > 0 && it != 769L } + val windows = snapshot?.optJSONArray("focusableApps") + focused?.toString() ?: windows?.let { values -> + (0 until values.length()).map { values.optLong(it) } + .filter { it > 0 && it != 769L }.distinct().singleOrNull()?.toString() + } + } + } + if (nextGame != gestureGame) { gestureGame = nextGame; refreshGestureConfig() } + } + LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) { + if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) { + cancelTouchGestures() + } + } + com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture) + if (gestureSettingsOpen) com.droiddeck.launcher.ui.TouchGestureDialog( + game = gestureGame, + onDismiss = { gestureSettingsOpen = false }, + onSaved = { gestureSettingsOpen = false; refreshGestureConfig() }, + ) androidx.compose.runtime.LaunchedEffect(drawerOpen) { if (drawerOpen) { syncLossless() @@ -823,6 +871,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { SessionService.suspendPolicyChanged(this@SessionActivity) }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, + onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, onSecondScreenMode = ::selectSecondScreenMode, onSecondScreenDisplay = ::selectSecondScreenDisplay, @@ -1543,6 +1592,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { surfaceW = width surfaceH = height if (resized) { + cancelTouchGestures() Log.i(TAG, "surface resized to ${width}x$height - rebinding the compositor") CompositorHost.resize(holder.surface) { applyFrameGen() } followWindow(width, height) @@ -1577,6 +1627,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { super.onConfigurationChanged(newConfig) + cancelTouchGestures() applyFollowOrientation(newConfig) applyUnfoldedControls() } @@ -1585,12 +1636,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // Hiding the phone surface after a handoff delivers a late destruction // callback. It must not reset the new output's size or attachment. if (holder !== outputHolder()) return + cancelTouchGestures() surfaceW = 0 surfaceH = 0 glassesOutputActive = false CompositorHost.detach(holder.surface) } + private fun cancelTouchGestures() { + if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel() + if (::touchpad.isInitialized) touchpad.cancel() + if (::scrollTouch.isInitialized) scrollTouch.cancel() + scrollTouchGesture = false + gesturePointerReady = false + } + private fun panelBounds(): android.graphics.Rect = if (Build.VERSION.SDK_INT >= 30) { windowManager.maximumWindowMetrics.bounds } else { @@ -1992,6 +2052,55 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { super.dispatchKeyEvent(event) } + private fun refreshGestureConfig() { + gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame) + if (::touchscreenGestures.isInitialized) touchscreenGestures.configure(gestureConfig) + gesturePointerReady = false + recognizedGesture = null + } + + private val gestureOutput = object : TouchscreenGestures.Output { + override fun moveTo(x: Float, y: Float) { + val rect = drawnRect() ?: return + if (pointerLocked) { + if (gesturePointerReady) moveBy(x - gesturePointerX, y - gesturePointerY, true) + } else movePointer(x, y) + gesturePointerX = if (pointerLocked) x else x.coerceIn(rect.left, rect.right) + gesturePointerY = if (pointerLocked) y else y.coerceIn(rect.top, rect.bottom) + gesturePointerReady = true + cursorVisible = false + } + override fun moveBy(dx: Float, dy: Float, relative: Boolean) { + val rect = drawnRect() ?: return + if (relative || pointerLocked) { + val scale = SessionState.outputSize.first / rect.width() + WaylandCompositor.sendPointerDelta(dx * scale, dy * scale) + } else moveTo(gesturePointerX + dx, gesturePointerY + dy) + } + override fun button(code: Int, down: Boolean) { + WaylandCompositor.nativeSendSceneInput(3, code, if (down) 1 else 0) + } + override fun prepareRelativePan() { + if (pointerLocked) return + val rect = drawnRect() ?: return + // Gamescope retains the last absolute position while a game can warp + // its own cursor to the center. Its first unlocked motion must start + // from that same origin, before the game switches to pointer lock. + moveTo(rect.centerX(), rect.centerY()) + } + override fun key(code: Int, down: Boolean) { + if (down) gestureKeysDown.add(code) else gestureKeysDown.remove(code) + if (code !in guestKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) + } + override fun wheel(steps: Int) { WaylandCompositor.nativeSendSceneInput(4, steps, 0) } + override fun showKeyboard() { uiHandler.post { touchscreenGestures.cancel(); togglePcKeyboard() } } + override fun gesture(gesture: TouchscreenGestures.Gesture) { + recognizedGesture = gesture + uiHandler.removeCallbacks(clearRecognizedGesture) + uiHandler.postDelayed(clearRecognizedGesture, 1200) + } + } + private val pointerListener = object : PointerGestures.Listener { override fun onMove(x: Float, y: Float) { if (pointerLocked) moveLockedPointer(x, y) else movePointer(x, y) @@ -2282,6 +2391,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { if (options == null || steamTouchControls?.visibility != View.VISIBLE) return SessionPrefs.touchMode(this) return when { options.inputMode == com.droiddeck.launcher.input.SteamTouchConfig.INPUT_CONTROLLER -> SessionPrefs.TOUCH_OFF + SessionPrefs.touchMode(this) == SessionPrefs.TOUCH_GESTURES -> SessionPrefs.TOUCH_GESTURES options.mouseMode == com.droiddeck.launcher.input.SteamTouchConfig.MOUSE_RELATIVE -> SessionPrefs.TOUCH_PAD else -> SessionPrefs.TOUCH_DIRECT } @@ -2294,6 +2404,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { touchpad.sensitivity = 1.15f * speed } if (next == routedTouchMode) return + if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel() + gesturePointerReady = false if (::touchpad.isInitialized) touchpad.cancel() if (::directTouchHold.isInitialized) directTouchHold.cancel() if (::scrollTouch.isInitialized) scrollTouch.cancel() @@ -2330,6 +2442,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onTouchEvent(event: MotionEvent): Boolean { if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE)) return onMouse(event) + if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) return true + if (routedTouchMode == SessionPrefs.TOUCH_GESTURES) { + if (event.actionMasked == MotionEvent.ACTION_DOWN) gesturePointerReady = false + return touchscreenGestures.onTouch(event) + } if (event.actionMasked == MotionEvent.ACTION_DOWN) { scrollTouchGesture = scrollTouchMode() scrollRestX = 0f @@ -2561,7 +2678,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private fun sendGuestKey(code: Int, down: Boolean) { if (down && pipUi) return if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) - WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) + if (down || code !in gestureKeysDown) WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) } private fun pipBounds(): android.graphics.Rect { @@ -2716,7 +2833,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onPause() { if (runtimeRemovalBlocked) { super.onPause(); return } sessionClipboard.stop() + if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel() + if (::touchpad.isInitialized) touchpad.cancel() if (::directTouchHold.isInitialized) directTouchHold.cancel() + uiHandler.removeCallbacks(clearRecognizedGesture) + gestureSettingsOpen = false drawerOpen = false pcKeyboardOpen = false achievementsOpen = false @@ -3092,6 +3213,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { super.onWindowFocusChanged(hasFocus) if (!hasFocus && ::padMouse.isInitialized) padMouse.reset() if (runtimeRemovalBlocked) return + if (!hasFocus) { + if (::touchscreenGestures.isInitialized) touchscreenGestures.cancel() + if (::touchpad.isInitialized) touchpad.cancel() + } if (hasFocus && !pipUi) { goFullscreen() refreshClipboard() diff --git a/app/src/main/java/com/droiddeck/launcher/input/GestureKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/GestureKeys.kt new file mode 100644 index 0000000000..2efdb940b2 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/GestureKeys.kt @@ -0,0 +1,111 @@ +/* + * SPDX-License-Identifier: GPL-3.0 + * Modified for DroidDeck on 2026-10-15. + */ +package com.droiddeck.launcher.input + +object GestureKeys { + val codes: Map = linkedMapOf( + "ESC" to 1, + "1" to 2, + "2" to 3, + "3" to 4, + "4" to 5, + "5" to 6, + "6" to 7, + "7" to 8, + "8" to 9, + "9" to 10, + "0" to 11, + "MINUS" to 12, + "EQUAL" to 13, + "BKSP" to 14, + "TAB" to 15, + "Q" to 16, + "W" to 17, + "E" to 18, + "R" to 19, + "T" to 20, + "Y" to 21, + "U" to 22, + "I" to 23, + "O" to 24, + "P" to 25, + "BRACKET_LEFT" to 26, + "BRACKET_RIGHT" to 27, + "ENTER" to 28, + "CTRL_L" to 29, + "A" to 30, + "S" to 31, + "D" to 32, + "F" to 33, + "G" to 34, + "H" to 35, + "J" to 36, + "K" to 37, + "L" to 38, + "SEMICOLON" to 39, + "APOSTROPHE" to 40, + "GRAVE" to 41, + "SHIFT_L" to 42, + "BACKSLASH" to 43, + "Z" to 44, + "X" to 45, + "C" to 46, + "V" to 47, + "B" to 48, + "N" to 49, + "M" to 50, + "COMMA" to 51, + "PERIOD" to 52, + "SLASH" to 53, + "SHIFT_R" to 54, + "KP_MULTIPLY" to 55, + "ALT_L" to 56, + "SPACE" to 57, + "CAPS_LOCK" to 58, + "F1" to 59, + "F2" to 60, + "F3" to 61, + "F4" to 62, + "F5" to 63, + "F6" to 64, + "F7" to 65, + "F8" to 66, + "F9" to 67, + "F10" to 68, + "NUM_LOCK" to 69, + "SCROLL_LOCK" to 70, + "KP_7" to 71, + "KP_8" to 72, + "KP_9" to 73, + "KP_SUBTRACT" to 74, + "KP_4" to 75, + "KP_5" to 76, + "KP_6" to 77, + "KP_ADD" to 78, + "KP_1" to 79, + "KP_2" to 80, + "KP_3" to 81, + "KP_0" to 82, + "KP_DEL" to 83, + "F11" to 87, + "F12" to 88, + "KP_ENTER" to 96, + "CTRL_R" to 97, + "KP_DIVIDE" to 98, + "PRTSCN" to 99, + "ALT_R" to 100, + "HOME" to 102, + "UP" to 103, + "PRIOR" to 104, + "LEFT" to 105, + "RIGHT" to 106, + "END" to 107, + "DOWN" to 108, + "NEXT" to 109, + "INSERT" to 110, + "DEL" to 111, + ) + @JvmStatic fun code(name: String): Int? = codes[name] +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/GesturePrefs.kt b/app/src/main/java/com/droiddeck/launcher/input/GesturePrefs.kt new file mode 100644 index 0000000000..b8be5bf542 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/GesturePrefs.kt @@ -0,0 +1,24 @@ +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) + + fun hasOverride(context: Context, game: String): Boolean = prefs(context).contains("game.$game") + + fun read(context: Context, game: String? = null): TouchGestureConfig { + val p = prefs(context) + val json = game?.let { p.getString("game.$it", null) } ?: p.getString("default", null) + return if (json == null) TouchGestureConfig() else TouchGestureConfig.fromJson(json) + } + + fun save(context: Context, game: String?, config: TouchGestureConfig) { + prefs(context).edit().putString(game?.let { "game.$it" } ?: "default", config.toJson()).apply() + } + + fun clear(context: Context, game: String?) { + prefs(context).edit().remove(game?.let { "game.$it" } ?: "default").apply() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/TouchGestureConfig.kt b/app/src/main/java/com/droiddeck/launcher/input/TouchGestureConfig.kt new file mode 100644 index 0000000000..8021536a9a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/TouchGestureConfig.kt @@ -0,0 +1,226 @@ +/* + * SPDX-License-Identifier: GPL-3.0 + * Modified for DroidDeck on 2026-10-15. + */ +package com.droiddeck.launcher.input + +import org.json.JSONObject + +data class TouchGestureConfig( + val tapEnabled: Boolean = true, + val tapAction: String = ACTION_LEFT_CLICK, + val dragEnabled: Boolean = true, + val dragAction: String = PAN_LEFT_CLICK_DRAG, + val longPressEnabled: Boolean = false, + val longPressAction: String = ACTION_RIGHT_CLICK, + val longPressMouseBehavior: String = MOUSE_BEHAVIOR_HOLD, + val longPressDelay: Int = DEFAULT_DELAY_MS, + val doubleTapEnabled: Boolean = true, + val doubleTapDelay: Int = DEFAULT_DELAY_MS, + val twoFingerDragEnabled: Boolean = true, + val twoFingerDragAction: String = PAN_ARROW_KEYS, + val pinchEnabled: Boolean = true, + val pinchAction: String = ZOOM_SCROLL_WHEEL, + val twoFingerTapEnabled: Boolean = true, + val twoFingerTapAction: String = ACTION_RIGHT_CLICK, + val twoFingerHoldEnabled: Boolean = true, + val twoFingerHoldAction: String = ACTION_MIDDLE_CLICK, + val twoFingerHoldMouseBehavior: String = MOUSE_BEHAVIOR_HOLD, + val twoFingerHoldDelay: Int = DEFAULT_DELAY_MS, + val threeFingerTapEnabled: Boolean = true, + val threeFingerTapAction: String = ACTION_SHOW_KEYBOARD, + val threeFingerDragEnabled: Boolean = false, + val threeFingerDragAction: String = PAN_ARROW_KEYS, + val threeFingerHoldEnabled: Boolean = true, + val threeFingerHoldAction: String = ACTION_KEY_ESC, + val threeFingerHoldMouseBehavior: String = MOUSE_BEHAVIOR_HOLD, + val threeFingerHoldDelay: Int = DEFAULT_DELAY_MS, + val showGestureDebugOverlay: Boolean = false, + val gestureThreshold: Int = DEFAULT_GESTURE_THRESHOLD, + val mouseDragMovementMode: String = MOUSE_DRAG_MOVEMENT_DIRECT, +) { + + fun toJson(): String { + return JSONObject().apply { + put(KEY_TAP_ENABLED, tapEnabled) + put(KEY_TAP_ACTION, tapAction) + put(KEY_DRAG_ENABLED, dragEnabled) + put(KEY_DRAG_ACTION, dragAction) + put(KEY_LONG_PRESS_ENABLED, longPressEnabled) + put(KEY_LONG_PRESS_ACTION, longPressAction) + put(KEY_LONG_PRESS_MOUSE_BEHAVIOR, longPressMouseBehavior) + put(KEY_LONG_PRESS_DELAY, longPressDelay) + put(KEY_DOUBLE_TAP_ENABLED, doubleTapEnabled) + put(KEY_DOUBLE_TAP_DELAY, doubleTapDelay) + put(KEY_TWO_FINGER_DRAG_ENABLED, twoFingerDragEnabled) + put(KEY_TWO_FINGER_DRAG_ACTION, twoFingerDragAction) + put(KEY_PINCH_ENABLED, pinchEnabled) + put(KEY_PINCH_ACTION, pinchAction) + put(KEY_TWO_FINGER_TAP_ENABLED, twoFingerTapEnabled) + put(KEY_TWO_FINGER_TAP_ACTION, twoFingerTapAction) + put(KEY_TWO_FINGER_HOLD_ENABLED, twoFingerHoldEnabled) + put(KEY_TWO_FINGER_HOLD_ACTION, twoFingerHoldAction) + put(KEY_TWO_FINGER_HOLD_MOUSE_BEHAVIOR, twoFingerHoldMouseBehavior) + put(KEY_TWO_FINGER_HOLD_DELAY, twoFingerHoldDelay) + put(KEY_THREE_FINGER_TAP_ENABLED, threeFingerTapEnabled) + put(KEY_THREE_FINGER_TAP_ACTION, threeFingerTapAction) + put(KEY_THREE_FINGER_DRAG_ENABLED, threeFingerDragEnabled) + put(KEY_THREE_FINGER_DRAG_ACTION, threeFingerDragAction) + put(KEY_THREE_FINGER_HOLD_ENABLED, threeFingerHoldEnabled) + put(KEY_THREE_FINGER_HOLD_ACTION, threeFingerHoldAction) + put(KEY_THREE_FINGER_HOLD_MOUSE_BEHAVIOR, threeFingerHoldMouseBehavior) + put(KEY_THREE_FINGER_HOLD_DELAY, threeFingerHoldDelay) + put(KEY_SHOW_GESTURE_DEBUG_OVERLAY, showGestureDebugOverlay) + put(KEY_GESTURE_THRESHOLD, gestureThreshold) + put(KEY_MOUSE_DRAG_MOVEMENT_MODE, mouseDragMovementMode) + }.toString() + } + + companion object { + const val DEFAULT_DELAY_MS = 300 + const val DEFAULT_GESTURE_THRESHOLD = 40 + const val ACTION_LEFT_CLICK = "left_click" + const val ACTION_RIGHT_CLICK = "right_click" + const val ACTION_MIDDLE_CLICK = "middle_click" + + const val MOUSE_BEHAVIOR_HOLD = "hold" + const val MOUSE_BEHAVIOR_CLICK = "click" + + const val MOUSE_DRAG_MOVEMENT_DIRECT = "direct" + const val MOUSE_DRAG_MOVEMENT_RELATIVE = "relative" + const val ACTION_SHOW_KEYBOARD = "show_keyboard" + const val ACTION_KEY_ESC = "key_ESC" + const val ACTION_KEY_TILDE = "key_TILDE" + const val PAN_WASD = "wasd" + const val PAN_INVERTED_WASD = "inverted_wasd" + const val PAN_ARROW_KEYS = "arrow_keys" + const val PAN_INVERTED_ARROW_KEYS = "inverted_arrow_keys" + const val PAN_MIDDLE_MOUSE = "middle_mouse_pan" + const val PAN_INVERTED_MIDDLE_MOUSE = "inverted_middle_mouse_pan" + const val PAN_LEFT_CLICK_DRAG = "left_click_drag" + const val PAN_RIGHT_CLICK_DRAG = "right_click_drag" + const val ZOOM_SCROLL_WHEEL = "scroll_wheel" + const val ZOOM_PLUS_MINUS = "plus_minus" + const val ZOOM_PAGE_UP_DOWN = "page_up_down" + private const val KEY_TAP_ENABLED = "tapEnabled" + private const val KEY_TAP_ACTION = "tapAction" + private const val KEY_DRAG_ENABLED = "dragEnabled" + private const val KEY_DRAG_ACTION = "dragAction" + private const val KEY_LONG_PRESS_ENABLED = "longPressEnabled" + private const val KEY_LONG_PRESS_ACTION = "longPressAction" + private const val KEY_LONG_PRESS_MOUSE_BEHAVIOR = "longPressMouseBehavior" + private const val KEY_LONG_PRESS_DELAY = "longPressDelay" + 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" + private const val KEY_TWO_FINGER_DRAG_ACTION = "twoFingerDragAction" + private const val KEY_PINCH_ENABLED = "pinchEnabled" + private const val KEY_PINCH_ACTION = "pinchAction" + private const val KEY_TWO_FINGER_TAP_ENABLED = "twoFingerTapEnabled" + private const val KEY_TWO_FINGER_TAP_ACTION = "twoFingerTapAction" + private const val KEY_TWO_FINGER_HOLD_ENABLED = "twoFingerHoldEnabled" + private const val KEY_TWO_FINGER_HOLD_ACTION = "twoFingerHoldAction" + private const val KEY_TWO_FINGER_HOLD_MOUSE_BEHAVIOR = "twoFingerHoldMouseBehavior" + private const val KEY_TWO_FINGER_HOLD_DELAY = "twoFingerHoldDelay" + private const val KEY_THREE_FINGER_TAP_ENABLED = "threeFingerTapEnabled" + private const val KEY_THREE_FINGER_TAP_ACTION = "threeFingerTapAction" + private const val KEY_THREE_FINGER_DRAG_ENABLED = "threeFingerDragEnabled" + private const val KEY_THREE_FINGER_DRAG_ACTION = "threeFingerDragAction" + private const val KEY_THREE_FINGER_HOLD_ENABLED = "threeFingerHoldEnabled" + private const val KEY_THREE_FINGER_HOLD_ACTION = "threeFingerHoldAction" + private const val KEY_THREE_FINGER_HOLD_MOUSE_BEHAVIOR = "threeFingerHoldMouseBehavior" + private const val KEY_THREE_FINGER_HOLD_DELAY = "threeFingerHoldDelay" + private const val KEY_SHOW_GESTURE_DEBUG_OVERLAY = "showGestureDebugOverlay" + private const val KEY_GESTURE_THRESHOLD = "gestureThreshold" + private const val KEY_MOUSE_DRAG_MOVEMENT_MODE = "mouseDragMovementMode" + + private fun fallbackDefaults(): TouchGestureConfig = TouchGestureConfig( + twoFingerHoldEnabled = false, + threeFingerTapEnabled = false, + threeFingerHoldEnabled = false, + ) + + fun fromJson(json: String?): TouchGestureConfig { + if (json.isNullOrBlank()) return fallbackDefaults() + return try { + val obj = JSONObject(json) + TouchGestureConfig( + tapEnabled = obj.optBoolean(KEY_TAP_ENABLED, true), + tapAction = obj.optString(KEY_TAP_ACTION, ACTION_LEFT_CLICK), + dragEnabled = obj.optBoolean(KEY_DRAG_ENABLED, true), + dragAction = obj.optString(KEY_DRAG_ACTION, PAN_LEFT_CLICK_DRAG), + longPressEnabled = obj.optBoolean(KEY_LONG_PRESS_ENABLED, false), + longPressAction = obj.optString(KEY_LONG_PRESS_ACTION, ACTION_RIGHT_CLICK), + longPressMouseBehavior = normalizeMouseBehavior( + obj.optString(KEY_LONG_PRESS_MOUSE_BEHAVIOR, MOUSE_BEHAVIOR_HOLD) + ), + longPressDelay = obj.optInt(KEY_LONG_PRESS_DELAY, DEFAULT_DELAY_MS), + doubleTapEnabled = obj.optBoolean(KEY_DOUBLE_TAP_ENABLED, true), + doubleTapDelay = obj.optInt(KEY_DOUBLE_TAP_DELAY, DEFAULT_DELAY_MS), + twoFingerDragEnabled = obj.optBoolean(KEY_TWO_FINGER_DRAG_ENABLED, true), + twoFingerDragAction = obj.optString(KEY_TWO_FINGER_DRAG_ACTION, PAN_ARROW_KEYS), + pinchEnabled = obj.optBoolean(KEY_PINCH_ENABLED, true), + pinchAction = obj.optString(KEY_PINCH_ACTION, ZOOM_SCROLL_WHEEL), + twoFingerTapEnabled = obj.optBoolean(KEY_TWO_FINGER_TAP_ENABLED, true), + twoFingerTapAction = obj.optString(KEY_TWO_FINGER_TAP_ACTION, ACTION_RIGHT_CLICK), + twoFingerHoldEnabled = obj.optBoolean(KEY_TWO_FINGER_HOLD_ENABLED, false), + twoFingerHoldAction = obj.optString(KEY_TWO_FINGER_HOLD_ACTION, ACTION_MIDDLE_CLICK), + twoFingerHoldMouseBehavior = normalizeMouseBehavior( + obj.optString(KEY_TWO_FINGER_HOLD_MOUSE_BEHAVIOR, MOUSE_BEHAVIOR_HOLD) + ), + twoFingerHoldDelay = obj.optInt(KEY_TWO_FINGER_HOLD_DELAY, DEFAULT_DELAY_MS), + threeFingerTapEnabled = obj.optBoolean(KEY_THREE_FINGER_TAP_ENABLED, false), + threeFingerTapAction = obj.optString(KEY_THREE_FINGER_TAP_ACTION, ACTION_SHOW_KEYBOARD), + threeFingerDragEnabled = obj.optBoolean(KEY_THREE_FINGER_DRAG_ENABLED, false), + threeFingerDragAction = obj.optString(KEY_THREE_FINGER_DRAG_ACTION, PAN_ARROW_KEYS), + threeFingerHoldEnabled = obj.optBoolean(KEY_THREE_FINGER_HOLD_ENABLED, false), + threeFingerHoldAction = obj.optString(KEY_THREE_FINGER_HOLD_ACTION, ACTION_KEY_ESC), + threeFingerHoldMouseBehavior = normalizeMouseBehavior( + obj.optString(KEY_THREE_FINGER_HOLD_MOUSE_BEHAVIOR, MOUSE_BEHAVIOR_HOLD) + ), + threeFingerHoldDelay = obj.optInt(KEY_THREE_FINGER_HOLD_DELAY, DEFAULT_DELAY_MS), + showGestureDebugOverlay = obj.optBoolean(KEY_SHOW_GESTURE_DEBUG_OVERLAY, false), + gestureThreshold = obj.optInt(KEY_GESTURE_THRESHOLD, DEFAULT_GESTURE_THRESHOLD), + mouseDragMovementMode = normalizeMouseDragMovementMode( + obj.optString(KEY_MOUSE_DRAG_MOVEMENT_MODE, MOUSE_DRAG_MOVEMENT_DIRECT), + ), + ) + } catch (_: Exception) { + fallbackDefaults() + } + } + + private fun normalizeMouseBehavior(value: String): String { + return if (value == MOUSE_BEHAVIOR_CLICK) MOUSE_BEHAVIOR_CLICK else MOUSE_BEHAVIOR_HOLD + } + + private fun normalizeMouseDragMovementMode(mode: String?): String { + return if (mode == MOUSE_DRAG_MOVEMENT_RELATIVE) { + MOUSE_DRAG_MOVEMENT_RELATIVE + } else { + MOUSE_DRAG_MOVEMENT_DIRECT + } + } + + val PAN_ACTIONS = listOf( + PAN_ARROW_KEYS, + PAN_INVERTED_ARROW_KEYS, + PAN_WASD, + PAN_INVERTED_WASD, + PAN_MIDDLE_MOUSE, + PAN_INVERTED_MIDDLE_MOUSE, + PAN_LEFT_CLICK_DRAG, + PAN_RIGHT_CLICK_DRAG, + ) + + val ZOOM_ACTIONS = listOf( + ZOOM_SCROLL_WHEEL, + ZOOM_PLUS_MINUS, + ZOOM_PAGE_UP_DOWN, + ) + + @JvmStatic + fun isMouseButtonAction(action: String?): Boolean = + action == ACTION_LEFT_CLICK || action == ACTION_RIGHT_CLICK || action == ACTION_MIDDLE_CLICK + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/TouchscreenGestures.java b/app/src/main/java/com/droiddeck/launcher/input/TouchscreenGestures.java new file mode 100644 index 0000000000..e71a14cd33 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/TouchscreenGestures.java @@ -0,0 +1,1332 @@ +/* + * SPDX-License-Identifier: GPL-3.0 + * Modified for DroidDeck on 2026-10-15. + */ +package com.droiddeck.launcher.input; + +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; +import android.view.MotionEvent; +import android.view.ViewConfiguration; +import java.util.ArrayList; +import java.util.ArrayDeque; +import java.util.LinkedHashMap; +import java.util.Map; + +public final class TouchscreenGestures { + public enum Gesture { + TAP, DRAG, LONG_PRESS, DOUBLE_TAP, + TWO_FINGER_TAP, TWO_FINGER_DRAG, TWO_FINGER_HOLD, PINCH, + THREE_FINGER_TAP, THREE_FINGER_DRAG, THREE_FINGER_HOLD + } + + public interface Output { + void moveTo(float x, float y); + void moveBy(float dx, float dy, boolean relative); + void button(int code, boolean down); + 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) {} + } + private final Handler handler = new Handler(Looper.getMainLooper()); + private final Output output; + private final float doubleTapSlop; + private TouchGestureConfig gestureConfig = new TouchGestureConfig(); + private static final int CLICK_DELAYED_TIME = 50; + private Runnable delayedPress, pendingHoldClickRelease; + private Runnable pendingTapPress; + private final ArrayDeque pendingTapClicks = new ArrayDeque<>(); + private long lastInputReleaseTime; + private String delayedPressAction, pendingHoldClickReleaseAction; + private final Map keysDown = new LinkedHashMap<>(); + private final Map buttonsDown = new LinkedHashMap<>(); + private boolean leftClickDragButtonDown, rightClickDragButtonDown; + + private static final class TapClick { + final String action; + final int x, y; + TapClick(String action, float x, float y) { + this.action = action; this.x = (int) x; this.y = (int) y; + } + } + + public TouchscreenGestures(float doubleTapSlop, Output output) { + this.output = output; + this.doubleTapSlop = Math.max(1f, doubleTapSlop); + } + public void configure(TouchGestureConfig config) { + cancel(); + gestureConfig = config; + } + public boolean onTouch(MotionEvent event) { return handleGestureTouchscreenEvent(event); } + public void cancel() { + handleTsCancel(); + handler.removeCallbacksAndMessages(null); + for (int code : keysDown.keySet()) output.key(code, false); + for (int code : buttonsDown.keySet()) output.button(code, false); + keysDown.clear(); buttonsDown.clear(); lastTapTime = 0; + } + private void postDelayed(Runnable action, long delay) { handler.postDelayed(action, delay); } + private void removeCallbacks(Runnable action) { handler.removeCallbacks(action); } + private void notifyGesture(Gesture gesture) { + if (gestureConfig.getShowGestureDebugOverlay()) output.gesture(gesture); + } + private void pressKey(int code) { press(keysDown, code, true); } + private void releaseKey(int code) { release(keysDown, code, true); } + private void pressButton(MouseButton button) { press(buttonsDown, button.code, false); } + private void releaseButton(MouseButton button) { release(buttonsDown, button.code, false); } + private void press(Map held, int code, boolean key) { + int count = held.getOrDefault(code, 0); + held.put(code, count + 1); + if (count == 0) { if (key) output.key(code, true); else output.button(code, true); } + } + private void release(Map held, int code, boolean key) { + int count = held.getOrDefault(code, 0); + if (count == 0) return; + if (count > 1) { held.put(code, count - 1); return; } + held.remove(code); + if (key) output.key(code, false); else output.button(code, false); + lastInputReleaseTime = SystemClock.uptimeMillis(); + } + private enum MouseButton { + BUTTON_LEFT(0x110), BUTTON_RIGHT(0x111), BUTTON_MIDDLE(0x112); + 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; + private boolean secondTapCandidate; + 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 + + // 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 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; + private float threeFingerLastMidX, threeFingerLastMidY; + private float threeFingerDragOffsetX, threeFingerDragOffsetY; + private Runnable threeFingerHoldRunnable; + private boolean threeFingerHoldTriggered; + private static final int THREE_FINGER_GESTURE_NONE = 0; + private static final int THREE_FINGER_GESTURE_PAN = 1; + private int threeFingerGestureMode = THREE_FINGER_GESTURE_NONE; + private float accumulatedThreeFingerDelta; + + private boolean handleGestureTouchscreenEvent(MotionEvent event) { + int action = event.getActionMasked(); + int actionIndex = event.getActionIndex(); + int pointerId = event.getPointerId(actionIndex); + + 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; + handleTsDown(event, actionIndex); + 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); + } else if (gestureFingerCount == 3) { + handleTsThreeFingerDown(event); + } + break; + + case MotionEvent.ACTION_MOVE: + if (gestureFingerCount >= 3) { + handleTsThreeFingerMove(event); + } else if (gestureFingerCount >= 2) { + handleTsTwoFingerMove(event); + } else if (gestureFingerCount == 1 && !gestureOwnedPointerIds.isEmpty()) { + int idx = event.findPointerIndex(gestureOwnedPointerIds.get(0)); + if (idx >= 0) handleTsMove(event, idx); + } + break; + + case MotionEvent.ACTION_POINTER_UP: + if (gestureOwnedPointerIds.contains(pointerId)) { + int prevCount = gestureFingerCount; + int removedIndex = gestureOwnedPointerIds.indexOf(pointerId); + 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); + } + } + break; + + case MotionEvent.ACTION_UP: + if (gestureOwnedPointerIds.contains(pointerId)) { + 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) { + handleTsPointerUp(event); + } + handleTsUp(event, actionIndex); + } + // ACTION_UP = last pointer overall — full cleanup + gestureOwnedPointerIds.clear(); + gestureFingerCount = 0; + break; + + case MotionEvent.ACTION_CANCEL: + gestureOwnedPointerIds.clear(); + gestureFingerCount = 0; + cancel(); + break; + } + return true; + } + + private void handleTsDown(MotionEvent event, int actionIndex) { + flushPendingHoldClickRelease(); + + int x = (int) event.getX(actionIndex); + int y = (int) event.getY(actionIndex); + + longPressTriggered = longPressActionHeld = false; + secondTapCandidate = false; + isDragging = false; + dragButtonPressed = false; + movedBeyondTapThreshold = false; + multiFingerGestureUsed = false; + twoFingerDragging = false; + twoFingerTapPossible = false; + twoFingerTapFired = false; + twoFingerMiddleButtonDown = false; + twoFingerGestureMode = TWO_FINGER_GESTURE_NONE; + threeFingerTapPossible = false; + threeFingerDragging = false; + threeFingerTapFired = false; + threeFingerGestureMode = THREE_FINGER_GESTURE_NONE; + 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; + doubleTapAnchorY = lastTapY; + lastTapTime = 0; + } + + if (!secondTapCandidate && delayedPress == null && pendingTapPress == null) moveCursorTo(x, y); + + // Schedule long-press + if (gestureConfig.getLongPressEnabled()) { + longPressRunnable = () -> { + secondTapCandidate = false; + lastTapTime = 0; + longPressTriggered = true; + moveCursorTo((int) touchDownRawX, (int) touchDownRawY); + longPressActionHeld = injectHoldAction( + gestureConfig.getLongPressAction(), + gestureConfig.getLongPressMouseBehavior()); + notifyGesture(Gesture.LONG_PRESS); + }; + postDelayed(longPressRunnable, gestureConfig.getLongPressDelay()); + } + + // Tap: immediate cursor move (press is deferred to UP for click, or MOVE for drag) + } + + private void handleTsPointerDown(MotionEvent event) { + if (multiFingerGestureUsed) return; + secondTapCandidate = false; + 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; + } + cancelLongPressTimer(); + cancelDrag(); + + if (gestureFingerCount == 2 && gestureOwnedPointerIds.size() >= 2) { + twoFingerTapPossible = true; + twoFingerDragging = false; + twoFingerGestureMode = TWO_FINGER_GESTURE_NONE; + twoFingerHoldTriggered = twoFingerHoldActionHeld = false; + accumulatedPinchDelta = 0; + accumulatedPanDelta = 0; + resetSmallMovement(); + twoFingerDownTime = SystemClock.uptimeMillis(); + twoFingerLastMoveTime = twoFingerDownTime; + twoFingerLockTime = 0; + reclassifyPinchDelta = 0; + reclassifyPanDelta = 0; + int idx0 = event.findPointerIndex(gestureOwnedPointerIds.get(0)); + int idx1 = event.findPointerIndex(gestureOwnedPointerIds.get(1)); + if (idx0 >= 0 && idx1 >= 0) { + twoFingerLastX0 = event.getX(idx0); + twoFingerLastY0 = event.getY(idx0); + twoFingerLastX1 = event.getX(idx1); + twoFingerLastY1 = event.getY(idx1); + pinchLastDistance = (float) Math.hypot( + event.getX(idx0) - event.getX(idx1), + event.getY(idx0) - event.getY(idx1)); + recordMultiFingerOrigins(event, 2); + } + // Schedule two-finger hold + if (gestureConfig.getTwoFingerHoldEnabled()) { + twoFingerHoldRunnable = () -> { + twoFingerHoldTriggered = true; + twoFingerTapPossible = false; + twoFingerHoldActionHeld = injectHoldAction( + gestureConfig.getTwoFingerHoldAction(), + gestureConfig.getTwoFingerHoldMouseBehavior()); + notifyGesture(Gesture.TWO_FINGER_HOLD); + }; + postDelayed(twoFingerHoldRunnable, gestureConfig.getTwoFingerHoldDelay()); + } + } + } + + 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(); + isDragging = true; + 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); + } else { + performClickDragAt(event.getX(pointerIndex), event.getY(pointerIndex), dragAction); + } + } else { + performPanAction(0f, 0f, dragAction); + } + notifyGesture(Gesture.DRAG); + // Non-click pan actions continue with real deltas on the next frame. + return; + } + + if (isDragging) { + String dragAction = gestureConfig.getDragAction(); + if (isClickDragAction(dragAction) && !useRelativeMouseDragMovement()) { + moveCursorTo(x, y); + return; + } + + float rawX = event.getX(pointerIndex); + float rawY = event.getY(pointerIndex); + float dx = rawX - singleFingerLastRawX; + float dy = rawY - singleFingerLastRawY; + singleFingerLastRawX = rawX; + singleFingerLastRawY = rawY; + if (isClickDragAction(dragAction)) { + performClickDragWithRelativeMovement(dx, dy, dragAction); + } else { + performPanAction(dx, dy, dragAction); + } + 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; + + int idx0 = event.findPointerIndex(gestureOwnedPointerIds.get(0)); + 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); + + float midX = (x0 + x1) / 2f; + float midY = (y0 + y1) / 2f; + float lastMidX = (twoFingerLastX0 + twoFingerLastX1) / 2f; + float lastMidY = (twoFingerLastY0 + twoFingerLastY1) / 2f; + float dx = midX - lastMidX; + float dy = midY - lastMidY; + float framePanDelta = (float) Math.hypot(dx, dy); + + 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; + return; + } + long frameTime = now - twoFingerLastMoveTime; + twoFingerLastMoveTime = now; + float velocity = (frameTime > 0) ? framePanDelta / frameTime : 0; // px/ms + + // 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 + && gestureConfig.getPinchEnabled()) { + twoFingerGestureMode = TWO_FINGER_GESTURE_ZOOM; + twoFingerLockTime = now; + notifyGesture(Gesture.PINCH); + } else if (velocity >= MIN_DRAG_VELOCITY && gestureConfig.getTwoFingerDragEnabled()) { + twoFingerGestureMode = TWO_FINGER_GESTURE_PAN; + 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); + } else if (gestureConfig.getPinchEnabled()) { + twoFingerGestureMode = TWO_FINGER_GESTURE_ZOOM; + twoFingerLockTime = now; + notifyGesture(Gesture.PINCH); + } else if (gestureConfig.getTwoFingerDragEnabled()) { + twoFingerGestureMode = TWO_FINGER_GESTURE_PAN; + twoFingerLockTime = now; + notifyGesture(Gesture.TWO_FINGER_DRAG); + } + } + } + if (twoFingerGestureMode != TWO_FINGER_GESTURE_NONE && twoFingerLockTime > 0 + && (now - twoFingerLockTime) < RECLASSIFY_WINDOW_MS) { + reclassifyPinchDelta += framePinchDelta; + reclassifyPanDelta += framePanDelta; + float reclassifyTotal = reclassifyPinchDelta + reclassifyPanDelta; + if (reclassifyTotal > 20f) { // enough post-lock data to reclassify + boolean shouldBeZoom = reclassifyPinchDelta > reclassifyPanDelta * PINCH_RATIO_THRESHOLD; + if (shouldBeZoom && twoFingerGestureMode == TWO_FINGER_GESTURE_PAN + && gestureConfig.getPinchEnabled()) { + twoFingerGestureMode = TWO_FINGER_GESTURE_ZOOM; + releaseDragInput(); + resetSmallMovement(); + notifyGesture(Gesture.PINCH); + } else if (!shouldBeZoom && twoFingerGestureMode == TWO_FINGER_GESTURE_ZOOM + && gestureConfig.getTwoFingerDragEnabled()) { + twoFingerGestureMode = TWO_FINGER_GESTURE_PAN; + resetSmallMovement(); + notifyGesture(Gesture.TWO_FINGER_DRAG); + } + twoFingerLockTime = 0; // done reclassifying + reclassifyPinchDelta = 0; + reclassifyPanDelta = 0; + } + } + if (twoFingerGestureMode == TWO_FINGER_GESTURE_ZOOM) { + float delta = currDist - pinchLastDistance; + 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 + if (twoFingerGestureMode == TWO_FINGER_GESTURE_PAN) { + String twoFingerDragAction = gestureConfig.getTwoFingerDragAction(); + if (isClickDragAction(twoFingerDragAction)) { + if (useRelativeMouseDragMovement()) { + twoFingerDragging = true; + performClickDragWithRelativeMovement(dx, dy, twoFingerDragAction); + } else { + if (!twoFingerDragging) moveCursorToMultiFingerOrigin(); + twoFingerDragging = true; + performClickDragAt(midX, midY, twoFingerDragAction); + } + } else if (dx != 0f || dy != 0f) { + twoFingerDragging = true; + performPanAction(dx, dy, twoFingerDragAction); + } + } + + twoFingerLastX0 = x0; + twoFingerLastY0 = y0; + twoFingerLastX1 = x1; + twoFingerLastY1 = y1; + } + + 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); + notifyGesture(Gesture.TWO_FINGER_TAP); + twoFingerTapFired = true; + } + releaseDragInput(); + twoFingerDragging = false; + twoFingerTapPossible = false; + multiFingerStartCount = 0; + resetSmallMovement(); + twoFingerGestureMode = TWO_FINGER_GESTURE_NONE; + accumulatedPinchDelta = 0; + accumulatedPanDelta = 0; + reclassifyPinchDelta = 0; + reclassifyPanDelta = 0; + twoFingerLockTime = 0; + // Suppress single-finger tap/drag when last finger lifts after any 2F gesture + movedBeyondTapThreshold = true; + multiFingerGestureUsed = true; + } + + private void handleTsUp(MotionEvent event, int actionIndex) { + cancelLongPressTimer(); + + if (longPressTriggered) { + // Release the long-press action + longPressActionHeld = releaseHoldAction(longPressActionHeld, gestureConfig.getLongPressAction()); + longPressTriggered = false; + return; + } + + float x = event.getX(actionIndex); + float y = event.getY(actionIndex); + + if (isDragging && dragButtonPressed) { + // End drag (release any held drag buttons/keys) + releaseDragInput(); + dragButtonPressed = false; + isDragging = false; + lastTapTime = 0; + return; + } + + if (secondTapCandidate) { + secondTapCandidate = false; + long tapLimit = gestureConfig.getLongPressEnabled() + ? 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; + for (int i = 0; i < clicks; i++) queueTapClick(TouchGestureConfig.ACTION_LEFT_CLICK, doubleTapAnchorX, doubleTapAnchorY); + notifyGesture(Gesture.DOUBLE_TAP); + lastTapTime = 0; + return; + } + } + + // 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; + lastTapY = y; + } + movedBeyondTapThreshold = false; + } + + private void handleTsCancel() { + handleTsCancel(false); + } + + private void handleTsCancel(boolean preserveTapRelease) { + cancelLongPressTimer(); + cancelTwoFingerHoldTimer(); + cancelThreeFingerHoldTimer(); + flushPendingHoldClickRelease(); + if (!preserveTapRelease) flushPendingTapRelease(); + if (dragButtonPressed) { + releaseDragInput(); + dragButtonPressed = false; + } + if (longPressTriggered) { + longPressActionHeld = releaseHoldAction(longPressActionHeld, gestureConfig.getLongPressAction()); + longPressTriggered = false; + } + if (twoFingerHoldTriggered) { + twoFingerHoldActionHeld = releaseHoldAction(twoFingerHoldActionHeld, gestureConfig.getTwoFingerHoldAction()); + twoFingerHoldTriggered = false; + } + if (threeFingerHoldTriggered) { + threeFingerHoldActionHeld = releaseHoldAction(threeFingerHoldActionHeld, gestureConfig.getThreeFingerHoldAction()); + threeFingerHoldTriggered = false; + } + releaseDragInput(); + isDragging = false; + twoFingerDragging = false; + twoFingerGestureMode = TWO_FINGER_GESTURE_NONE; + threeFingerDragging = false; + threeFingerTapPossible = false; + threeFingerTapFired = false; + threeFingerGestureMode = THREE_FINGER_GESTURE_NONE; + longPressTriggered = false; + longPressActionHeld = twoFingerHoldActionHeld = threeFingerHoldActionHeld = false; + multiFingerGestureUsed = false; + movedBeyondTapThreshold = false; + secondTapCandidate = false; + gestureOwnedPointerIds.clear(); + gestureFingerCount = 0; + multiFingerStartCount = 0; + resetSmallMovement(); + } + + private void handleTsThreeFingerDown(MotionEvent event) { + if (multiFingerGestureUsed) return; + flushPendingHoldClickRelease(); + 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; + twoFingerTapPossible = false; + twoFingerGestureMode = TWO_FINGER_GESTURE_NONE; + + threeFingerTapPossible = true; + threeFingerDragging = false; + threeFingerHoldTriggered = threeFingerHoldActionHeld = false; + threeFingerGestureMode = THREE_FINGER_GESTURE_NONE; + accumulatedThreeFingerDelta = 0; + threeFingerDragOffsetX = threeFingerDragOffsetY = 0f; + threeFingerDownTime = SystemClock.uptimeMillis(); + + // Compute midpoint of three gesture fingers + if (gestureOwnedPointerIds.size() >= 3) { + float sumX = 0, sumY = 0; + int validCount = 0; + for (int i = 0; i < 3; i++) { + int idx = event.findPointerIndex(gestureOwnedPointerIds.get(i)); + if (idx >= 0) { + sumX += event.getX(idx); + sumY += event.getY(idx); + validCount++; + } + } + if (validCount < 3) return; // Can't proceed without all 3 pointers + threeFingerLastMidX = sumX / 3f; + threeFingerLastMidY = sumY / 3f; + recordMultiFingerOrigins(event, 3); + } + + // Schedule three-finger hold + if (gestureConfig.getThreeFingerHoldEnabled()) { + threeFingerHoldRunnable = () -> { + threeFingerHoldTriggered = true; + threeFingerTapPossible = false; + threeFingerHoldActionHeld = injectHoldAction( + gestureConfig.getThreeFingerHoldAction(), + gestureConfig.getThreeFingerHoldMouseBehavior()); + notifyGesture(Gesture.THREE_FINGER_HOLD); + }; + postDelayed(threeFingerHoldRunnable, gestureConfig.getThreeFingerHoldDelay()); + } + } + + 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; + cancelThreeFingerHoldTimer(); + } + if (multiFingerMovementExceeded(event, true)) cancelThreeFingerHoldTimer(); + + float sumX = 0, sumY = 0; + int validCount = 0; + for (int i = 0; i < 3; i++) { + int idx = event.findPointerIndex(gestureOwnedPointerIds.get(i)); + if (idx >= 0) { + sumX += event.getX(idx); + sumY += event.getY(idx); + validCount++; + } + } + if (validCount < 3) return; + + float midX = sumX / 3f; + float midY = sumY / 3f; + float dx = midX - threeFingerLastMidX; + float dy = midY - threeFingerLastMidY; + float frameDelta = (float) Math.hypot(dx, dy); + long now = SystemClock.uptimeMillis(); + if (now - threeFingerDownTime < THREE_FINGER_SETTLE_MS) { + threeFingerLastMidX = midX; + threeFingerLastMidY = midY; + return; + } + + if (threeFingerGestureMode == THREE_FINGER_GESTURE_NONE) { + accumulatedThreeFingerDelta += frameDelta; + if (accumulatedThreeFingerDelta > (float) gestureConfig.getGestureThreshold()) { + threeFingerTapPossible = false; + cancelThreeFingerHoldTimer(); + if (gestureConfig.getThreeFingerDragEnabled()) { + threeFingerGestureMode = THREE_FINGER_GESTURE_PAN; + notifyGesture(Gesture.THREE_FINGER_DRAG); + } + } + } + + 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()) { + threeFingerDragging = true; + performClickDragWithRelativeMovement(dx, dy, threeFingerDragAction); + } else { + if (!threeFingerDragging) moveCursorToMultiFingerOrigin(); + threeFingerDragging = true; + performClickDragAt(midX + threeFingerDragOffsetX, midY + threeFingerDragOffsetY, threeFingerDragAction); + } + } else if (dx != 0f || dy != 0f) { + threeFingerDragging = true; + performPanAction(dx, dy, threeFingerDragAction); + } + } + + threeFingerLastMidX = midX; + threeFingerLastMidY = midY; + } + + private void handleTsThreeFingerUp(MotionEvent event) { + cancelThreeFingerHoldTimer(); + if (multiFingerMovementExceeded(event)) threeFingerTapPossible = false; + + if (threeFingerHoldTriggered) { + threeFingerHoldActionHeld = releaseHoldAction(threeFingerHoldActionHeld, gestureConfig.getThreeFingerHoldAction()); + threeFingerHoldTriggered = false; + } else if (threeFingerTapPossible && !threeFingerDragging + && gestureConfig.getThreeFingerTapEnabled()) { + queueTapClick(gestureConfig.getThreeFingerTapAction(), threeFingerLastMidX, threeFingerLastMidY); + notifyGesture(Gesture.THREE_FINGER_TAP); + threeFingerTapFired = true; + } + + releaseDragInput(); + threeFingerDragging = false; + threeFingerTapPossible = false; + 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; + } + + private void resetSmallMovement() { + pinchZoomRemainder = keyPanRemainderX = keyPanRemainderY = 0f; + } + + private static float accumulateSignedMovement(float remainder, float delta) { + if (delta != 0f && Math.signum(delta) != Math.signum(remainder)) remainder = 0f; + return remainder + delta; + } + + private void recordMultiFingerOrigins(MotionEvent event, int count) { + multiFingerStartCount = 0; + for (int i = 0; i < count; i++) { + int id = gestureOwnedPointerIds.get(i); + int index = event.findPointerIndex(id); + if (index < 0) return; + multiFingerStartIds[i] = id; + multiFingerStartX[i] = event.getX(index); + multiFingerStartY[i] = event.getY(index); + } + multiFingerStartCount = count; + } + + private void moveCursorToMultiFingerOrigin() { + if (multiFingerStartCount == 0) return; + float x = 0, y = 0; + for (int i = 0; i < multiFingerStartCount; i++) { + x += multiFingerStartX[i]; + y += multiFingerStartY[i]; + } + moveCursorTo((int) (x / multiFingerStartCount), (int) (y / multiFingerStartCount)); + } + + private void rebaseThreeFingerMovement(MotionEvent event) { + float x = 0, y = 0; + for (int i = 0; i < 3; i++) { + int index = event.findPointerIndex(gestureOwnedPointerIds.get(i)); + if (index < 0) return; + x += event.getX(index); + y += event.getY(index); + } + x /= 3f; + y /= 3f; + // Replacing a tracked finger changes the centroid without moving the cursor. + if (threeFingerDragging) { + threeFingerDragOffsetX += threeFingerLastMidX - x; + threeFingerDragOffsetY += threeFingerLastMidY - y; + } + threeFingerLastMidX = x; + threeFingerLastMidY = y; + accumulatedThreeFingerDelta = 0; + threeFingerTapPossible = false; + cancelThreeFingerHoldTimer(); + recordMultiFingerOrigins(event, 3); + resetSmallMovement(); + } + + private float maxFingerTravel(MotionEvent event, int index, float originX, float originY) { + float distance = (float) Math.hypot(event.getX(index) - originX, event.getY(index) - originY); + for (int h = 0; h < event.getHistorySize(); h++) { + distance = Math.max(distance, (float) Math.hypot( + event.getHistoricalX(index, h) - originX, event.getHistoricalY(index, h) - originY)); + } + return distance; + } + + private boolean multiFingerMovementExceeded(MotionEvent event) { + return multiFingerMovementExceeded(event, false); + } + + private boolean multiFingerMovementExceeded(MotionEvent event, boolean forHold) { + float tolerance = forHold ? doubleTapSlop : gestureConfig.getGestureThreshold(); + for (int i = 0; i < multiFingerStartCount; i++) { + int index = event.findPointerIndex(multiFingerStartIds[i]); + if (index < 0) continue; + if (maxFingerTravel(event, index, multiFingerStartX[i], multiFingerStartY[i]) > tolerance) return true; + for (int j = 0; !forHold && j < i; j++) { + int other = event.findPointerIndex(multiFingerStartIds[j]); + if (other < 0) continue; + double initialDistance = Math.hypot(multiFingerStartX[i] - multiFingerStartX[j], multiFingerStartY[i] - multiFingerStartY[j]); + double distance = Math.hypot(event.getX(index) - event.getX(other), event.getY(index) - event.getY(other)); + if (Math.abs(distance - initialDistance) > tolerance) return true; + for (int h = 0; h < event.getHistorySize(); h++) { + distance = Math.hypot(event.getHistoricalX(index, h) - event.getHistoricalX(other, h), + event.getHistoricalY(index, h) - event.getHistoricalY(other, h)); + if (Math.abs(distance - initialDistance) > tolerance) return true; + } + } + } + return false; + } + + private boolean isDoubleTap(MotionEvent event, int index) { + return gestureConfig.getDoubleTapEnabled() && lastTapTime > 0 + && SystemClock.uptimeMillis() - lastTapTime < gestureConfig.getDoubleTapDelay() + && Math.hypot(event.getX(index) - lastTapX, event.getY(index) - lastTapY) + < doubleTapSlop; + } + + private void queueTapClick(String action, float x, float y) { + pendingTapClicks.addLast(new TapClick(action, x, y)); + startPendingTapClick(); + } + + 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; + pendingTapClicks.removeFirst(); + moveCursorTo(click.x, click.y); + injectClick(click.action); + delayedPressAction = click.action; + delayedPress = () -> { + injectRelease(click.action); + delayedPress = null; + delayedPressAction = null; + startPendingTapClick(); + }; + postDelayed(delayedPress, CLICK_DELAYED_TIME); + }; + if (delay > 0) postDelayed(pendingTapPress, delay); + else pendingTapPress.run(); + } + + private void flushPendingTapRelease() { + if (pendingTapPress != null) removeCallbacks(pendingTapPress); + pendingTapPress = null; + pendingTapClicks.clear(); + if (delayedPress != null) { + removeCallbacks(delayedPress); + injectRelease(delayedPressAction); + delayedPressAction = null; + delayedPress = null; + } + } + + private void flushPendingHoldClickRelease() { + if (pendingHoldClickRelease != null) { + removeCallbacks(pendingHoldClickRelease); + String action = pendingHoldClickReleaseAction; + pendingHoldClickRelease = null; + pendingHoldClickReleaseAction = null; + injectRelease(action); + } + } + + private void cancelLongPressTimer() { + if (longPressRunnable != null) { + removeCallbacks(longPressRunnable); + longPressRunnable = null; + } + } + + private void cancelDrag() { + if (isDragging && dragButtonPressed) { + releaseDragInput(); + dragButtonPressed = false; + } + isDragging = false; + } + + private void cancelTwoFingerHoldTimer() { + if (twoFingerHoldRunnable != null) { + removeCallbacks(twoFingerHoldRunnable); + twoFingerHoldRunnable = null; + } + } + + private void cancelThreeFingerHoldTimer() { + if (threeFingerHoldRunnable != null) { + removeCallbacks(threeFingerHoldRunnable); + threeFingerHoldRunnable = null; + } + } + + private void moveCursorTo(int x, int y) { output.moveTo(x, y); } + + private boolean injectClick(String action) { + if (action == null) return false; + if (TouchGestureConfig.ACTION_SHOW_KEYBOARD.equals(action)) { + output.showKeyboard(); return false; + } + if (TouchGestureConfig.ACTION_KEY_TILDE.equals(action)) { + pressKey(42); pressKey(41); return true; + } + Integer code = actionToKeycode(action); + if (code != null) { pressKey(code); return true; } + MouseButton button = actionToButton(action); + if (button != null) { pressButton(button); return true; } + return false; + } + + private void injectRelease(String action) { + if (action == null) return; + if (TouchGestureConfig.ACTION_KEY_TILDE.equals(action)) { releaseKey(41); releaseKey(42); return; } + Integer code = actionToKeycode(action); + if (code != null) { releaseKey(code); return; } + MouseButton button = actionToButton(action); + if (button != null) releaseButton(button); + } + + private boolean injectHoldAction(String action, String mouseBehavior) { + if (TouchGestureConfig.isMouseButtonAction(action) && TouchGestureConfig.MOUSE_BEHAVIOR_CLICK.equals(mouseBehavior)) { + flushPendingHoldClickRelease(); + if (injectClick(action)) { + pendingHoldClickReleaseAction = action; + pendingHoldClickRelease = () -> { + String pendingAction = pendingHoldClickReleaseAction; + pendingHoldClickRelease = null; + pendingHoldClickReleaseAction = null; + injectRelease(pendingAction); + }; + postDelayed(pendingHoldClickRelease, CLICK_DELAYED_TIME); + } + return false; + } + return injectClick(action); + } + + private boolean releaseHoldAction(boolean held, String action) { + if (held) injectRelease(action); + return false; + } + + private Integer actionToKeycode(String action) { + return action != null && action.startsWith("key_") ? GestureKeys.code(action.substring(4)) : null; + } + + private MouseButton actionToButton(String action) { + if (TouchGestureConfig.ACTION_LEFT_CLICK.equals(action)) return MouseButton.BUTTON_LEFT; + if (TouchGestureConfig.ACTION_RIGHT_CLICK.equals(action)) return MouseButton.BUTTON_RIGHT; + if (TouchGestureConfig.ACTION_MIDDLE_CLICK.equals(action)) return MouseButton.BUTTON_MIDDLE; + return null; + } + private void performZoomAction(boolean zoomIn) { + String action = gestureConfig.getPinchAction(); + if (TouchGestureConfig.ZOOM_SCROLL_WHEEL.equals(action)) { output.wheel(zoomIn ? -1 : 1); return; } + int code = TouchGestureConfig.ZOOM_PLUS_MINUS.equals(action) ? (zoomIn ? 13 : 12) : (zoomIn ? 104 : 109); + pressKey(code); + postDelayed(() -> releaseKey(code), CLICK_DELAYED_TIME); + } + + private void performPanAction(float dx, float dy, String action) { + switch (action) { + case TouchGestureConfig.PAN_MIDDLE_MOUSE: + performMiddleMousePan(dx, dy); + break; + case TouchGestureConfig.PAN_INVERTED_MIDDLE_MOUSE: + performMiddleMousePan(-dx, -dy); + break; + case TouchGestureConfig.PAN_WASD: + performKeyPan(dx, dy, GestureKeys.code("A"), GestureKeys.code("D"), GestureKeys.code("W"), GestureKeys.code("S")); + break; + case TouchGestureConfig.PAN_INVERTED_WASD: + performKeyPan(dx, dy, GestureKeys.code("D"), GestureKeys.code("A"), GestureKeys.code("S"), GestureKeys.code("W")); + break; + case TouchGestureConfig.PAN_ARROW_KEYS: + performKeyPan(dx, dy, GestureKeys.code("LEFT"), GestureKeys.code("RIGHT"), GestureKeys.code("UP"), GestureKeys.code("DOWN")); + break; + case TouchGestureConfig.PAN_INVERTED_ARROW_KEYS: + performKeyPan(dx, dy, GestureKeys.code("RIGHT"), GestureKeys.code("LEFT"), GestureKeys.code("DOWN"), GestureKeys.code("UP")); + break; + case TouchGestureConfig.PAN_LEFT_CLICK_DRAG: + performClickDrag(dx, dy, MouseButton.BUTTON_LEFT); + break; + case TouchGestureConfig.PAN_RIGHT_CLICK_DRAG: + performClickDrag(dx, dy, MouseButton.BUTTON_RIGHT); + break; + } + } + + private boolean isClickDragAction(String action) { + return TouchGestureConfig.PAN_LEFT_CLICK_DRAG.equals(action) + || TouchGestureConfig.PAN_RIGHT_CLICK_DRAG.equals(action); + } + + private boolean useRelativeMouseDragMovement() { + return TouchGestureConfig.MOUSE_DRAG_MOVEMENT_RELATIVE.equals(gestureConfig.getMouseDragMovementMode()); + } + + private MouseButton buttonForClickDragAction(String action) { + return TouchGestureConfig.PAN_RIGHT_CLICK_DRAG.equals(action) + ? MouseButton.BUTTON_RIGHT : MouseButton.BUTTON_LEFT; + } + + private void performClickDragAt(float rawX, float rawY, String action) { + pressClickDragAction(action); + moveCursorTo((int) rawX, (int) rawY); + } + + private void performMiddleMousePan(float dx, float dy) { + if (!twoFingerMiddleButtonDown) { + output.prepareRelativePan(); + 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); + } + + private void performClickDrag(float dx, float dy, MouseButton button) { + pressClickDragButton(button); + moveCursorByDelta(dx, dy); + } + + private void performClickDragWithRelativeMovement(float dx, float dy, String action) { + pressClickDragAction(action); + moveCursorByRelativeDelta(dx, dy); + } + + private void pressClickDragAction(String action) { + pressClickDragButton(buttonForClickDragAction(action)); + } + + private void pressClickDragButton(MouseButton button) { + if (button == MouseButton.BUTTON_LEFT && !leftClickDragButtonDown) { + pressButton(MouseButton.BUTTON_LEFT); + leftClickDragButtonDown = true; + } else if (button == MouseButton.BUTTON_RIGHT && !rightClickDragButtonDown) { + pressButton(MouseButton.BUTTON_RIGHT); + rightClickDragButtonDown = true; + } + } + + private void moveCursorByRelativeDelta(float dx, float dy) { output.moveBy(dx, dy, true); } + + private void moveCursorByDelta(float dx, float dy) { output.moveBy(dx, dy, false); } + + private void releaseTwoFingerMiddleButton() { + if (twoFingerMiddleButtonDown) { + releaseButton(MouseButton.BUTTON_MIDDLE); + twoFingerMiddleButtonDown = false; + } + } + + private void releaseClickDragButtons() { + if (leftClickDragButtonDown) { + releaseButton(MouseButton.BUTTON_LEFT); + leftClickDragButtonDown = false; + } + if (rightClickDragButtonDown) { + releaseButton(MouseButton.BUTTON_RIGHT); + rightClickDragButtonDown = false; + } + } + + private void releaseDragInput() { + releasePanKeys(); + releaseAllDragButtons(); + } + + private void releaseAllDragButtons() { + releaseTwoFingerMiddleButton(); + releaseClickDragButtons(); + } + + 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); + float totalDelta = Math.abs(keyPanRemainderX) + Math.abs(keyPanRemainderY); + if (totalDelta < 5f || (Math.abs(keyPanRemainderX) <= 3f && Math.abs(keyPanRemainderY) <= 3f)) return; + dx = keyPanRemainderX; + 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; + + if (panKeyLeft && !wantLeft) { releaseKey(leftKey); panKeyLeft = false; } + if (panKeyRight && !wantRight) { releaseKey(rightKey); panKeyRight = false; } + 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; + + if (panKeyUp && !wantUp) { releaseKey(upKey); panKeyUp = false; } + if (panKeyDown && !wantDown) { releaseKey(downKey); panKeyDown = false; } + if (wantUp && !panKeyUp) { pressKey(upKey); panKeyUp = true; panUpKey = upKey; } + if (wantDown && !panKeyDown) { pressKey(downKey); panKeyDown = true; panDownKey = downKey; } + } + + private void releasePanKeys() { + keyPanRemainderX = keyPanRemainderY = 0f; + if (panKeyLeft && panLeftKey != null) { releaseKey(panLeftKey); panKeyLeft = false; } + if (panKeyRight && panRightKey != null) { releaseKey(panRightKey); panKeyRight = false; } + if (panKeyUp && panUpKey != null) { releaseKey(panUpKey); panKeyUp = false; } + if (panKeyDown && panDownKey != null) { releaseKey(panDownKey); panKeyDown = false; } + } + +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index f808be94de..3cf155ccb7 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -168,6 +168,7 @@ object SessionPrefs { const val TOUCH_AUTO = "auto" const val TOUCH_PAD = "touchpad" const val TOUCH_DIRECT = "direct" + const val TOUCH_GESTURES = "gestures" const val TOUCH_OFF = "off" fun touchMode(context: Context): String = prefs(context).getString("touch", TOUCH_AUTO) ?: TOUCH_AUTO diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GestureActions.kt b/app/src/main/java/com/droiddeck/launcher/ui/GestureActions.kt new file mode 100644 index 0000000000..56643effe7 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GestureActions.kt @@ -0,0 +1,128 @@ +package com.droiddeck.launcher.ui + +import androidx.annotation.StringRes +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import com.droiddeck.launcher.R +import java.text.Collator + +internal enum class GestureActionGroup(@StringRes val title: Int) { + MOUSE(R.string.gesture_group_mouse), APP(R.string.gesture_group_app), + NAVIGATION(R.string.gesture_group_navigation), LETTERS(R.string.gesture_group_letters), + NUMBERS(R.string.gesture_group_numbers), FUNCTION(R.string.gesture_group_function), + MODIFIERS(R.string.gesture_group_modifiers), NUMPAD(R.string.gesture_group_numpad), + SYMBOLS(R.string.gesture_group_symbols), +} + +internal data class GestureAction(val id: String, val title: String, val group: GestureActionGroup) + +internal fun gestureActionGroup(id: String): GestureActionGroup { + if (id == "show_keyboard") return GestureActionGroup.APP + if (id in setOf("left_click", "right_click", "middle_click", "left_click_drag", "right_click_drag", + "middle_mouse_pan", "inverted_middle_mouse_pan", "scroll_wheel")) return GestureActionGroup.MOUSE + val key = id.removePrefix("key_") + return when { + key.startsWith("KP_") -> GestureActionGroup.NUMPAD + key.length == 1 && key[0] in 'A'..'Z' -> GestureActionGroup.LETTERS + key.length == 1 && key[0].isDigit() -> GestureActionGroup.NUMBERS + key.matches(Regex("F(?:[1-9]|1[0-2])")) -> GestureActionGroup.FUNCTION + key.startsWith("CTRL_") || key.startsWith("SHIFT_") || key.startsWith("ALT_") || key.endsWith("_LOCK") -> GestureActionGroup.MODIFIERS + key in setOf("MINUS", "EQUAL", "BRACKET_LEFT", "BRACKET_RIGHT", "SEMICOLON", "APOSTROPHE", + "GRAVE", "TILDE", "BACKSLASH", "COMMA", "PERIOD", "SLASH") || id == "plus_minus" -> GestureActionGroup.SYMBOLS + else -> GestureActionGroup.NAVIGATION + } +} + +internal fun filterGestureActions(actions: List, query: String, group: GestureActionGroup?): List { + val words = query.trim().split(Regex("\\s+")).filter { it.isNotEmpty() } + val collator = Collator.getInstance() + return actions.filter { action -> + (group == null || action.group == group) && words.all { word -> + action.title.contains(word, ignoreCase = true) || action.id.removePrefix("key_").replace('_', ' ').contains(word, ignoreCase = true) + } + }.sortedWith(compareBy { it.group.ordinal }.thenComparator { a, b -> + // Function keys follow their numeric sequence; names use the UI locale. + if (a.group == GestureActionGroup.FUNCTION) { + a.id.removePrefix("key_F").toInt().compareTo(b.id.removePrefix("key_F").toInt()) + } else collator.compare(a.title, b.title) + }.thenBy { it.id }) +} + +@Composable +internal fun gestureActionTitle(action: String): String { + val named = when (action) { + "left_click" -> R.string.gesture_left_click + "right_click" -> R.string.gesture_right_click + "middle_click" -> R.string.gesture_middle_click + "show_keyboard" -> R.string.gesture_keyboard + "left_click_drag" -> R.string.gesture_left_drag + "right_click_drag" -> R.string.gesture_right_drag + "middle_mouse_pan" -> R.string.gesture_middle_pan + "inverted_middle_mouse_pan" -> R.string.gesture_middle_pan_inverted + "arrow_keys" -> R.string.gesture_arrows + "inverted_arrow_keys" -> R.string.gesture_arrows_inverted + "inverted_wasd" -> R.string.gesture_wasd_inverted + "scroll_wheel" -> R.string.gesture_scroll + else -> null + } + if (named != null) return stringResource(named) + return when (action) { + "wasd" -> "WASD" + "plus_minus" -> "+ / −" + "page_up_down" -> stringResource(R.string.gesture_key_page_up) + " / " + stringResource(R.string.gesture_key_page_down) + else -> gestureKeyTitle(action.removePrefix("key_")) + } +} + +@Composable +private fun gestureKeyTitle(key: String): String { + if (key.startsWith("KP_")) return stringResource(R.string.gesture_key_numpad, gestureKeyTitle(key.removePrefix("KP_"))) + val named = when (key) { + "ESC" -> R.string.gesture_key_escape + "BKSP" -> R.string.gesture_key_backspace + "ENTER" -> R.string.gesture_key_enter + "TAB" -> R.string.gesture_key_tab + "SPACE" -> R.string.gesture_key_space + "DEL" -> R.string.gesture_key_delete + "INSERT" -> R.string.gesture_key_insert + "HOME" -> R.string.gesture_key_home + "END" -> R.string.gesture_key_end + "PRIOR" -> R.string.gesture_key_page_up + "NEXT" -> R.string.gesture_key_page_down + "PRTSCN" -> R.string.gesture_key_print_screen + "UP" -> R.string.gesture_key_up + "DOWN" -> R.string.gesture_key_down + "LEFT" -> R.string.gesture_key_left_arrow + "RIGHT" -> R.string.gesture_key_right_arrow + "CAPS_LOCK" -> R.string.gesture_key_caps_lock + "NUM_LOCK" -> R.string.gesture_key_num_lock + "SCROLL_LOCK" -> R.string.gesture_key_scroll_lock + else -> null + } + if (named != null) return stringResource(named) + if (key.startsWith("CTRL_") || key.startsWith("SHIFT_") || key.startsWith("ALT_")) { + val name = stringResource(when (key.substringBefore('_')) { + "CTRL" -> R.string.pckb_key_ctrl + "SHIFT" -> R.string.gesture_key_shift + else -> R.string.pckb_key_alt + }) + return stringResource(if (key.endsWith("_L")) R.string.gesture_key_left else R.string.gesture_key_right, name) + } + return when (key) { + "MINUS", "SUBTRACT" -> "−" + "EQUAL" -> "=" + "ADD" -> "+" + "MULTIPLY" -> "×" + "DIVIDE", "SLASH" -> "/" + "BRACKET_LEFT" -> "[" + "BRACKET_RIGHT" -> "]" + "SEMICOLON" -> ";" + "APOSTROPHE" -> "'" + "GRAVE" -> "`" + "TILDE" -> "~" + "BACKSLASH" -> "\\" + "COMMA" -> "," + "PERIOD" -> "." + else -> key.replace('_', ' ') + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GestureFeedback.kt b/app/src/main/java/com/droiddeck/launcher/ui/GestureFeedback.kt new file mode 100644 index 0000000000..89233e9240 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/GestureFeedback.kt @@ -0,0 +1,35 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.TouchscreenGestures.Gesture + +@Composable +fun GestureFeedback(gesture: Gesture?) { + Box(Modifier.fillMaxSize()) { + if (gesture != null) Text(stringResource(when (gesture) { + Gesture.TAP -> R.string.gesture_tap + Gesture.DRAG -> R.string.gesture_drag + Gesture.LONG_PRESS -> R.string.gesture_long_press + Gesture.DOUBLE_TAP -> R.string.gesture_double_tap + Gesture.TWO_FINGER_TAP -> R.string.gesture_two_tap + Gesture.TWO_FINGER_DRAG -> R.string.gesture_two_drag + Gesture.TWO_FINGER_HOLD -> R.string.gesture_two_hold + Gesture.PINCH -> R.string.gesture_pinch + Gesture.THREE_FINGER_TAP -> R.string.gesture_three_tap + Gesture.THREE_FINGER_DRAG -> R.string.gesture_three_drag + Gesture.THREE_FINGER_HOLD -> R.string.gesture_three_hold + }), + Modifier.align(Alignment.TopCenter).padding(top = 24.dp) + .background(MaterialTheme.colorScheme.surface).padding(horizontal = 16.dp, vertical = 8.dp), + color = MaterialTheme.colorScheme.onSurface) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index 0fb34d6634..b0f501cbe9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -250,7 +250,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SettingsGroup(if (steam) stringResource(R.string.mode_touch_controls) else stringResource(R.string.mode_touch)) { ChoiceRow( host, "touch", stringResource(R.string.mode_touch), null, - listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), s.touchMode, + listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.common_auto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), s.touchMode, note = stringResource(R.string.mode_touch_note), onPick = a.onTouch, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 4d4cdbabad..6fa4cba7b6 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -245,6 +245,7 @@ class DrawerActions( val onLowLatencyController: (Boolean) -> Unit = {}, val onLowLatencyTouch: (Boolean) -> Unit = {}, val onTouch: (String) -> Unit, + val onGestureSettings: () -> Unit = {}, val onFexPreset: (String) -> Unit, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, @@ -500,8 +501,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont type, chipModifier = focus.track(page, "pad-type"), onPick = a.onPadType) } ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null, - listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), + listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), a.touchMode, chipModifier = focus.track(page, "touch"), onPick = a.onTouch) + ActionRow(stringResource(R.string.gesture_settings), stringResource(R.string.gesture_settings_hint), + stringResource(R.string.ctrl_edit), a.onGestureSettings, + modifier = focus.track(page, "gesture-settings")) ChoiceRow(host, "osc", stringResource(R.string.mode_osc), null, if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)) else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 8db2cc793b..fb92473338 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -648,8 +648,8 @@ fun MultiRow( } @Composable -fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit, progress: Float? = null) { - SettingsRow(label, hint) { SecondaryButton(button, progress = progress, onClick = onClick) } +fun ActionRow(label: String, hint: String?, button: String, onClick: () -> Unit, progress: Float? = null, modifier: Modifier = Modifier) { + SettingsRow(label, hint) { SecondaryButton(button, modifier = modifier, progress = progress, onClick = onClick) } } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TouchGestureDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/TouchGestureDialog.kt new file mode 100644 index 0000000000..8cd79257d6 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/TouchGestureDialog.kt @@ -0,0 +1,345 @@ +package com.droiddeck.launcher.ui + +import androidx.annotation.StringRes +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowForward +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Keyboard +import androidx.compose.material.icons.filled.Mouse +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.TouchApp +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalLayoutDirection +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.GestureKeys +import com.droiddeck.launcher.input.GesturePrefs +import com.droiddeck.launcher.input.TouchGestureConfig +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_LEFT_CLICK +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_RIGHT_CLICK +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_MIDDLE_CLICK +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_SHOW_KEYBOARD +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ACTION_KEY_TILDE +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.PAN_ACTIONS +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.ZOOM_ACTIONS +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_HOLD +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_BEHAVIOR_CLICK +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_DRAG_MOVEMENT_DIRECT +import com.droiddeck.launcher.input.TouchGestureConfig.Companion.MOUSE_DRAG_MOVEMENT_RELATIVE + +@Composable +fun TouchGestureDialog(game: String?, onDismiss: () -> Unit, onSaved: () -> Unit) { + val context = LocalContext.current + // Keep an open editor attached to the game it was opened for. + val targetGame = remember { game } + val initialDefaults = remember { GesturePrefs.read(context) } + val initialGame = remember { targetGame?.takeIf { GesturePrefs.hasOverride(context, it) }?.let { GesturePrefs.read(context, it) } } + var defaults by remember { mutableStateOf(initialDefaults) } + var gameDraft by remember { mutableStateOf(initialGame) } + var forGame by rememberSaveable { mutableStateOf(targetGame != null) } + val config = if (forGame) gameDraft ?: defaults else defaults + val change: (TouchGestureConfig) -> Unit = { if (forGame) gameDraft = it else defaults = it } + var tab by rememberSaveable { mutableIntStateOf(0) } + val tabs = listOf(R.string.gesture_tab_one, R.string.gesture_tab_two, R.string.gesture_tab_three, R.string.gesture_tab_options) + val mouse = listOf(ACTION_LEFT_CLICK, ACTION_RIGHT_CLICK, ACTION_MIDDLE_CLICK) + val actions = mouse + ACTION_SHOW_KEYBOARD + GestureKeys.codes.keys.map { "key_$it" } + ACTION_KEY_TILDE + val p = LocalPalette.current + + GestureDialogFrame(stringResource(R.string.gesture_settings), stringResource(R.string.gesture_editor_subtitle), onDismiss, + footer = { + Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 12.dp), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.gesture_cancel)) } + Spacer(Modifier.width(12.dp)) + Button(onClick = { + if (defaults != initialDefaults) GesturePrefs.save(context, null, defaults) + if (targetGame != null && gameDraft != initialGame) { + gameDraft?.let { GesturePrefs.save(context, targetGame, it) } ?: GesturePrefs.clear(context, targetGame) + } + onSaved() + }, modifier = Modifier.testTag("gesture-save")) { Text(stringResource(R.string.gesture_save_changes)) } + } + }) { + Column(Modifier.padding(horizontal = 20.dp)) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + GestureFilterChip(!forGame, onClick = { forGame = false }, label = { Text(stringResource(R.string.gesture_defaults)) }, modifier = Modifier.testTag("gesture-scope-default")) + if (targetGame != null) GestureFilterChip(forGame, onClick = { forGame = true }, label = { Text(stringResource(R.string.gesture_game)) }, modifier = Modifier.testTag("gesture-scope-game")) + if (forGame && gameDraft != null) TextButton(onClick = { gameDraft = null }, modifier = Modifier.testTag("gesture-inherit")) { Text(stringResource(R.string.gesture_use_defaults)) } + } + Text(stringResource(if (!forGame) R.string.gesture_scope_default else if (gameDraft == null) R.string.gesture_inheriting else R.string.gesture_scope_game), + color = p.onSurfaceVariant, style = MaterialTheme.typography.bodySmall, modifier = Modifier.padding(bottom = 12.dp)) + } + ScrollableTabRow(tab, edgePadding = 12.dp, containerColor = p.surface, divider = { HorizontalDivider(color = p.line) }) { + tabs.forEachIndexed { index, title -> + Tab(tab == index, onClick = { tab = index }, text = { Text(stringResource(title)) }, selectedContentColor = p.onBackground, + unselectedContentColor = p.onSurfaceVariant, modifier = Modifier.testTag("gesture-tab-$index")) + } + } + key(tab) { + Column(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { + when (tab) { + 0 -> { + GestureSection(R.string.gesture_tab_one, R.string.gesture_one_hint) + GestureCard(R.string.gesture_tap, config.tapEnabled, { change(config.copy(tapEnabled = it)) }) { + GestureActionField("tap", R.string.gesture_tap, config.tapAction, actions) { change(config.copy(tapAction = it)) } + } + GestureCard(R.string.gesture_drag, config.dragEnabled, { change(config.copy(dragEnabled = it)) }) { + GestureActionField("drag", R.string.gesture_drag, config.dragAction, PAN_ACTIONS) { change(config.copy(dragAction = it)) } + } + GestureCard(R.string.gesture_long_press, config.longPressEnabled, { change(config.copy(longPressEnabled = it)) }) { + GestureActionField("long-press", R.string.gesture_long_press, config.longPressAction, actions) { change(config.copy(longPressAction = it)) } + GestureHoldOptions(config.longPressAction, config.longPressMouseBehavior, config.longPressDelay, { change(config.copy(longPressMouseBehavior = it)) }, { change(config.copy(longPressDelay = it)) }) + } + GestureCard(R.string.gesture_double_tap, config.doubleTapEnabled, { change(config.copy(doubleTapEnabled = it)) }) { + GestureDelay(stringResource(R.string.gesture_double_delay), config.doubleTapDelay) { change(config.copy(doubleTapDelay = it)) } + } + } + 1 -> { + GestureSection(R.string.gesture_tab_two, R.string.gesture_two_hint) + GestureCard(R.string.gesture_two_tap, config.twoFingerTapEnabled, { change(config.copy(twoFingerTapEnabled = it)) }) { + GestureActionField("two-tap", R.string.gesture_two_tap, config.twoFingerTapAction, actions) { change(config.copy(twoFingerTapAction = it)) } + } + GestureCard(R.string.gesture_two_drag, config.twoFingerDragEnabled, { change(config.copy(twoFingerDragEnabled = it)) }) { + GestureActionField("two-drag", R.string.gesture_two_drag, config.twoFingerDragAction, PAN_ACTIONS) { change(config.copy(twoFingerDragAction = it)) } + } + GestureCard(R.string.gesture_two_hold, config.twoFingerHoldEnabled, { change(config.copy(twoFingerHoldEnabled = it)) }) { + GestureActionField("two-hold", R.string.gesture_two_hold, config.twoFingerHoldAction, actions) { change(config.copy(twoFingerHoldAction = it)) } + GestureHoldOptions(config.twoFingerHoldAction, config.twoFingerHoldMouseBehavior, config.twoFingerHoldDelay, { change(config.copy(twoFingerHoldMouseBehavior = it)) }, { change(config.copy(twoFingerHoldDelay = it)) }) + } + GestureCard(R.string.gesture_pinch, config.pinchEnabled, { change(config.copy(pinchEnabled = it)) }) { + GestureActionField("pinch", R.string.gesture_pinch, config.pinchAction, ZOOM_ACTIONS) { change(config.copy(pinchAction = it)) } + } + } + 2 -> { + GestureSection(R.string.gesture_tab_three, R.string.gesture_three_hint) + GestureCard(R.string.gesture_three_tap, config.threeFingerTapEnabled, { change(config.copy(threeFingerTapEnabled = it)) }) { + GestureActionField("three-tap", R.string.gesture_three_tap, config.threeFingerTapAction, actions) { change(config.copy(threeFingerTapAction = it)) } + } + GestureCard(R.string.gesture_three_drag, config.threeFingerDragEnabled, { change(config.copy(threeFingerDragEnabled = it)) }) { + GestureActionField("three-drag", R.string.gesture_three_drag, config.threeFingerDragAction, PAN_ACTIONS) { change(config.copy(threeFingerDragAction = it)) } + } + GestureCard(R.string.gesture_three_hold, config.threeFingerHoldEnabled, { change(config.copy(threeFingerHoldEnabled = it)) }) { + GestureActionField("three-hold", R.string.gesture_three_hold, config.threeFingerHoldAction, actions) { change(config.copy(threeFingerHoldAction = it)) } + GestureHoldOptions(config.threeFingerHoldAction, config.threeFingerHoldMouseBehavior, config.threeFingerHoldDelay, { change(config.copy(threeFingerHoldMouseBehavior = it)) }, { change(config.copy(threeFingerHoldDelay = it)) }) + } + } + 3 -> { + GestureSection(R.string.gesture_tab_options, R.string.gesture_options_hint) + GestureSettingsCard(R.string.gesture_movement) { + Text(stringResource(R.string.gesture_movement_hint), color = p.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium) + GestureChoiceChips(config.mouseDragMovementMode, listOf(MOUSE_DRAG_MOVEMENT_DIRECT to stringResource(R.string.gesture_direct), MOUSE_DRAG_MOVEMENT_RELATIVE to stringResource(R.string.gesture_relative))) { change(config.copy(mouseDragMovementMode = it)) } + Text(stringResource(R.string.gesture_middle_relative_hint), color = p.onSurfaceVariant, style = MaterialTheme.typography.bodySmall) + } + GestureSettingsCard(R.string.gesture_recognition) { + Text(stringResource(R.string.gesture_threshold, config.gestureThreshold), style = MaterialTheme.typography.bodyMedium) + Slider(config.gestureThreshold.toFloat(), { change(config.copy(gestureThreshold = it.toInt())) }, valueRange = 10f..100f, steps = 17) + Text(stringResource(R.string.gesture_threshold_hint), color = p.onSurfaceVariant, style = MaterialTheme.typography.bodySmall) + } + GestureSettingsCard(R.string.gesture_feedback) { + GestureToggle(R.string.gesture_debug, config.showGestureDebugOverlay) { change(config.copy(showGestureDebugOverlay = it)) } + } + OutlinedButton(onClick = { change(TouchGestureConfig()) }, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.gesture_reset)) } + } + } + } + } + } +} + +@Composable +private fun GestureDialogFrame(title: String, subtitle: String, onDismiss: () -> Unit, + footer: @Composable () -> Unit = {}, content: @Composable ColumnScope.() -> Unit) { + val p = LocalPalette.current + // The app window does not opt into RTL, so these dialogs follow their resource locale explicitly. + val direction = if (LocalConfiguration.current.layoutDirection == android.view.View.LAYOUT_DIRECTION_RTL) LayoutDirection.Rtl else LayoutDirection.Ltr + Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) { + CompositionLocalProvider(LocalLayoutDirection provides direction) { + Box(Modifier.fillMaxSize().systemBarsPadding().imePadding().padding(12.dp), contentAlignment = Alignment.Center) { + Surface(Modifier.widthIn(max = 1040.dp).fillMaxWidth().fillMaxHeight(), shape = RoundedCornerShape(22.dp), color = p.background, + contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2)) { + Column { + Row(Modifier.fillMaxWidth().padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 12.dp), verticalAlignment = Alignment.CenterVertically) { + Surface(shape = RoundedCornerShape(12.dp), color = p.primary.copy(alpha = 0.14f)) { + Icon(Icons.Default.TouchApp, null, tint = p.primary, modifier = Modifier.padding(10.dp).size(24.dp)) + } + Column(Modifier.weight(1f).padding(horizontal = 14.dp), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text(title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.SemiBold) + Text(subtitle, style = MaterialTheme.typography.bodySmall, color = p.onSurfaceVariant) + } + IconButton(onClick = onDismiss) { Icon(Icons.Default.Close, stringResource(R.string.gesture_close)) } + } + content() + HorizontalDivider(color = p.line) + footer() + } + } + } + } + } +} + +@Composable +private fun GestureSection(@StringRes title: Int, @StringRes hint: Int) { + Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(stringResource(title), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold) + Text(stringResource(hint), style = MaterialTheme.typography.bodyMedium, color = LocalPalette.current.onSurfaceVariant) + } +} + +@Composable +private fun GestureCard(@StringRes title: Int, checked: Boolean, onToggle: (Boolean) -> Unit, + content: @Composable ColumnScope.() -> Unit) { + val p = LocalPalette.current + Surface(Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), color = p.surface, + border = BorderStroke(1.dp, if (checked) p.line2 else p.line)) { + Column { + Row(Modifier.fillMaxWidth().toggleable(checked, role = Role.Switch, onValueChange = onToggle) + .padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f).padding(end = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text(stringResource(title), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) + } + Switch(checked, onCheckedChange = null) + } + if (checked) Column(Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), content = content) + } + } +} + +@Composable +private fun GestureActionField(id: String, @StringRes gesture: Int, selected: String, choices: List, onChoose: (String) -> Unit) { + var open by remember { mutableStateOf(false) } + val p = LocalPalette.current + Surface(onClick = { open = true }, modifier = Modifier.fillMaxWidth().testTag("gesture-choice-$id"), shape = RoundedCornerShape(10.dp), + color = p.surfaceVariant, contentColor = p.onBackground, border = BorderStroke(1.dp, p.line2)) { + Row(Modifier.padding(horizontal = 14.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text(stringResource(R.string.gesture_action_label), color = p.onSurfaceVariant, style = MaterialTheme.typography.labelSmall) + Text(gestureActionTitle(selected), style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium) + } + Icon(Icons.AutoMirrored.Filled.ArrowForward, null, modifier = Modifier.size(19.dp), tint = p.onSurfaceVariant) + } + } + if (open) GestureActionPicker(choices, selected, stringResource(gesture), onDismiss = { open = false }) { open = false; onChoose(it) } +} + +@Composable +internal fun GestureActionPicker(choices: List, selected: String, gesture: String, onDismiss: () -> Unit, onChoose: (String) -> Unit) { + var query by rememberSaveable { mutableStateOf("") } + var category by remember { mutableStateOf(null) } + val catalog = choices.distinct().map { GestureAction(it, gestureActionTitle(it), gestureActionGroup(it)) } + val groups = GestureActionGroup.entries.filter { group -> catalog.any { it.group == group } } + val shown = filterGestureActions(catalog, query, category) + val p = LocalPalette.current + GestureDialogFrame(stringResource(R.string.gesture_action), stringResource(R.string.gesture_action_for, gesture), onDismiss) { + OutlinedTextField(query, onValueChange = { query = it }, modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).testTag("gesture-action-search"), + singleLine = true, shape = RoundedCornerShape(12.dp), placeholder = { Text(stringResource(R.string.gesture_search_actions)) }, + leadingIcon = { Icon(Icons.Default.Search, null) }, trailingIcon = { + if (query.isNotEmpty()) IconButton(onClick = { query = "" }) { Icon(Icons.Default.Close, stringResource(R.string.gesture_clear_search)) } + }) + Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + GestureFilterChip(category == null, onClick = { category = null }, label = { Text(stringResource(R.string.gesture_all_actions)) }) + if (groups.size > 1) groups.forEach { group -> + GestureFilterChip(category == group, onClick = { category = group }, label = { Text(stringResource(group.title)) }, modifier = Modifier.testTag("gesture-category-${group.name}")) + } + } + if (shown.isEmpty()) Box(Modifier.weight(1f).fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { + Text(stringResource(R.string.gesture_no_actions), color = p.onSurfaceVariant) + } else LazyColumn(Modifier.weight(1f).fillMaxWidth().testTag("gesture-action-list"), contentPadding = PaddingValues(start = 20.dp, end = 20.dp, bottom = 16.dp), + verticalArrangement = Arrangement.spacedBy(6.dp)) { + groups.forEach { group -> + val entries = shown.filter { it.group == group } + if (entries.isNotEmpty()) { + item(key = group.name) { Text(stringResource(group.title), style = MaterialTheme.typography.labelLarge, color = p.onSurfaceVariant, modifier = Modifier.padding(top = 12.dp, bottom = 5.dp)) } + items(entries, key = { it.id }) { action -> + val isSelected = action.id == selected + Surface(shape = RoundedCornerShape(12.dp), color = if (isSelected) p.primary.copy(alpha = 0.12f) else p.surface, + border = BorderStroke(1.dp, if (isSelected) p.primary else p.line)) { + Row(Modifier.fillMaxWidth().selectable(isSelected, role = Role.RadioButton, onClick = { onChoose(action.id) }) + .testTag("gesture-action-${action.id}").padding(horizontal = 14.dp, vertical = 9.dp), verticalAlignment = Alignment.CenterVertically) { + Icon(when (group) { GestureActionGroup.MOUSE -> Icons.Default.Mouse; GestureActionGroup.APP -> Icons.Default.TouchApp; else -> Icons.Default.Keyboard }, + null, tint = if (isSelected) p.primary else p.onSurfaceVariant, modifier = Modifier.size(22.dp)) + Text(action.title, Modifier.weight(1f).padding(horizontal = 14.dp), style = MaterialTheme.typography.bodyLarge) + RadioButton(isSelected, onClick = null) + } + } + } + } + } + } + } +} + +@Composable +private fun GestureHoldOptions(action: String, behavior: String, delay: Int, onBehavior: (String) -> Unit, onDelay: (Int) -> Unit) { + if (TouchGestureConfig.isMouseButtonAction(action)) { + Text(stringResource(R.string.gesture_mouse_behavior), style = MaterialTheme.typography.labelMedium, color = LocalPalette.current.onSurfaceVariant) + GestureChoiceChips(behavior, listOf(MOUSE_BEHAVIOR_HOLD to stringResource(R.string.gesture_hold_button), MOUSE_BEHAVIOR_CLICK to stringResource(R.string.gesture_click_once)), onBehavior) + } + GestureDelay(stringResource(R.string.gesture_hold_delay), delay, onDelay) +} + +@Composable +private fun GestureFilterChip(selected: Boolean, onClick: () -> Unit, label: @Composable () -> Unit, modifier: Modifier = Modifier) { + val p = LocalPalette.current + FilterChip(selected, onClick, label, modifier = modifier, colors = FilterChipDefaults.filterChipColors( + containerColor = p.surface, labelColor = p.onSurfaceVariant, + selectedContainerColor = p.primary.copy(alpha = 0.16f), selectedLabelColor = p.onBackground)) +} + +@Composable +private fun GestureChoiceChips(selected: String, options: List>, choose: (String) -> Unit) { + Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { + options.forEach { (id, label) -> GestureFilterChip(selected == id, onClick = { choose(id) }, label = { Text(label) }) } + } +} + +@Composable +private fun GestureSettingsCard(@StringRes title: Int, content: @Composable ColumnScope.() -> Unit) { + val p = LocalPalette.current + Surface(shape = RoundedCornerShape(16.dp), color = p.surface, border = BorderStroke(1.dp, p.line)) { + Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text(stringResource(title), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold) + content() + } + } +} + +@Composable +private fun GestureToggle(@StringRes title: Int, checked: Boolean, change: (Boolean) -> Unit) { + Row(Modifier.fillMaxWidth().toggleable(checked, role = Role.Switch, onValueChange = change).padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically) { + Text(stringResource(title), Modifier.weight(1f).padding(end = 12.dp), style = MaterialTheme.typography.bodyMedium) + Switch(checked, null) + } +} + +@Composable +private fun GestureDelay(label: String, value: Int, change: (Int) -> Unit) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(label, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium) + Text(stringResource(R.string.gesture_ms, value), Modifier.background(LocalPalette.current.surfaceVariant, RoundedCornerShape(6.dp)).padding(horizontal = 10.dp, vertical = 5.dp), style = MaterialTheme.typography.labelLarge) + } + Slider(value.toFloat().coerceIn(100f, 1000f), { change((it / 50).toInt() * 50) }, valueRange = 100f..1000f, steps = 17) +} diff --git a/app/src/main/res/values-ar/gestures.xml b/app/src/main/res/values-ar/gestures.xml new file mode 100644 index 0000000000..5aee4b085d --- /dev/null +++ b/app/src/main/res/values-ar/gestures.xml @@ -0,0 +1,103 @@ + + + الإيماءات + إعدادات إيماءات اللمس + خصّص إيماءات الفأرة ولوحة المفاتيح. اختر الإيماءات كوضع للمس لاستخدامها. + نقرة + سحب بإصبع واحد + ضغط مطوّل + نقر مزدوج (نقرتان بالزر الأيسر) + نقر بإصبعين + سحب بإصبعين + ضغط مستمر بإصبعين + نقر بثلاثة أصابع + سحب بثلاثة أصابع + ضغط مستمر بثلاثة أصابع + ضمّ الإصبعين أو إبعادهما للتكبير والتصغير + إبقاء الزر مضغوطًا + النقر مرة واحدة + مهلة الضغط المستمر + الفاصل بين النقرتين + ينطبق على اللعبة الحالية + الإعدادات الافتراضية لجميع الألعاب + استعادة إعدادات الإيماءات الأصلية + إلغاء + اختيار إجراء + نقر بالزر الأيسر + نقر بالزر الأيمن + نقر بالزر الأوسط + إظهار لوحة المفاتيح + نقر أيسر وسحب + نقر أيمن وسحب + تحريك العرض بزر الفأرة الأوسط + تحريك العرض بزر الفأرة الأوسط (معكوس) + مفاتيح الأسهم + مفاتيح الأسهم (معكوسة) + WASD (معكوس) + عجلة الفأرة + عتبة الإيماءات: %1$d بكسل + إظهار الإيماءة المكتشفة + عناصر تحكم الفأرة ولوحة المفاتيح مرتبة حسب الإيماءة + إصبع واحد + إصبعان + ثلاثة أصابع + خيارات + اختر إجراء النقر أو السحب أو الضغط المستمر. + اضبط تحريك الكاميرا والتكبير والنقرات الثانوية. + اجعل الاختصارات الإضافية في متناولك. + اضبط الحركة والتعرّف والاستجابة المرئية. + الافتراضية + هذه اللعبة + استخدام الإعدادات الافتراضية + تُستخدم الإعدادات الافتراضية. يؤدي التعديل إلى إنشاء إعدادات خاصة باللعبة. + حفظ التغييرات + إغلاق + الإجراء + لـ %1$s + البحث عن إجراءات الفأرة أو مفاتيح لوحة المفاتيح + مسح البحث + الكل + لا توجد إجراءات مطابقة. جرّب اسم مفتاح أو إجراء آخر. + الفأرة + إجراءات التطبيق + التنقل + الأحرف + الأرقام + مفاتيح الوظائف + مفاتيح التعديل + لوحة الأرقام + الرموز + حركة الفأرة + يتبع السحب المباشر موضع اللمس. ويتبع السحب النسبي حركة الإصبع، وهو مفيد عندما تعيد اللعبة الفأرة إلى المنتصف. + يتبع تحريك العرض بالزر الأوسط حركة الإصبع دائمًا لتجنّب قفزات المؤشر. + مباشر + نسبي + التعرّف على الإيماءات + تحرّك هذه المسافة قبل أن تتحول إيماءة بإصبعين أو ثلاثة إلى تحريك العرض أو التكبير. + الاستجابة المرئية + سلوك زر الفأرة + %1$d مللي ثانية + لوحة الأرقام %1$s + هروب + مسافة للخلف + إدخال + Tab + مسافة + حذف + إدراج + Home + End + صفحة لأعلى + صفحة لأسفل + طباعة الشاشة + سهم لأعلى + سهم لأسفل + سهم لليسار + سهم لليمين + قفل الأحرف الكبيرة + قفل الأرقام + قفل التمرير + %1$s الأيسر + %1$s الأيمن + Shift + diff --git a/app/src/main/res/values-b+es+419/gestures.xml b/app/src/main/res/values-b+es+419/gestures.xml new file mode 100644 index 0000000000..13a89a1b84 --- /dev/null +++ b/app/src/main/res/values-b+es+419/gestures.xml @@ -0,0 +1,103 @@ + + + Gestos + Ajustes de gestos táctiles + Personaliza los gestos de ratón y teclado. Selecciona Gestos como modo táctil para usarlos. + Toque + Arrastre con un dedo + Pulsación prolongada + Doble toque (doble clic izquierdo) + Toque con dos dedos + Arrastre con dos dedos + Pulsación sostenida con dos dedos + Toque con tres dedos + Arrastre con tres dedos + Pulsación sostenida con tres dedos + Pellizcar para ampliar + Mantener el botón pulsado + Hacer clic una vez + Tiempo de pulsación sostenida + Intervalo de doble toque + Se aplica al juego actual + Ajustes predeterminados para todos los juegos + Restablecer los ajustes originales de gestos + Cancelar + Elegir acción + Clic izquierdo + Clic derecho + Clic central + Mostrar teclado + Clic izquierdo y arrastre + Clic derecho y arrastre + Desplazamiento con el botón central + Desplazamiento con el botón central (invertido) + Teclas de dirección + Teclas de dirección (invertidas) + WASD (invertido) + Rueda del ratón + Umbral de gestos: %1$d px + Mostrar gesto reconocido + Controles de ratón y teclado organizados por gesto + Un dedo + Dos dedos + Tres dedos + Opciones + Elige qué debe hacer un toque, arrastre o pulsación sostenida. + Configura el movimiento de cámara, el zoom y los clics secundarios. + Ten más accesos directos al alcance de la mano. + Ajusta el movimiento, el reconocimiento y la respuesta visual. + Predeterminados + Este juego + Usar valores predeterminados + Se usan los ajustes predeterminados. Al editarlos, se crean ajustes específicos del juego. + Guardar cambios + Cerrar + ACCIÓN + Para %1$s + Buscar acciones de ratón o teclas del teclado + Borrar búsqueda + Todas + No hay acciones coincidentes. Prueba con otro nombre de tecla o acción. + Ratón + Acciones de la aplicación + Navegación + Letras + Números + Teclas de función + Teclas modificadoras + Teclado numérico + Símbolos + Movimiento del ratón + El arrastre directo sigue la posición del toque. El relativo sigue el movimiento del dedo y resulta útil cuando un juego centra el ratón. + El desplazamiento con el botón central siempre sigue el movimiento del dedo para evitar saltos del cursor. + Directo + Relativo + Reconocimiento de gestos + Recorre esta distancia antes de que un gesto con dos o tres dedos se convierta en desplazamiento o zoom. + Respuesta visual + Comportamiento del botón del ratón + %1$d ms + Teclado numérico %1$s + Escape + Retroceso + Intro + Tab + Espacio + Supr + Insertar + Inicio + Fin + Re Pág + Av Pág + Impr Pant + Flecha arriba + Flecha abajo + Flecha izquierda + Flecha derecha + Bloq Mayús + Bloq Num + Bloq Despl + %1$s izquierdo + %1$s derecho + Mayús + diff --git a/app/src/main/res/values-bg/gestures.xml b/app/src/main/res/values-bg/gestures.xml new file mode 100644 index 0000000000..4c389aaba6 --- /dev/null +++ b/app/src/main/res/values-bg/gestures.xml @@ -0,0 +1,103 @@ + + + Жестове + Настройки на сензорните жестове + Настройте жестовете за мишка и клавиатура. За да ги използвате, изберете сензорен режим „Жестове“. + Докосване + Плъзгане с един пръст + Продължително натискане + Двойно докосване (двойно ляво щракване) + Докосване с два пръста + Плъзгане с два пръста + Задържане с два пръста + Докосване с три пръста + Плъзгане с три пръста + Задържане с три пръста + Мащабиране със събиране или раздалечаване на пръстите + Задържане на бутона натиснат + Еднократно щракване + Закъснение за задържане + Интервал за двойно докосване + Прилага се към текущата игра + Настройки по подразбиране за всички игри + Възстановяване на първоначалните настройки на жестовете + Отказ + Избор на действие + Ляво щракване + Дясно щракване + Средно щракване + Показване на клавиатурата + Ляво щракване и плъзгане + Дясно щракване и плъзгане + Преместване със средния бутон + Преместване със средния бутон (обърнато) + Клавиши със стрелки + Клавиши със стрелки (обърнати) + WASD (обърнато) + Колелце на мишката + Праг на жестовете: %1$d пиксела + Показване на разпознатия жест + Управление с мишка и клавиатура, подредено по жестове + Един пръст + Два пръста + Три пръста + Опции + Изберете действието при докосване, плъзгане или задържане. + Настройте преместването на камерата, мащабирането и вторичните щраквания. + Дръжте допълнителните команди подръка. + Настройте движението, разпознаването и визуалната обратна връзка. + Стандартни настройки + Тази игра + Използване на подразбиращите се + Използват се настройките по подразбиране. Редактирането създава настройки за тази игра. + Запазване на промените + Затвори + ДЕЙСТВИЕ + За %1$s + Търсене на действия с мишката или клавиши + Изчистване на търсенето + Всички + Няма съвпадащи действия. Опитайте друго име на клавиш или действие. + Мишка + Действия на приложението + Навигация + Букви + Цифри + Функционални клавиши + Модифициращи клавиши + Цифрова клавиатура + Символи + Движение на мишката + Директното плъзгане следва мястото на докосване. Относителното следва движението на пръста и е полезно, когато играта центрира мишката. + Преместването със средния бутон винаги следва движението на пръста, за да няма скокове на курсора. + Директно + Относително + Разпознаване на жестове + Изминете това разстояние, преди жест с два или три пръста да стане преместване или мащабиране. + Визуална обратна връзка + Поведение на бутона на мишката + %1$d мс + Цифрова клавиатура %1$s + Esc + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Стрелка нагоре + Стрелка надолу + Стрелка наляво + Стрелка надясно + Caps Lock + Num Lock + Scroll Lock + Ляв %1$s + Десен %1$s + Shift + diff --git a/app/src/main/res/values-cs/gestures.xml b/app/src/main/res/values-cs/gestures.xml new file mode 100644 index 0000000000..81de9094de --- /dev/null +++ b/app/src/main/res/values-cs/gestures.xml @@ -0,0 +1,103 @@ + + + Gesta + Nastavení dotykových gest + Přizpůsobte gesta myši a klávesnice. Chcete-li je používat, vyberte dotykový režim Gesta. + Klepnutí + Tažení jedním prstem + Dlouhé stisknutí + Dvojité klepnutí (dvojklik levým tlačítkem) + Klepnutí dvěma prsty + Tažení dvěma prsty + Podržení dvěma prsty + Klepnutí třemi prsty + Tažení třemi prsty + Podržení třemi prsty + Přiblížení sevřením či rozevřením prstů + Držet tlačítko stisknuté + Jednou kliknout + Prodleva podržení + Interval dvojitého klepnutí + Platí pro aktuální hru + Výchozí nastavení pro všechny hry + Obnovit původní nastavení gest + Zrušit + Vybrat akci + Levé kliknutí + Pravé kliknutí + Prostřední kliknutí + Zobrazit klávesnici + Levé kliknutí a tažení + Pravé kliknutí a tažení + Posouvání prostředním tlačítkem myši + Posouvání prostředním tlačítkem myši (obráceně) + Šipky + Šipky (obráceně) + WASD (obráceně) + Kolečko myši + Práh gest: %1$d px + Zobrazovat rozpoznané gesto + Ovládání myši a klávesnice uspořádané podle gest + Jeden prst + Dva prsty + Tři prsty + Možnosti + Vyberte akci pro klepnutí, tažení nebo podržení. + Nastavte posouvání kamery, přiblížení a vedlejší kliknutí. + Mějte další zkratky na dosah. + Upravte pohyb, rozpoznávání a vizuální odezvu. + Výchozí + Tato hra + Použít výchozí + Používá se výchozí nastavení. Úpravou vznikne nastavení pro tuto hru. + Uložit změny + Zavřít + AKCE + Pro %1$s + Hledat akce myši nebo klávesy + Vymazat hledání + Vše + Žádné odpovídající akce. Zkuste jiný název klávesy nebo akce. + Myš + Akce aplikace + Navigace + Písmena + Číslice + Funkční klávesy + Modifikační klávesy + Numerická klávesnice + Symboly + Pohyb myši + Přímé tažení sleduje polohu dotyku. Relativní tažení sleduje pohyb prstu a hodí se, když hra vrací myš do středu. + Posouvání prostředním tlačítkem vždy sleduje pohyb prstu, aby kurzor nepřeskakoval. + Přímé + Relativní + Rozpoznávání gest + Po překonání této vzdálenosti se gesto dvěma či třemi prsty změní na posouvání nebo přiblížení. + Vizuální odezva + Chování tlačítka myši + %1$d ms + Numerická klávesnice %1$s + Esc + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Šipka nahoru + Šipka dolů + Šipka vlevo + Šipka vpravo + Caps Lock + Num Lock + Scroll Lock + Levý %1$s + Pravý %1$s + Shift + diff --git a/app/src/main/res/values-da/gestures.xml b/app/src/main/res/values-da/gestures.xml new file mode 100644 index 0000000000..e7b0cc1dc4 --- /dev/null +++ b/app/src/main/res/values-da/gestures.xml @@ -0,0 +1,103 @@ + + + Bevægelser + Indstillinger for berøringsbevægelser + Tilpas muse- og tastaturbevægelser. Vælg Bevægelser som berøringstilstand for at bruge dem. + Tryk + Træk med én finger + Langt tryk + Dobbelttryk (dobbelt venstreklik) + Tryk med to fingre + Træk med to fingre + Hold med to fingre + Tryk med tre fingre + Træk med tre fingre + Hold med tre fingre + Knib for at zoome + Hold knappen nede + Klik én gang + Forsinkelse før hold + Interval for dobbelttryk + Gælder det aktuelle spil + Standardindstillinger for alle spil + Gendan de oprindelige bevægelsesindstillinger + Annuller + Vælg handling + Venstreklik + Højreklik + Midterklik + Vis tastatur + Venstreklik og træk + Højreklik og træk + Panorering med midterste museknap + Panorering med midterste museknap (omvendt) + Piletaster + Piletaster (omvendt) + WASD (omvendt) + Musehjul + Bevægelsestærskel: %1$d px + Vis genkendt bevægelse + Muse- og tastaturstyring organiseret efter bevægelse + Én finger + To fingre + Tre fingre + Indstillinger + Vælg, hvad et tryk, træk eller hold skal gøre. + Indstil kamerapanorering, zoom og sekundære klik. + Hav flere genveje inden for rækkevidde. + Juster bevægelse, genkendelse og visuel feedback. + Standarder + Dette spil + Brug standardindstillinger + Bruger standardindstillingerne. Redigering opretter særlige indstillinger for spillet. + Gem ændringer + Luk + HANDLING + For %1$s + Søg efter musehandlinger eller tastaturtaster + Ryd søgning + Alle + Ingen matchende handlinger. Prøv et andet navn på en tast eller handling. + Mus + Apphandlinger + Navigation + Bogstaver + Tal + Funktionstaster + Modifikationstaster + Numerisk tastatur + Symboler + Musebevægelse + Direkte træk følger berøringspositionen. Relative træk følger fingerbevægelsen og er nyttige, når et spil centrerer musen. + Panorering med midterste museknap følger altid fingerbevægelsen for at undgå markørspring. + Direkte + Relativ + Genkendelse af bevægelser + Bevæg fingrene så langt, før en bevægelse med to eller tre fingre bliver til panorering eller zoom. + Visuel feedback + Museknappens funktion + %1$d ms + Numerisk tastatur %1$s + Escape + Tilbage + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Pil op + Pil ned + Pil til venstre + Pil til højre + Caps Lock + Num Lock + Scroll Lock + Venstre %1$s + Højre %1$s + Skift + diff --git a/app/src/main/res/values-de/gestures.xml b/app/src/main/res/values-de/gestures.xml new file mode 100644 index 0000000000..22b750ece8 --- /dev/null +++ b/app/src/main/res/values-de/gestures.xml @@ -0,0 +1,103 @@ + + + Gesten + Touchgesten-Einstellungen + Maus- und Tastaturgesten anpassen. Wähle Gesten als Touchmodus, um sie zu verwenden. + Tippen + Mit einem Finger ziehen + Lange drücken + Doppeltippen (doppelter Linksklick) + Mit zwei Fingern tippen + Mit zwei Fingern ziehen + Mit zwei Fingern halten + Mit drei Fingern tippen + Mit drei Fingern ziehen + Mit drei Fingern halten + Zum Zoomen Finger zusammen- oder auseinanderziehen + Taste gedrückt halten + Einmal klicken + Halteverzögerung + Doppeltipp-Intervall + Gilt für das aktuelle Spiel + Standardeinstellungen für alle Spiele + Ursprüngliche Gesteneinstellungen wiederherstellen + Abbrechen + Aktion auswählen + Linksklick + Rechtsklick + Mittelklick + Tastatur einblenden + Linksklick und ziehen + Rechtsklick und ziehen + Mit mittlerer Maustaste schwenken + Mit mittlerer Maustaste schwenken (umgekehrt) + Pfeiltasten + Pfeiltasten (umgekehrt) + WASD (umgekehrt) + Mausrad + Gestenschwelle: %1$d px + Erkannte Geste anzeigen + Maus- und Tastatursteuerung nach Gesten geordnet + Ein Finger + Zwei Finger + Drei Finger + Optionen + Wähle die Aktion für Tippen, Ziehen oder Halten. + Kameraschwenks, Zoom und sekundäre Klicks anpassen. + Zusätzliche Kurzbefehle griffbereit halten. + Bewegung, Erkennung und visuelle Rückmeldung anpassen. + Standardwerte + Dieses Spiel + Standardeinstellungen verwenden + Standardeinstellungen werden verwendet. Änderungen erstellen eine Spielanpassung. + Änderungen speichern + Schließen + AKTION + Für %1$s + Mausaktionen oder Tastaturtasten suchen + Suche leeren + Alle + Keine passenden Aktionen. Versuche einen anderen Tasten- oder Aktionsnamen. + Maus + App-Aktionen + Navigation + Buchstaben + Zahlen + Funktionstasten + Modifikatortasten + Ziffernblock + Symbole + Mausbewegung + Direktes Ziehen folgt der Berührungsposition. Relatives Ziehen folgt der Fingerbewegung und eignet sich für Spiele, die die Maus zentrieren. + Schwenks mit mittlerer Maustaste folgen immer der Fingerbewegung, um Zeigersprünge zu vermeiden. + Direkt + Relativ + Gestenerkennung + Bewege die Finger um diese Strecke, bevor eine Zwei- oder Dreifingergeste als Schwenken oder Zoomen gilt. + Visuelle Rückmeldung + Verhalten der Maustaste + %1$d ms + Ziffernblock %1$s + Esc + Rücktaste + Eingabetaste + Tab + Leertaste + Entf + Einfg + Pos1 + Ende + Bild auf + Bild ab + Druck + Pfeil nach oben + Pfeil nach unten + Pfeil nach links + Pfeil nach rechts + Feststelltaste + Num-Feststelltaste + Rollen-Feststelltaste + Linke %1$s + Rechte %1$s + Umschalt + diff --git a/app/src/main/res/values-el/gestures.xml b/app/src/main/res/values-el/gestures.xml new file mode 100644 index 0000000000..65b86e4a7a --- /dev/null +++ b/app/src/main/res/values-el/gestures.xml @@ -0,0 +1,103 @@ + + + Χειρονομίες + Ρυθμίσεις χειρονομιών αφής + Προσαρμόστε τις χειρονομίες ποντικιού και πληκτρολογίου. Επιλέξτε Χειρονομίες ως λειτουργία αφής για να τις χρησιμοποιήσετε. + Πάτημα + Σύρσιμο με ένα δάχτυλο + Παρατεταμένο πάτημα + Διπλό πάτημα (διπλό αριστερό κλικ) + Πάτημα με δύο δάχτυλα + Σύρσιμο με δύο δάχτυλα + Κράτημα με δύο δάχτυλα + Πάτημα με τρία δάχτυλα + Σύρσιμο με τρία δάχτυλα + Κράτημα με τρία δάχτυλα + Μεγέθυνση με τσίμπημα + Διατήρηση του κουμπιού πατημένου + Ένα κλικ + Καθυστέρηση κρατήματος + Διάστημα διπλού πατήματος + Ισχύει για το τρέχον παιχνίδι + Προεπιλεγμένες ρυθμίσεις για όλα τα παιχνίδια + Επαναφορά αρχικών ρυθμίσεων χειρονομιών + Ακύρωση + Επιλογή ενέργειας + Αριστερό κλικ + Δεξί κλικ + Μεσαίο κλικ + Εμφάνιση πληκτρολογίου + Αριστερό κλικ και σύρσιμο + Δεξί κλικ και σύρσιμο + Μετατόπιση με το μεσαίο κουμπί + Μετατόπιση με το μεσαίο κουμπί (αντίστροφη) + Πλήκτρα βέλους + Πλήκτρα βέλους (αντίστροφα) + WASD (αντίστροφα) + Ροδέλα ποντικιού + Όριο χειρονομιών: %1$d px + Εμφάνιση αναγνωρισμένης χειρονομίας + Χειρισμοί ποντικιού και πληκτρολογίου ανά χειρονομία + Ένα δάχτυλο + Δύο δάχτυλα + Τρία δάχτυλα + Επιλογές + Επιλέξτε την ενέργεια για πάτημα, σύρσιμο ή κράτημα. + Ρυθμίστε τη μετατόπιση της κάμερας, τη μεγέθυνση και τα δευτερεύοντα κλικ. + Κρατήστε επιπλέον συντομεύσεις κοντά σας. + Ρυθμίστε την κίνηση, την αναγνώριση και την οπτική ανάδραση. + Προεπιλογές + Αυτό το παιχνίδι + Χρήση προεπιλογών + Χρησιμοποιούνται οι προεπιλογές. Η επεξεργασία δημιουργεί ρυθμίσεις για αυτό το παιχνίδι. + Αποθήκευση αλλαγών + Κλείσιμο + ΕΝΕΡΓΕΙΑ + Για %1$s + Αναζήτηση ενεργειών ποντικιού ή πλήκτρων + Εκκαθάριση αναζήτησης + Όλα + Δεν βρέθηκαν ενέργειες. Δοκιμάστε άλλο όνομα πλήκτρου ή ενέργειας. + Ποντίκι + Ενέργειες εφαρμογής + Πλοήγηση + Γράμματα + Αριθμοί + Πλήκτρα λειτουργιών + Πλήκτρα τροποποίησης + Αριθμητικό πληκτρολόγιο + Σύμβολα + Κίνηση ποντικιού + Το άμεσο σύρσιμο ακολουθεί τη θέση αφής. Το σχετικό σύρσιμο ακολουθεί την κίνηση του δαχτύλου, χρήσιμο όταν το παιχνίδι επαναφέρει το ποντίκι στο κέντρο. + Η μετατόπιση με το μεσαίο κουμπί ακολουθεί πάντα την κίνηση του δαχτύλου για να αποφεύγονται άλματα του δείκτη. + Απευθείας + Σχετική + Αναγνώριση χειρονομιών + Κινηθείτε κατά αυτή την απόσταση προτού μια χειρονομία με δύο ή τρία δάχτυλα γίνει μετατόπιση ή μεγέθυνση. + Οπτική ανάδραση + Συμπεριφορά κουμπιού ποντικιού + %1$d ms + Αριθμητικό πληκτρολόγιο %1$s + Escape + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Βέλος πάνω + Βέλος κάτω + Βέλος αριστερά + Βέλος δεξιά + Caps Lock + Num Lock + Scroll Lock + Αριστερό %1$s + Δεξί %1$s + Shift + diff --git a/app/src/main/res/values-es/gestures.xml b/app/src/main/res/values-es/gestures.xml new file mode 100644 index 0000000000..13a89a1b84 --- /dev/null +++ b/app/src/main/res/values-es/gestures.xml @@ -0,0 +1,103 @@ + + + Gestos + Ajustes de gestos táctiles + Personaliza los gestos de ratón y teclado. Selecciona Gestos como modo táctil para usarlos. + Toque + Arrastre con un dedo + Pulsación prolongada + Doble toque (doble clic izquierdo) + Toque con dos dedos + Arrastre con dos dedos + Pulsación sostenida con dos dedos + Toque con tres dedos + Arrastre con tres dedos + Pulsación sostenida con tres dedos + Pellizcar para ampliar + Mantener el botón pulsado + Hacer clic una vez + Tiempo de pulsación sostenida + Intervalo de doble toque + Se aplica al juego actual + Ajustes predeterminados para todos los juegos + Restablecer los ajustes originales de gestos + Cancelar + Elegir acción + Clic izquierdo + Clic derecho + Clic central + Mostrar teclado + Clic izquierdo y arrastre + Clic derecho y arrastre + Desplazamiento con el botón central + Desplazamiento con el botón central (invertido) + Teclas de dirección + Teclas de dirección (invertidas) + WASD (invertido) + Rueda del ratón + Umbral de gestos: %1$d px + Mostrar gesto reconocido + Controles de ratón y teclado organizados por gesto + Un dedo + Dos dedos + Tres dedos + Opciones + Elige qué debe hacer un toque, arrastre o pulsación sostenida. + Configura el movimiento de cámara, el zoom y los clics secundarios. + Ten más accesos directos al alcance de la mano. + Ajusta el movimiento, el reconocimiento y la respuesta visual. + Predeterminados + Este juego + Usar valores predeterminados + Se usan los ajustes predeterminados. Al editarlos, se crean ajustes específicos del juego. + Guardar cambios + Cerrar + ACCIÓN + Para %1$s + Buscar acciones de ratón o teclas del teclado + Borrar búsqueda + Todas + No hay acciones coincidentes. Prueba con otro nombre de tecla o acción. + Ratón + Acciones de la aplicación + Navegación + Letras + Números + Teclas de función + Teclas modificadoras + Teclado numérico + Símbolos + Movimiento del ratón + El arrastre directo sigue la posición del toque. El relativo sigue el movimiento del dedo y resulta útil cuando un juego centra el ratón. + El desplazamiento con el botón central siempre sigue el movimiento del dedo para evitar saltos del cursor. + Directo + Relativo + Reconocimiento de gestos + Recorre esta distancia antes de que un gesto con dos o tres dedos se convierta en desplazamiento o zoom. + Respuesta visual + Comportamiento del botón del ratón + %1$d ms + Teclado numérico %1$s + Escape + Retroceso + Intro + Tab + Espacio + Supr + Insertar + Inicio + Fin + Re Pág + Av Pág + Impr Pant + Flecha arriba + Flecha abajo + Flecha izquierda + Flecha derecha + Bloq Mayús + Bloq Num + Bloq Despl + %1$s izquierdo + %1$s derecho + Mayús + diff --git a/app/src/main/res/values-fi/gestures.xml b/app/src/main/res/values-fi/gestures.xml new file mode 100644 index 0000000000..1cca2cb40e --- /dev/null +++ b/app/src/main/res/values-fi/gestures.xml @@ -0,0 +1,103 @@ + + + Eleet + Kosketuseleiden asetukset + Mukauta hiiri- ja näppäimistöeleitä. Ota ne käyttöön valitsemalla kosketustilaksi Eleet. + Napautus + Veto yhdellä sormella + Pitkä painallus + Kaksoisnapautus (vasemman painikkeen kaksoisnapsautus) + Napautus kahdella sormella + Veto kahdella sormella + Pito kahdella sormella + Napautus kolmella sormella + Veto kolmella sormella + Pito kolmella sormella + Zoomaa nipistämällä + Pidä painike painettuna + Napsauta kerran + Pidon viive + Kaksoisnapautuksen aikaväli + Koskee nykyistä peliä + Kaikkien pelien oletusasetukset + Palauta alkuperäiset eleasetukset + Peruuta + Valitse toiminto + Vasen napsautus + Oikea napsautus + Keskinapsautus + Näytä näppäimistö + Vasen napsautus ja veto + Oikea napsautus ja veto + Panorointi hiiren keskipainikkeella + Panorointi hiiren keskipainikkeella (käänteinen) + Nuolinäppäimet + Nuolinäppäimet (käänteiset) + WASD (käänteinen) + Hiiren rulla + Elekynnys: %1$d px + Näytä tunnistettu ele + Hiiri- ja näppäimistöohjaus eleittäin + Yksi sormi + Kaksi sormea + Kolme sormea + Asetukset + Valitse napautuksen, vedon tai pidon toiminto. + Määritä kameran panorointi, zoomaus ja toissijaiset napsautukset. + Pidä lisäpikakomennot ulottuvillasi. + Säädä liikettä, tunnistusta ja visuaalista palautetta. + Oletukset + Tämä peli + Käytä oletuksia + Oletusasetukset ovat käytössä. Muokkaaminen luo pelikohtaiset asetukset. + Tallenna muutokset + Sulje + TOIMINTO + Kohteelle %1$s + Etsi hiiritoimintoja tai näppäimiä + Tyhjennä haku + Kaikki + Vastaavia toimintoja ei löytynyt. Kokeile toista näppäimen tai toiminnon nimeä. + Hiiri + Sovellustoiminnot + Siirtyminen + Kirjaimet + Numerot + Funktionäppäimet + Muunnosnäppäimet + Numeronäppäimistö + Symbolit + Hiiren liike + Suora veto seuraa kosketuskohtaa. Suhteellinen veto seuraa sormen liikettä ja sopii peleihin, jotka keskittävät hiiren. + Panorointi keskipainikkeella seuraa aina sormen liikettä, jotta osoitin ei hypi. + Suora + Suhteellinen + Eleiden tunnistus + Liikuta sormia tämän matkan verran, ennen kuin kahden tai kolmen sormen ele muuttuu panoroinniksi tai zoomaukseksi. + Visuaalinen palaute + Hiiripainikkeen toiminta + %1$d ms + Numeronäppäimistö %1$s + Esc + Askelpalautin + Enter + Tab + Space + Delete + Insert + Home + End + Sivu ylös + Sivu alas + Print Screen + Nuoli ylös + Nuoli alas + Nuoli vasemmalle + Nuoli oikealle + Caps Lock + Num Lock + Scroll Lock + Vasen %1$s + Oikea %1$s + Vaihto + diff --git a/app/src/main/res/values-fr/gestures.xml b/app/src/main/res/values-fr/gestures.xml new file mode 100644 index 0000000000..72c9b6a0b1 --- /dev/null +++ b/app/src/main/res/values-fr/gestures.xml @@ -0,0 +1,103 @@ + + + Gestes + Paramètres des gestes tactiles + Personnalisez les gestes de souris et de clavier. Sélectionnez Gestes comme mode tactile pour les utiliser. + Appui + Glissement à un doigt + Appui prolongé + Double appui (double clic gauche) + Appui à deux doigts + Glissement à deux doigts + Maintien à deux doigts + Appui à trois doigts + Glissement à trois doigts + Maintien à trois doigts + Pincer pour zoomer + Maintenir le bouton enfoncé + Cliquer une fois + Délai de maintien + Intervalle du double appui + S\'applique au jeu actuel + Paramètres par défaut pour tous les jeux + Rétablir les paramètres des gestes d\'origine + Annuler + Choisir une action + Clic gauche + Clic droit + Clic du milieu + Afficher le clavier + Clic gauche et glissement + Clic droit et glissement + Déplacement avec le bouton du milieu + Déplacement avec le bouton du milieu (inversé) + Touches fléchées + Touches fléchées (inversées) + WASD (inversé) + Molette de la souris + Seuil des gestes : %1$d px + Afficher le geste reconnu + Commandes de souris et de clavier organisées par geste + Un doigt + Deux doigts + Trois doigts + Options + Choisissez l\'action d\'un appui, d\'un glissement ou d\'un maintien. + Configurez les déplacements de caméra, le zoom et les clics secondaires. + Gardez des raccourcis supplémentaires à portée de main. + Ajustez les mouvements, la reconnaissance et le retour visuel. + Valeurs par défaut + Ce jeu + Utiliser les valeurs par défaut + Paramètres par défaut utilisés. Une modification crée des paramètres propres au jeu. + Enregistrer les modifications + Fermer + ACTION + Pour %1$s + Rechercher des actions de souris ou des touches du clavier + Effacer la recherche + Tout + Aucune action correspondante. Essayez un autre nom de touche ou d\'action. + Souris + Actions de l\'application + Navigation + Lettres + Chiffres + Touches de fonction + Touches de modification + Pavé numérique + Symboles + Mouvement de la souris + Le glissement direct suit la position du toucher. Le glissement relatif suit le mouvement du doigt, utile lorsqu\'un jeu recentre la souris. + Le déplacement avec le bouton du milieu suit toujours le mouvement du doigt pour éviter les sauts du curseur. + Direct + Relatif + Reconnaissance des gestes + Parcourez cette distance avant qu\'un geste à deux ou trois doigts soit reconnu comme un déplacement ou un zoom. + Retour visuel + Comportement du bouton de souris + %1$d ms + Pavé numérique %1$s + Échap + Retour arrière + Entrée + Tab + Espace + Suppr + Inser + Début + Fin + Page précédente + Page suivante + Impr. écran + Flèche haut + Flèche bas + Flèche gauche + Flèche droite + Verr. maj. + Verr. num. + Arrêt défil. + %1$s gauche + %1$s droite + Maj + diff --git a/app/src/main/res/values-hi/gestures.xml b/app/src/main/res/values-hi/gestures.xml new file mode 100644 index 0000000000..7d4a2365e9 --- /dev/null +++ b/app/src/main/res/values-hi/gestures.xml @@ -0,0 +1,103 @@ + + + जेस्चर + टच जेस्चर सेटिंग + माउस और कीबोर्ड जेस्चर बदलें। इस्तेमाल करने के लिए टच मोड में जेस्चर चुनें। + टैप + एक उँगली से खींचना + देर तक दबाना + दो बार टैप (दो बार बायाँ क्लिक) + दो उँगलियों से टैप + दो उँगलियों से खींचना + दो उँगलियों से दबाए रखना + तीन उँगलियों से टैप + तीन उँगलियों से खींचना + तीन उँगलियों से दबाए रखना + पिंच करके ज़ूम करें + बटन दबाए रखें + एक बार क्लिक करें + दबाए रखने का विलंब + दो टैप के बीच का अंतराल + मौजूदा गेम पर लागू होता है + सभी गेम की डिफ़ॉल्ट सेटिंग + जेस्चर की मूल सेटिंग वापस लाएँ + रद्द करें + कार्रवाई चुनें + बायाँ क्लिक + दायाँ क्लिक + बीच का क्लिक + कीबोर्ड दिखाएं + बायाँ क्लिक करके खींचना + दायाँ क्लिक करके खींचना + माउस के बीच वाले बटन से दृश्य खिसकाना + माउस के बीच वाले बटन से दृश्य खिसकाना (उल्टा) + तीर वाली कुंजियाँ + तीर वाली कुंजियाँ (उल्टी) + WASD (उल्टा) + माउस व्हील + जेस्चर की सीमा: %1$d पिक्सेल + पहचाना गया जेस्चर दिखाएँ + जेस्चर के अनुसार माउस और कीबोर्ड कंट्रोल + एक उँगली + दो उँगलियाँ + तीन उँगलियाँ + विकल्प + चुनें कि टैप करने, खींचने या दबाए रखने पर क्या हो। + कैमरा खिसकाना, ज़ूम और दूसरे क्लिक सेट करें। + अतिरिक्त शॉर्टकट आसानी से इस्तेमाल करें। + गति, पहचान और दृश्य प्रतिक्रिया में बदलाव करें। + डिफ़ॉल्ट + यह गेम + डिफ़ॉल्ट इस्तेमाल करें + डिफ़ॉल्ट सेटिंग इस्तेमाल हो रही हैं। बदलाव करने पर इस गेम की अलग सेटिंग बनेंगी। + बदलाव सेव करें + बंद करें + कार्रवाई + %1$s के लिए + माउस की कार्रवाइयाँ या कीबोर्ड की कुंजियाँ खोजें + खोज मिटाएँ + सभी + कोई मिलती-जुलती कार्रवाई नहीं मिली। किसी दूसरी कुंजी या कार्रवाई का नाम आज़माएँ। + माउस + ऐप की कार्रवाइयाँ + नेविगेशन + अक्षर + अंक + फ़ंक्शन कुंजियाँ + मॉडिफ़ायर कुंजियाँ + नंबर पैड + चिह्न + माउस की गति + सीधे खींचना छुई गई जगह के अनुसार चलता है। सापेक्ष खींचना उँगली की गति के अनुसार चलता है और गेम के माउस को बीच में लाने पर उपयोगी है। + माउस के बीच वाले बटन से दृश्य खिसकाना हमेशा उँगली की गति के अनुसार चलता है, ताकि कर्सर न उछले। + डायरेक्ट + सापेक्ष + जेस्चर की पहचान + दो या तीन उँगलियों का जेस्चर दृश्य खिसकाने या ज़ूम में बदलने से पहले इतनी दूरी तय करें। + दृश्य प्रतिक्रिया + माउस बटन का व्यवहार + %1$d मिलीसेकंड + नंबर पैड %1$s + एस्केप + बैकस्पेस + एंटर + Tab + Space + डिलीट + इंसर्ट + Home + End + पेज अप + पेज डाउन + प्रिंट स्क्रीन + ऊपर का तीर + नीचे का तीर + बायाँ तीर + दायाँ तीर + कैप्स लॉक + नम लॉक + स्क्रॉल लॉक + बायाँ %1$s + दायाँ %1$s + शिफ़्ट + diff --git a/app/src/main/res/values-hu/gestures.xml b/app/src/main/res/values-hu/gestures.xml new file mode 100644 index 0000000000..359224c549 --- /dev/null +++ b/app/src/main/res/values-hu/gestures.xml @@ -0,0 +1,103 @@ + + + Gesztusok + Érintési gesztusok beállításai + Szabd testre az egér- és billentyűzetgesztusokat. Használatukhoz válaszd a Gesztusok érintési módot. + Koppintás + Húzás egy ujjal + Hosszú nyomás + Dupla koppintás (dupla bal kattintás) + Koppintás két ujjal + Húzás két ujjal + Nyomva tartás két ujjal + Koppintás három ujjal + Húzás három ujjal + Nyomva tartás három ujjal + Csippentéses nagyítás + Gomb nyomva tartása + Egyszeri kattintás + Nyomva tartás késleltetése + Dupla koppintás időköze + Az aktuális játékra érvényes + Alapbeállítások minden játékhoz + Eredeti gesztusbeállítások visszaállítása + Mégse + Művelet kiválasztása + Bal kattintás + Jobb kattintás + Középső kattintás + Billentyűzet megjelenítése + Bal kattintás és húzás + Jobb kattintás és húzás + Pásztázás középső egérgombbal + Pásztázás középső egérgombbal (fordított) + Nyílbillentyűk + Nyílbillentyűk (fordított) + WASD (fordított) + Egérgörgő + Gesztusküszöb: %1$d px + Felismert gesztus megjelenítése + Egér- és billentyűzetvezérlés gesztusok szerint + Egy ujj + Két ujj + Három ujj + Beállítások + Válaszd ki a koppintás, húzás vagy nyomva tartás műveletét. + Állítsd be a kamera pásztázását, a nagyítást és a másodlagos kattintásokat. + Tarts további gyorsparancsokat kéznél. + Finomhangold a mozgást, a felismerést és a vizuális visszajelzést. + Alapértelmezések + Ez a játék + Alapbeállítások használata + Az alapbeállítások érvényesek. A szerkesztés játékhoz tartozó beállításokat hoz létre. + Módosítások mentése + Bezárás + MŰVELET + Ehhez: %1$s + Egérműveletek vagy billentyűk keresése + Keresés törlése + Összes + Nincs megfelelő művelet. Próbálj másik billentyű- vagy műveletnevet. + Egér + Alkalmazásműveletek + Navigáció + Betűk + Számok + Funkcióbillentyűk + Módosítóbillentyűk + Numerikus billentyűzet + Szimbólumok + Egérmozgás + A közvetlen húzás az érintési helyet követi. A relatív húzás az ujj mozgását követi, ami hasznos, ha a játék középre állítja az egeret. + A középső egérgombos pásztázás mindig az ujj mozgását követi, hogy a kurzor ne ugorjon el. + Közvetlen + Relatív + Gesztusfelismerés + Ennyit kell elmozdítani az ujjakat, mielőtt a két- vagy háromujjas gesztus pásztázássá vagy nagyítássá válik. + Vizuális visszajelzés + Egérgomb működése + %1$d ms + Numerikus billentyűzet %1$s + Escape + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Fel nyíl + Le nyíl + Balra nyíl + Jobbra nyíl + Caps Lock + Num Lock + Scroll Lock + Bal %1$s + Jobb %1$s + Shift + diff --git a/app/src/main/res/values-in/gestures.xml b/app/src/main/res/values-in/gestures.xml new file mode 100644 index 0000000000..67a82a4e21 --- /dev/null +++ b/app/src/main/res/values-in/gestures.xml @@ -0,0 +1,103 @@ + + + Gestur + Setelan gestur layar sentuh + Sesuaikan gestur mouse dan keyboard. Pilih Gestur sebagai mode sentuh untuk menggunakannya. + Ketuk + Seret dengan satu jari + Tekan lama + Ketuk dua kali (klik kiri dua kali) + Ketuk dengan dua jari + Seret dengan dua jari + Tahan dengan dua jari + Ketuk dengan tiga jari + Seret dengan tiga jari + Tahan dengan tiga jari + Cubit untuk memperbesar + Tetap tekan tombol + Klik sekali + Jeda sebelum menahan + Interval ketuk dua kali + Berlaku untuk game saat ini + Setelan default untuk semua game + Pulihkan setelan gestur awal + Batal + Pilih tindakan + Klik kiri + Klik kanan + Klik tengah + Tampilkan keyboard + Klik kiri dan seret + Klik kanan dan seret + Geser dengan tombol tengah mouse + Geser dengan tombol tengah mouse (terbalik) + Tombol panah + Tombol panah (terbalik) + WASD (terbalik) + Roda mouse + Ambang gestur: %1$d px + Tampilkan gestur yang dikenali + Kontrol mouse dan keyboard menurut gestur + Satu jari + Dua jari + Tiga jari + Opsi + Pilih tindakan saat mengetuk, menyeret, atau menahan. + Atur pergeseran kamera, zoom, dan klik sekunder. + Jangkau lebih banyak pintasan dengan mudah. + Sesuaikan gerakan, pengenalan, dan umpan balik visual. + Default + Game ini + Gunakan default + Menggunakan setelan default. Mengedit akan membuat setelan khusus game. + Simpan perubahan + Tutup + TINDAKAN + Untuk %1$s + Cari tindakan mouse atau tombol keyboard + Hapus pencarian + Semua + Tidak ada tindakan yang cocok. Coba nama tombol atau tindakan lain. + Mouse + Tindakan aplikasi + Navigasi + Huruf + Angka + Tombol fungsi + Tombol pengubah + Keypad numerik + Simbol + Gerakan mouse + Seret langsung mengikuti posisi sentuhan. Seret relatif mengikuti gerakan jari, berguna saat game memusatkan mouse. + Pergeseran dengan tombol tengah mouse selalu mengikuti gerakan jari agar kursor tidak melompat. + Langsung + Relatif + Pengenalan gestur + Gerakkan sejauh ini sebelum gestur dua atau tiga jari menjadi pergeseran atau zoom. + Umpan balik visual + Perilaku tombol mouse + %1$d md + Keypad numerik %1$s + Escape + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Panah atas + Panah bawah + Panah kiri + Panah kanan + Caps Lock + Num Lock + Scroll Lock + %1$s kiri + %1$s kanan + Shift + diff --git a/app/src/main/res/values-it/gestures.xml b/app/src/main/res/values-it/gestures.xml new file mode 100644 index 0000000000..07475d5d7f --- /dev/null +++ b/app/src/main/res/values-it/gestures.xml @@ -0,0 +1,103 @@ + + + Gesti + Impostazioni dei gesti tattili + Personalizza i gesti di mouse e tastiera. Seleziona Gesti come modalità tattile per usarli. + Tocco + Trascinamento con un dito + Pressione prolungata + Doppio tocco (doppio clic sinistro) + Tocco con due dita + Trascinamento con due dita + Pressione con due dita + Tocco con tre dita + Trascinamento con tre dita + Pressione con tre dita + Pizzica per ingrandire + Tieni premuto il pulsante + Clic singolo + Ritardo della pressione + Intervallo del doppio tocco + Si applica al gioco attuale + Impostazioni predefinite per tutti i giochi + Ripristina le impostazioni originali dei gesti + Annulla + Scegli azione + Clic sinistro + Clic destro + Clic centrale + Mostra tastiera + Clic sinistro e trascinamento + Clic destro e trascinamento + Spostamento con il pulsante centrale + Spostamento con il pulsante centrale (invertito) + Tasti freccia + Tasti freccia (invertiti) + WASD (invertito) + Rotellina del mouse + Soglia dei gesti: %1$d px + Mostra il gesto riconosciuto + Comandi di mouse e tastiera organizzati per gesto + Un dito + Due dita + Tre dita + Opzioni + Scegli l\'azione di un tocco, trascinamento o pressione. + Configura lo spostamento della visuale, lo zoom e i clic secondari. + Tieni altre scorciatoie a portata di mano. + Regola movimento, riconoscimento e riscontro visivo. + Predefiniti + Questo gioco + Usa impostazioni predefinite + Sono in uso le impostazioni predefinite. Una modifica crea impostazioni specifiche del gioco. + Salva modifiche + Chiudi + AZIONE + Per %1$s + Cerca azioni del mouse o tasti della tastiera + Cancella ricerca + Tutte + Nessuna azione corrispondente. Prova un altro nome di tasto o azione. + Mouse + Azioni dell\'app + Navigazione + Lettere + Numeri + Tasti funzione + Tasti modificatori + Tastierino numerico + Simboli + Movimento del mouse + Il trascinamento diretto segue la posizione del tocco. Quello relativo segue il movimento del dito ed è utile quando un gioco ricentra il mouse. + Lo spostamento con il pulsante centrale segue sempre il movimento del dito per evitare salti del cursore. + Diretto + Relativo + Riconoscimento dei gesti + Percorri questa distanza prima che un gesto con due o tre dita diventi uno spostamento o uno zoom. + Riscontro visivo + Comportamento del pulsante del mouse + %1$d ms + Tastierino numerico %1$s + Esc + Backspace + Invio + Tab + Spazio + Canc + Ins + Home + Fine + Pagina su + Pagina giù + Stamp + Freccia su + Freccia giù + Freccia sinistra + Freccia destra + Bloc Maiusc + Bloc Num + Bloc Scorr + %1$s sinistro + %1$s destro + Maiusc + diff --git a/app/src/main/res/values-ja/gestures.xml b/app/src/main/res/values-ja/gestures.xml new file mode 100644 index 0000000000..7568885f2c --- /dev/null +++ b/app/src/main/res/values-ja/gestures.xml @@ -0,0 +1,103 @@ + + + ジェスチャー + タッチジェスチャーの設定 + マウスとキーボードのジェスチャーを設定します。使用するにはタッチモードで「ジェスチャー」を選択してください。 + タップ + 1本指でドラッグ + 長押し + ダブルタップ(左ダブルクリック) + 2本指でタップ + 2本指でドラッグ + 2本指で長押し + 3本指でタップ + 3本指でドラッグ + 3本指で長押し + ピンチで拡大・縮小 + ボタンを押したままにする + 1回クリック + 長押しの待ち時間 + ダブルタップの間隔 + 現在のゲームに適用 + すべてのゲームの既定設定 + ジェスチャーの設定を初期状態に戻す + キャンセル + 操作を選択 + 左クリック + 右クリック + 中クリック + キーボードを表示 + 左クリックしてドラッグ + 右クリックしてドラッグ + マウスの中ボタンで視点移動 + マウスの中ボタンで視点移動(反転) + 矢印キー + 矢印キー(反転) + WASD(反転) + マウスホイール + ジェスチャーのしきい値:%1$d px + 認識したジェスチャーを表示 + ジェスチャー別のマウスとキーボード操作 + 1本指 + 2本指 + 3本指 + オプション + タップ、ドラッグ、長押しの動作を選択します。 + カメラ移動、ズーム、補助クリックを設定します。 + 追加のショートカットを手元に配置します。 + 移動、認識、視覚的フィードバックを調整します。 + デフォルト + このゲーム + 既定値を使用 + 既定設定を使用しています。編集するとゲーム固有の設定が作成されます。 + 変更を保存 + 閉じる + 操作 + %1$sの操作 + マウス操作やキーボードのキーを検索 + 検索をクリア + すべて + 一致する操作がありません。別のキー名や操作名を試してください。 + マウス + アプリの操作 + ナビゲーション + 英字 + 数字 + ファンクションキー + 修飾キー + テンキー + 記号 + マウスの移動 + 直接ドラッグはタッチ位置に従います。相対ドラッグは指の動きに従い、ゲームがマウスを中央に戻す場合に適しています。 + カーソルの飛びを防ぐため、中ボタンによる視点移動は常に指の動きに従います。 + ダイレクト + 相対 + ジェスチャー認識 + 2本指または3本指のジェスチャーが視点移動やズームになるまでに必要な移動距離です。 + 視覚的フィードバック + マウスボタンの動作 + %1$dミリ秒 + テンキー %1$s + Esc + Backspace + Enter + Tab + スペース + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + 上矢印 + 下矢印 + 左矢印 + 右矢印 + Caps Lock + Num Lock + Scroll Lock + 左%1$s + 右%1$s + Shift + diff --git a/app/src/main/res/values-ko/gestures.xml b/app/src/main/res/values-ko/gestures.xml new file mode 100644 index 0000000000..5ca6d89f5b --- /dev/null +++ b/app/src/main/res/values-ko/gestures.xml @@ -0,0 +1,103 @@ + + + 제스처 + 터치 제스처 설정 + 마우스와 키보드 제스처를 맞춤 설정합니다. 사용하려면 터치 모드에서 제스처를 선택하세요. + 탭 + 한 손가락 드래그 + 길게 누르기 + 두 번 탭 (왼쪽 더블 클릭) + 두 손가락 탭 + 두 손가락 드래그 + 두 손가락 길게 누르기 + 세 손가락 탭 + 세 손가락 드래그 + 세 손가락 길게 누르기 + 손가락을 모으거나 벌려 확대/축소 + 버튼을 누른 상태로 유지 + 한 번 클릭 + 길게 누르기 대기 시간 + 두 번 탭 간격 + 현재 게임에 적용 + 모든 게임의 기본 설정 + 제스처 설정을 초기 상태로 재설정 + 취소 + 동작 선택 + 왼쪽 클릭 + 오른쪽 클릭 + 가운데 클릭 + 키보드 표시 + 왼쪽 클릭 후 드래그 + 오른쪽 클릭 후 드래그 + 마우스 가운데 버튼으로 이동 + 마우스 가운데 버튼으로 이동 (반전) + 방향키 + 방향키 (반전) + WASD (반전) + 마우스 휠 + 제스처 임계값: %1$d px + 인식된 제스처 표시 + 제스처별 마우스 및 키보드 조작 + 한 손가락 + 두 손가락 + 세 손가락 + 옵션 + 탭, 드래그, 길게 누르기의 동작을 선택하세요. + 카메라 이동, 확대/축소, 보조 클릭을 설정하세요. + 추가 단축 동작을 손쉽게 사용하세요. + 이동, 인식, 시각적 피드백을 조정하세요. + 기본값 + 이 게임 + 기본값 사용 + 기본 설정을 사용 중입니다. 수정하면 게임별 설정이 생성됩니다. + 변경 사항 저장 + 닫기 + 동작 + %1$s 동작 + 마우스 동작 또는 키보드 키 검색 + 검색 지우기 + 전체 + 일치하는 동작이 없습니다. 다른 키나 동작 이름을 검색하세요. + 마우스 + 앱 동작 + 탐색 + 문자 + 숫자 + 기능키 + 보조키 + 숫자 키패드 + 기호 + 마우스 이동 + 직접 드래그는 터치 위치를 따릅니다. 상대 드래그는 손가락 움직임을 따르며, 게임에서 마우스를 중앙으로 돌려놓을 때 유용합니다. + 커서가 튀지 않도록 가운데 버튼 이동은 항상 손가락 움직임을 따릅니다. + 직접 터치 + 상대 + 제스처 인식 + 두 손가락 또는 세 손가락 제스처가 카메라 이동이나 확대/축소로 인식되기 위한 이동 거리입니다. + 시각적 피드백 + 마우스 버튼 동작 + %1$d ms + 숫자 키패드 %1$s + Esc + 백스페이스 + 엔터 + Tab + Space + 삭제 + 삽입 + Home + End + 페이지 위로 + 페이지 아래로 + 화면 인쇄 + 위쪽 화살표 + 아래쪽 화살표 + 왼쪽 화살표 + 오른쪽 화살표 + Caps Lock + Num Lock + Scroll Lock + 왼쪽 %1$s + 오른쪽 %1$s + Shift + diff --git a/app/src/main/res/values-ms/gestures.xml b/app/src/main/res/values-ms/gestures.xml new file mode 100644 index 0000000000..f4762ac34a --- /dev/null +++ b/app/src/main/res/values-ms/gestures.xml @@ -0,0 +1,103 @@ + + + Gerak isyarat + Tetapan gerak isyarat sentuhan + Sesuaikan gerak isyarat tetikus dan papan kekunci. Pilih Gerak isyarat sebagai mod sentuhan untuk menggunakannya. + Ketik + Seret dengan satu jari + Tekan lama + Ketik dua kali (klik kiri dua kali) + Ketik dengan dua jari + Seret dengan dua jari + Tahan dengan dua jari + Ketik dengan tiga jari + Seret dengan tiga jari + Tahan dengan tiga jari + Cubit untuk zum + Kekalkan butang ditekan + Klik sekali + Lengah sebelum menahan + Sela ketikan dua kali + Digunakan untuk permainan semasa + Tetapan lalai untuk semua permainan + Pulihkan tetapan gerak isyarat asal + Batal + Pilih tindakan + Klik kiri + Klik kanan + Klik tengah + Papar papan kekunci + Klik kiri dan seret + Klik kanan dan seret + Sorot dengan butang tengah tetikus + Sorot dengan butang tengah tetikus (terbalik) + Kekunci anak panah + Kekunci anak panah (terbalik) + WASD (terbalik) + Roda tetikus + Ambang gerak isyarat: %1$d px + Tunjukkan gerak isyarat yang dikenal pasti + Kawalan tetikus dan papan kekunci mengikut gerak isyarat + Satu jari + Dua jari + Tiga jari + Pilihan + Pilih tindakan apabila mengetik, menyeret atau menahan. + Tetapkan sorotan kamera, zum dan klik sekunder. + Pastikan pintasan tambahan mudah dicapai. + Laraskan pergerakan, pengecaman dan maklum balas visual. + Lalai + Permainan ini + Gunakan lalai + Menggunakan tetapan lalai. Penyuntingan mencipta tetapan khusus permainan. + Simpan perubahan + Tutup + TINDAKAN + Untuk %1$s + Cari tindakan tetikus atau kekunci papan kekunci + Kosongkan carian + Semua + Tiada tindakan sepadan. Cuba nama kekunci atau tindakan lain. + Tetikus + Tindakan aplikasi + Navigasi + Huruf + Nombor + Kekunci fungsi + Kekunci pengubah suai + Pad nombor + Simbol + Pergerakan tetikus + Seretan langsung mengikut kedudukan sentuhan. Seretan relatif mengikut pergerakan jari dan berguna apabila permainan memusatkan tetikus. + Sorotan dengan butang tengah tetikus sentiasa mengikut pergerakan jari untuk mengelakkan lompatan kursor. + Terus + Relatif + Pengecaman gerak isyarat + Gerakkan sejauh ini sebelum gerak isyarat dua atau tiga jari menjadi sorotan atau zum. + Maklum balas visual + Kelakuan butang tetikus + %1$d ms + Pad nombor %1$s + Escape + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Anak panah atas + Anak panah bawah + Anak panah kiri + Anak panah kanan + Caps Lock + Num Lock + Scroll Lock + %1$s kiri + %1$s kanan + Shift + diff --git a/app/src/main/res/values-nb/gestures.xml b/app/src/main/res/values-nb/gestures.xml new file mode 100644 index 0000000000..77330e3c39 --- /dev/null +++ b/app/src/main/res/values-nb/gestures.xml @@ -0,0 +1,103 @@ + + + Bevegelser + Innstillinger for berøringsbevegelser + Tilpass muse- og tastaturbevegelser. Velg Bevegelser som berøringsmodus for å bruke dem. + Trykk + Dra med én finger + Langt trykk + Dobbelttrykk (dobbelt venstreklikk) + Trykk med to fingre + Dra med to fingre + Hold med to fingre + Trykk med tre fingre + Dra med tre fingre + Hold med tre fingre + Knip for å zoome + Hold knappen nede + Klikk én gang + Forsinkelse før hold + Intervall for dobbelttrykk + Gjelder det gjeldende spillet + Standardinnstillinger for alle spill + Gjenopprett de opprinnelige bevegelsesinnstillingene + Avbryt + Velg handling + Venstreklikk + Høyreklikk + Midtklikk + Vis tastatur + Venstreklikk og dra + Høyreklikk og dra + Panorer med midtre museknapp + Panorer med midtre museknapp (omvendt) + Piltaster + Piltaster (omvendt) + WASD (omvendt) + Musehjul + Bevegelsesterskel: %1$d px + Vis gjenkjent bevegelse + Muse- og tastaturstyring organisert etter bevegelse + Én finger + To fingre + Tre fingre + Alternativer + Velg hva et trykk, drag eller hold skal gjøre. + Still inn kamerapanorering, zoom og sekundære klikk. + Ha flere snarveier innen rekkevidde. + Juster bevegelse, gjenkjenning og visuell tilbakemelding. + Standardverdier + Dette spillet + Bruk standardinnstillinger + Standardinnstillinger brukes. Redigering oppretter egne innstillinger for spillet. + Lagre endringer + Lukk + HANDLING + For %1$s + Søk etter musehandlinger eller tastaturtaster + Tøm søket + Alle + Ingen handlinger samsvarer. Prøv et annet navn på en tast eller handling. + Mus + Apphandlinger + Navigasjon + Bokstaver + Tall + Funksjonstaster + Modifikatortaster + Numerisk tastatur + Symboler + Musebevegelse + Direkte draing følger berøringsposisjonen. Relativ draing følger fingerbevegelsen og er nyttig når et spill sentrerer musen. + Panorering med midtre museknapp følger alltid fingerbevegelsen for å unngå markørhopp. + Direkte + Relativ + Gjenkjenning av bevegelser + Beveg fingrene så langt før en bevegelse med to eller tre fingre blir til panorering eller zoom. + Visuell tilbakemelding + Museknappens funksjon + %1$d ms + Numerisk tastatur %1$s + Escape + Tilbake + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Pil opp + Pil ned + Pil til venstre + Pil til høyre + Caps Lock + Num Lock + Scroll Lock + Venstre %1$s + Høyre %1$s + Shift + diff --git a/app/src/main/res/values-nl/gestures.xml b/app/src/main/res/values-nl/gestures.xml new file mode 100644 index 0000000000..1b225d5ad4 --- /dev/null +++ b/app/src/main/res/values-nl/gestures.xml @@ -0,0 +1,103 @@ + + + Gebaren + Instellingen voor aanraakgebaren + Pas muis- en toetsenbordgebaren aan. Kies Gebaren als aanraakmodus om ze te gebruiken. + Tikken + Slepen met één vinger + Lang indrukken + Dubbeltikken (dubbele linkermuisklik) + Tikken met twee vingers + Slepen met twee vingers + Vasthouden met twee vingers + Tikken met drie vingers + Slepen met drie vingers + Vasthouden met drie vingers + Knijpen om te zoomen + Knop ingedrukt houden + Eenmaal klikken + Wachttijd voor vasthouden + Interval voor dubbeltikken + Geldt voor het huidige spel + Standaardinstellingen voor alle spellen + Oorspronkelijke gebareninstellingen herstellen + Annuleren + Actie kiezen + Linkermuisklik + Rechtermuisklik + Middelste muisklik + Toetsenbord tonen + Linkermuisknop en slepen + Rechtermuisknop en slepen + Pannen met de middelste muisknop + Pannen met de middelste muisknop (omgekeerd) + Pijltoetsen + Pijltoetsen (omgekeerd) + WASD (omgekeerd) + Muiswiel + Gebaardrempel: %1$d px + Herkend gebaar tonen + Muis- en toetsenbordbediening per gebaar + Eén vinger + Twee vingers + Drie vingers + Opties + Kies wat tikken, slepen of vasthouden doet. + Stel camerabewegingen, zoomen en secundaire klikken in. + Houd extra sneltoetsen binnen handbereik. + Pas beweging, herkenning en visuele feedback aan. + Standaardinstellingen + Dit spel + Standaardinstellingen gebruiken + Standaardinstellingen zijn actief. Bewerken maakt instellingen voor dit spel. + Wijzigingen opslaan + Sluiten + ACTIE + Voor %1$s + Zoek muisacties of toetsen + Zoekopdracht wissen + Alle + Geen overeenkomende acties. Probeer een andere toets- of actienaam. + Muis + App-acties + Navigatie + Letters + Cijfers + Functietoetsen + Modificatietoetsen + Numeriek toetsenblok + Symbolen + Muisbeweging + Direct slepen volgt de aanraakpositie. Relatief slepen volgt de vingerbeweging en is handig als een spel de muis opnieuw centreert. + Pannen met de middelste muisknop volgt altijd de vingerbeweging om cursorsprongen te voorkomen. + Direct + Relatief + Gebarenherkenning + Beweeg deze afstand voordat een gebaar met twee of drie vingers overgaat in pannen of zoomen. + Visuele feedback + Gedrag van de muisknop + %1$d ms + Numeriek toetsenblok %1$s + Escape + Backspace + Enter + Tab + Spatie + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Pijl omhoog + Pijl omlaag + Pijl links + Pijl rechts + Caps Lock + Num Lock + Scroll Lock + Linker %1$s + Rechter %1$s + Shift + diff --git a/app/src/main/res/values-pl/gestures.xml b/app/src/main/res/values-pl/gestures.xml new file mode 100644 index 0000000000..9ff5f867bb --- /dev/null +++ b/app/src/main/res/values-pl/gestures.xml @@ -0,0 +1,103 @@ + + + Gesty + Ustawienia gestów dotykowych + Dostosuj gesty myszy i klawiatury. Aby ich używać, wybierz Gesty jako tryb dotyku. + Stuknięcie + Przeciąganie jednym palcem + Długie naciśnięcie + Podwójne stuknięcie (podwójny lewy klik) + Stuknięcie dwoma palcami + Przeciąganie dwoma palcami + Przytrzymanie dwoma palcami + Stuknięcie trzema palcami + Przeciąganie trzema palcami + Przytrzymanie trzema palcami + Uszczypnij, aby przybliżyć + Trzymaj przycisk wciśnięty + Kliknij raz + Czas przytrzymania + Odstęp podwójnego stuknięcia + Dotyczy bieżącej gry + Ustawienia domyślne dla wszystkich gier + Przywróć pierwotne ustawienia gestów + Anuluj + Wybierz akcję + Lewy klik + Prawy klik + Środkowy klik + Pokaż klawiaturę + Lewy klik i przeciąganie + Prawy klik i przeciąganie + Przesuwanie środkowym przyciskiem myszy + Przesuwanie środkowym przyciskiem myszy (odwrócone) + Klawisze strzałek + Klawisze strzałek (odwrócone) + WASD (odwrócone) + Kółko myszy + Próg gestów: %1$d px + Pokaż rozpoznany gest + Sterowanie myszą i klawiaturą pogrupowane według gestów + Jeden palec + Dwa palce + Trzy palce + Opcje + Wybierz działanie stuknięcia, przeciągania lub przytrzymania. + Skonfiguruj przesuwanie kamery, przybliżanie i kliknięcia pomocnicze. + Miej dodatkowe skróty pod ręką. + Dostosuj ruch, rozpoznawanie i wizualne potwierdzenia. + Domyślne + Ta gra + Użyj domyślnych + Używane są ustawienia domyślne. Edycja tworzy ustawienia dla tej gry. + Zapisz zmiany + Zamknij + AKCJA + Dla %1$s + Szukaj akcji myszy lub klawiszy klawiatury + Wyczyść wyszukiwanie + Wszystkie + Brak pasujących akcji. Spróbuj innej nazwy klawisza lub akcji. + Mysz + Akcje aplikacji + Nawigacja + Litery + Cyfry + Klawisze funkcyjne + Klawisze modyfikujące + Klawiatura numeryczna + Symbole + Ruch myszy + Przeciąganie bezpośrednie podąża za pozycją dotyku. Względne podąża za ruchem palca i przydaje się, gdy gra centruje mysz. + Przesuwanie środkowym przyciskiem myszy zawsze podąża za ruchem palca, aby uniknąć skoków kursora. + Bezpośredni + Względny + Rozpoznawanie gestów + Przesuń palce o tę odległość, zanim gest dwoma lub trzema palcami stanie się przesuwaniem lub przybliżaniem. + Wizualne potwierdzenia + Działanie przycisku myszy + %1$d ms + Klawiatura numeryczna %1$s + Escape + Backspace + Enter + Tab + Spacja + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Strzałka w górę + Strzałka w dół + Strzałka w lewo + Strzałka w prawo + Caps Lock + Num Lock + Scroll Lock + Lewy %1$s + Prawy %1$s + Shift + diff --git a/app/src/main/res/values-pt-rPT/gestures.xml b/app/src/main/res/values-pt-rPT/gestures.xml new file mode 100644 index 0000000000..610ebc4148 --- /dev/null +++ b/app/src/main/res/values-pt-rPT/gestures.xml @@ -0,0 +1,103 @@ + + + Gestos + Configurações de gestos de toque + Personalize os gestos de rato e teclado. Selecione Gestos como modo de toque para usá-los. + Toque + Arrastar com um dedo + Toque longo + Toque duplo (clique duplo esquerdo) + Toque com dois dedos + Arrastar com dois dedos + Manter premido com dois dedos + Toque com três dedos + Arrastar com três dedos + Manter premido com três dedos + Pinçar para ampliar + Manter o botão premido + Clicar uma vez + Tempo para manter premido + Intervalo de toque duplo + Aplica-se ao jogo atual + Configurações padrão para todos os jogos + Restaurar as configurações originais de gestos + Cancelar + Escolher ação + Clique esquerdo + Clique direito + Clique do meio + Mostrar teclado + Clique esquerdo e arrastar + Clique direito e arrastar + Mover com o botão do meio + Mover com o botão do meio (invertido) + Teclas de direção + Teclas de direção (invertidas) + WASD (invertido) + Roda do rato + Limiar dos gestos: %1$d px + Mostrar gesto reconhecido + Controlos de rato e teclado organizados por gesto + Um dedo + Dois dedos + Três dedos + Opções + Escolha o que um toque, arraste ou toque mantido deve fazer. + Configure o movimento da câmera, o zoom e os cliques secundários. + Mantenha mais atalhos ao alcance dos dedos. + Ajuste o movimento, o reconhecimento e a resposta visual. + Valores padrão + Este jogo + Usar padrões + Usando as configurações padrão. A edição cria configurações específicas do jogo. + Salvar alterações + Fechar + AÇÃO + Para %1$s + Pesquisar ações de rato ou teclas do teclado + Limpar pesquisa + Todas + Nenhuma ação correspondente. Tente outro nome de tecla ou ação. + Rato + Ações da aplicação + Navegação + Letras + Números + Teclas de função + Teclas modificadoras + Teclado numérico + Símbolos + Movimento do rato + O arraste direto segue a posição do toque. O relativo segue o movimento do dedo e é útil quando um jogo centra o rato. + O movimento com o botão do meio sempre segue o movimento do dedo para evitar saltos do cursor. + Direto + Relativo + Reconhecimento de gestos + Percorra esta distância antes que um gesto de dois ou três dedos se torne movimento de câmera ou zoom. + Resposta visual + Comportamento do botão do rato + %1$d ms + Teclado numérico %1$s + Esc + Backspace + Enter + Tab + Espaço + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Seta para cima + Seta para baixo + Seta para a esquerda + Seta para a direita + Caps Lock + Num Lock + Scroll Lock + %1$s esquerdo + %1$s direito + Shift + diff --git a/app/src/main/res/values-pt/gestures.xml b/app/src/main/res/values-pt/gestures.xml new file mode 100644 index 0000000000..545700a318 --- /dev/null +++ b/app/src/main/res/values-pt/gestures.xml @@ -0,0 +1,103 @@ + + + Gestos + Configurações de gestos de toque + Personalize os gestos de mouse e teclado. Selecione Gestos como modo de toque para usá-los. + Toque + Arrastar com um dedo + Toque longo + Toque duplo (clique duplo esquerdo) + Toque com dois dedos + Arrastar com dois dedos + Manter pressionado com dois dedos + Toque com três dedos + Arrastar com três dedos + Manter pressionado com três dedos + Pinçar para ampliar + Manter o botão pressionado + Clicar uma vez + Tempo para manter pressionado + Intervalo de toque duplo + Aplica-se ao jogo atual + Configurações padrão para todos os jogos + Restaurar as configurações originais de gestos + Cancelar + Escolher ação + Clique esquerdo + Clique direito + Clique do meio + Mostrar teclado + Clique esquerdo e arrastar + Clique direito e arrastar + Mover com o botão do meio + Mover com o botão do meio (invertido) + Teclas de direção + Teclas de direção (invertidas) + WASD (invertido) + Roda do mouse + Limiar dos gestos: %1$d px + Mostrar gesto reconhecido + Controles de mouse e teclado organizados por gesto + Um dedo + Dois dedos + Três dedos + Opções + Escolha o que um toque, arraste ou toque mantido deve fazer. + Configure o movimento da câmera, o zoom e os cliques secundários. + Mantenha mais atalhos ao alcance dos dedos. + Ajuste o movimento, o reconhecimento e a resposta visual. + Padrões + Este jogo + Usar padrões + Usando as configurações padrão. A edição cria configurações específicas do jogo. + Salvar alterações + Fechar + AÇÃO + Para %1$s + Pesquisar ações de mouse ou teclas do teclado + Limpar pesquisa + Todos + Nenhuma ação correspondente. Tente outro nome de tecla ou ação. + Mouse + Ações do aplicativo + Navegação + Letras + Números + Teclas de função + Teclas modificadoras + Teclado numérico + Símbolos + Movimento do mouse + O arraste direto segue a posição do toque. O relativo segue o movimento do dedo e é útil quando um jogo centraliza o mouse. + O movimento com o botão do meio sempre segue o movimento do dedo para evitar saltos do cursor. + Direto + Relativo + Reconhecimento de gestos + Percorra esta distância antes que um gesto de dois ou três dedos se torne movimento de câmera ou zoom. + Resposta visual + Comportamento do botão do mouse + %1$d ms + Teclado numérico %1$s + Esc + Backspace + Enter + Tab + Espaço + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Seta para cima + Seta para baixo + Seta para a esquerda + Seta para a direita + Caps Lock + Num Lock + Scroll Lock + %1$s esquerdo + %1$s direito + Shift + diff --git a/app/src/main/res/values-ro/gestures.xml b/app/src/main/res/values-ro/gestures.xml new file mode 100644 index 0000000000..6b7ab9bdee --- /dev/null +++ b/app/src/main/res/values-ro/gestures.xml @@ -0,0 +1,103 @@ + + + Gesturi + Setări pentru gesturile tactile + Personalizează gesturile de mouse și tastatură. Selectează Gesturi ca mod tactil pentru a le folosi. + Atingere + Tragere cu un deget + Apăsare lungă + Atingere dublă (dublu clic stânga) + Atingere cu două degete + Tragere cu două degete + Menținere cu două degete + Atingere cu trei degete + Tragere cu trei degete + Menținere cu trei degete + Apropie sau depărtează degetele pentru zoom + Ține butonul apăsat + Un singur clic + Durata până la menținere + Intervalul atingerii duble + Se aplică jocului curent + Setări implicite pentru toate jocurile + Restabilește setările originale ale gesturilor + Anulează + Alege acțiunea + Clic stânga + Clic dreapta + Clic mijloc + Arată tastatura + Clic stânga și tragere + Clic dreapta și tragere + Deplasare cu butonul din mijloc + Deplasare cu butonul din mijloc (inversată) + Taste săgeată + Taste săgeată (inversate) + WASD (inversat) + Rotița mouse-ului + Pragul gesturilor: %1$d px + Arată gestul recunoscut + Comenzi de mouse și tastatură organizate după gest + Un deget + Două degete + Trei degete + Opțiuni + Alege acțiunea unei atingeri, trageri sau mențineri. + Configurează deplasarea camerei, zoomul și clicurile secundare. + Păstrează scurtături suplimentare la îndemână. + Ajustează mișcarea, recunoașterea și feedbackul vizual. + Valori implicite + Acest joc + Folosește valorile implicite + Se folosesc setările implicite. Editarea creează setări specifice jocului. + Salvează modificările + Închide + ACȚIUNE + Pentru %1$s + Caută acțiuni de mouse sau taste + Șterge căutarea + Toate + Nicio acțiune potrivită. Încearcă alt nume de tastă sau acțiune. + Mouse + Acțiuni ale aplicației + Navigare + Litere + Cifre + Taste funcționale + Taste modificatoare + Tastatură numerică + Simboluri + Mișcarea mouse-ului + Tragerea directă urmărește poziția atingerii. Cea relativă urmărește mișcarea degetului și este utilă când jocul recentrează mouse-ul. + Deplasarea cu butonul din mijloc urmărește întotdeauna mișcarea degetului pentru a evita salturile cursorului. + Direct + Relativă + Recunoașterea gesturilor + Parcurge această distanță înainte ca un gest cu două sau trei degete să devină deplasare sau zoom. + Feedback vizual + Comportamentul butonului de mouse + %1$d ms + Tastatură numerică %1$s + Escape + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Săgeată sus + Săgeată jos + Săgeată stânga + Săgeată dreapta + Caps Lock + Num Lock + Scroll Lock + %1$s stânga + %1$s dreapta + Shift + diff --git a/app/src/main/res/values-ru/gestures.xml b/app/src/main/res/values-ru/gestures.xml new file mode 100644 index 0000000000..631b1fcfe4 --- /dev/null +++ b/app/src/main/res/values-ru/gestures.xml @@ -0,0 +1,103 @@ + + + Жесты + Настройки сенсорных жестов + Настройте жесты мыши и клавиатуры. Чтобы использовать их, выберите режим касаний «Жесты». + Касание + Перетаскивание одним пальцем + Долгое нажатие + Двойное касание (двойной щелчок левой кнопкой) + Касание двумя пальцами + Перетаскивание двумя пальцами + Удержание двумя пальцами + Касание тремя пальцами + Перетаскивание тремя пальцами + Удержание тремя пальцами + Масштабирование щипком + Удерживать кнопку нажатой + Один щелчок + Задержка удержания + Интервал двойного касания + Применяется к текущей игре + Настройки по умолчанию для всех игр + Восстановить исходные настройки жестов + Отмена + Выберите действие + Левая кнопка мыши + Правая кнопка мыши + Средняя кнопка мыши + Показать клавиатуру + Перетаскивание левой кнопкой + Перетаскивание правой кнопкой + Панорамирование средней кнопкой + Панорамирование средней кнопкой (обратное) + Клавиши со стрелками + Клавиши со стрелками (обратные) + WASD (обратное) + Колесо мыши + Порог жестов: %1$d пикс. + Показывать распознанный жест + Управление мышью и клавиатурой по жестам + Один палец + Два пальца + Три пальца + Параметры + Выберите действие для касания, перетаскивания или удержания. + Настройте перемещение камеры, масштабирование и дополнительные щелчки. + Держите дополнительные команды под рукой. + Настройте движение, распознавание и визуальный отклик. + По умолчанию + Эта игра + Использовать настройки по умолчанию + Используются настройки по умолчанию. Изменение создаст настройки для этой игры. + Сохранить изменения + Закрыть + ДЕЙСТВИЕ + Для %1$s + Поиск действий мыши или клавиш клавиатуры + Очистить поиск + Все + Подходящих действий нет. Попробуйте другое название клавиши или действия. + Мышь + Действия приложения + Навигация + Буквы + Цифры + Функциональные клавиши + Клавиши-модификаторы + Цифровой блок + Символы + Движение мыши + Прямое перетаскивание следует позиции касания. Относительное следует движению пальца и полезно, когда игра возвращает мышь в центр. + Панорамирование средней кнопкой всегда следует движению пальца, чтобы избежать скачков курсора. + Прямой + Относительное + Распознавание жестов + Пройдите это расстояние, прежде чем жест двумя или тремя пальцами станет перемещением камеры или масштабированием. + Визуальный отклик + Поведение кнопки мыши + %1$d мс + Цифровой блок: %1$s + Esc + Backspace + Enter + Tab + Пробел + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Стрелка вверх + Стрелка вниз + Стрелка влево + Стрелка вправо + Caps Lock + Num Lock + Scroll Lock + Левый %1$s + Правый %1$s + Shift + diff --git a/app/src/main/res/values-sv/gestures.xml b/app/src/main/res/values-sv/gestures.xml new file mode 100644 index 0000000000..a7475e8205 --- /dev/null +++ b/app/src/main/res/values-sv/gestures.xml @@ -0,0 +1,103 @@ + + + Gester + Inställningar för pekgester + Anpassa mus- och tangentbordsgester. Välj Gester som pekläge för att använda dem. + Tryck + Dra med ett finger + Långt tryck + Dubbeltryck (dubbelt vänsterklick) + Tryck med två fingrar + Dra med två fingrar + Håll med två fingrar + Tryck med tre fingrar + Dra med tre fingrar + Håll med tre fingrar + Nyp för att zooma + Håll knappen nedtryckt + Klicka en gång + Fördröjning före hållning + Intervall för dubbeltryck + Gäller det aktuella spelet + Standardinställningar för alla spel + Återställ de ursprungliga gestinställningarna + Avbryt + Välj åtgärd + Vänsterklick + Högerklick + Mittenklick + Visa tangentbord + Vänsterklicka och dra + Högerklicka och dra + Panorera med musens mittknapp + Panorera med musens mittknapp (omvänt) + Piltangenter + Piltangenter (omvänt) + WASD (omvänt) + Mushjul + Gesttröskel: %1$d px + Visa identifierad gest + Mus- och tangentbordsstyrning ordnad efter gest + Ett finger + Två fingrar + Tre fingrar + Alternativ + Välj vad ett tryck, drag eller håll ska göra. + Ställ in kamerapanorering, zoom och sekundära klick. + Ha fler genvägar inom räckhåll. + Justera rörelse, identifiering och visuell återkoppling. + Standardvärden + Det här spelet + Använd standardinställningar + Standardinställningar används. Redigering skapar inställningar för spelet. + Spara ändringar + Stäng + ÅTGÄRD + För %1$s + Sök efter musåtgärder eller tangenter + Rensa sökning + Alla + Inga matchande åtgärder. Prova ett annat tangent- eller åtgärdsnamn. + Mus + Appåtgärder + Navigering + Bokstäver + Siffror + Funktionstangenter + Modifierartangenter + Numeriskt tangentbord + Symboler + Musrörelse + Direkta drag följer pekpositionen. Relativa drag följer fingerrörelsen och är användbara när ett spel centrerar musen. + Panorering med musens mittknapp följer alltid fingerrörelsen för att undvika att pekaren hoppar. + Direkt + Relativ + Gestidentifiering + Flytta fingrarna så här långt innan en gest med två eller tre fingrar blir panorering eller zoom. + Visuell återkoppling + Musknappens beteende + %1$d ms + Numeriskt tangentbord %1$s + Escape + Backsteg + Retur + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Pil upp + Pil ned + Pil vänster + Pil höger + Caps Lock + Num Lock + Scroll Lock + Vänster %1$s + Höger %1$s + Skift + diff --git a/app/src/main/res/values-th/gestures.xml b/app/src/main/res/values-th/gestures.xml new file mode 100644 index 0000000000..f625c607b7 --- /dev/null +++ b/app/src/main/res/values-th/gestures.xml @@ -0,0 +1,103 @@ + + + ท่าทาง + การตั้งค่าท่าทางสัมผัส + ปรับแต่งท่าทางเมาส์และแป้นพิมพ์ เลือกท่าทางเป็นโหมดสัมผัสเพื่อใช้งาน + แตะ + ลากด้วยหนึ่งนิ้ว + กดค้าง + แตะสองครั้ง (ดับเบิลคลิกซ้าย) + แตะด้วยสองนิ้ว + ลากด้วยสองนิ้ว + กดค้างด้วยสองนิ้ว + แตะด้วยสามนิ้ว + ลากด้วยสามนิ้ว + กดค้างด้วยสามนิ้ว + จีบนิ้วเพื่อซูม + กดปุ่มค้างไว้ + คลิกหนึ่งครั้ง + ระยะเวลาก่อนกดค้าง + ช่วงเวลาแตะสองครั้ง + ใช้กับเกมปัจจุบัน + การตั้งค่าเริ่มต้นสำหรับทุกเกม + คืนค่าการตั้งค่าท่าทางเดิม + ยกเลิก + เลือกการกระทำ + คลิกซ้าย + คลิกขวา + คลิกกลาง + แสดงแป้นพิมพ์ + คลิกซ้ายแล้วลาก + คลิกขวาแล้วลาก + เลื่อนมุมมองด้วยปุ่มเมาส์กลาง + เลื่อนมุมมองด้วยปุ่มเมาส์กลาง (กลับด้าน) + ปุ่มลูกศร + ปุ่มลูกศร (กลับด้าน) + WASD (กลับด้าน) + ล้อเมาส์ + เกณฑ์ท่าทาง: %1$d พิกเซล + แสดงท่าทางที่ตรวจพบ + การควบคุมเมาส์และแป้นพิมพ์แยกตามท่าทาง + หนึ่งนิ้ว + สองนิ้ว + สามนิ้ว + ตัวเลือก + เลือกการทำงานเมื่อแตะ ลาก หรือกดค้าง + ตั้งค่าการเลื่อนกล้อง การซูม และการคลิกรอง + เข้าถึงทางลัดเพิ่มเติมได้ง่าย + ปรับการเคลื่อนไหว การตรวจจับ และการตอบสนองทางภาพ + ค่าเริ่มต้น + เกมนี้ + ใช้ค่าเริ่มต้น + กำลังใช้การตั้งค่าเริ่มต้น การแก้ไขจะสร้างการตั้งค่าเฉพาะเกม + บันทึกการเปลี่ยนแปลง + ปิด + การกระทำ + สำหรับ %1$s + ค้นหาการกระทำของเมาส์หรือปุ่มแป้นพิมพ์ + ล้างการค้นหา + ทั้งหมด + ไม่พบการกระทำที่ตรงกัน ลองชื่อปุ่มหรือการกระทำอื่น + เมาส์ + การกระทำของแอป + การนำทาง + ตัวอักษร + ตัวเลข + ปุ่มฟังก์ชัน + ปุ่มปรับเปลี่ยน + แป้นตัวเลข + สัญลักษณ์ + การเคลื่อนที่ของเมาส์ + การลากแบบตรงจะตามตำแหน่งที่สัมผัส ส่วนการลากแบบสัมพัทธ์จะตามการเคลื่อนนิ้ว เหมาะเมื่อเกมนำเมาส์กลับไปตรงกลาง + การเลื่อนมุมมองด้วยปุ่มเมาส์กลางจะตามการเคลื่อนนิ้วเสมอเพื่อไม่ให้เคอร์เซอร์กระโดด + โดยตรง + สัมพัทธ์ + การตรวจจับท่าทาง + เคลื่อนนิ้วตามระยะนี้ก่อนที่ท่าทางสองหรือสามนิ้วจะกลายเป็นการเลื่อนมุมมองหรือซูม + การตอบสนองทางภาพ + การทำงานของปุ่มเมาส์ + %1$d มิลลิวินาที + แป้นตัวเลข %1$s + Escape + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + ลูกศรขึ้น + ลูกศรลง + ลูกศรซ้าย + ลูกศรขวา + Caps Lock + Num Lock + Scroll Lock + %1$s ซ้าย + %1$s ขวา + Shift + diff --git a/app/src/main/res/values-tr/gestures.xml b/app/src/main/res/values-tr/gestures.xml new file mode 100644 index 0000000000..53cc3ffb22 --- /dev/null +++ b/app/src/main/res/values-tr/gestures.xml @@ -0,0 +1,103 @@ + + + Hareketler + Dokunmatik hareket ayarları + Fare ve klavye hareketlerini özelleştirin. Kullanmak için dokunma modu olarak Hareketler\'i seçin. + Dokunma + Tek parmakla sürükleme + Uzun basma + Çift dokunma (çift sol tıklama) + İki parmakla dokunma + İki parmakla sürükleme + İki parmakla basılı tutma + Üç parmakla dokunma + Üç parmakla sürükleme + Üç parmakla basılı tutma + İki parmakla yakınlaştırma + Düğmeyi basılı tut + Bir kez tıkla + Basılı tutma gecikmesi + Çift dokunma aralığı + Geçerli oyuna uygulanır + Tüm oyunlar için varsayılan ayarlar + İlk hareket ayarlarına sıfırla + İptal + Eylem seç + Sol tıklama + Sağ tıklama + Orta tıklama + Klavyeyi göster + Sol tıklayıp sürükleme + Sağ tıklayıp sürükleme + Orta fare düğmesiyle kaydırma + Orta fare düğmesiyle kaydırma (ters) + Ok tuşları + Ok tuşları (ters) + WASD (ters) + Fare tekerleği + Hareket eşiği: %1$d piksel + Algılanan hareketi göster + Hareketlere göre düzenlenmiş fare ve klavye kontrolleri + Tek parmak + İki parmak + Üç parmak + Seçenekler + Dokunma, sürükleme veya basılı tutmanın ne yapacağını seçin. + Kamera kaydırmasını, yakınlaştırmayı ve ikincil tıklamaları ayarlayın. + Ek kısayolları elinizin altında tutun. + Hareketi, algılamayı ve görsel geri bildirimi ayarlayın. + Varsayılanlar + Bu oyun + Varsayılanları kullan + Varsayılan ayarlar kullanılıyor. Düzenleme, oyuna özel ayarlar oluşturur. + Değişiklikleri kaydet + Kapat + EYLEM + %1$s için + Fare eylemlerini veya klavye tuşlarını ara + Aramayı temizle + Tümü + Eşleşen eylem yok. Başka bir tuş veya eylem adı deneyin. + Fare + Uygulama eylemleri + Gezinme + Harfler + Sayılar + İşlev tuşları + Değiştirici tuşlar + Sayısal tuş takımı + Semboller + Fare hareketi + Doğrudan sürükleme dokunma konumunu izler. Göreli sürükleme parmak hareketini izler ve oyun fareyi merkeze aldığında kullanışlıdır. + Orta fare düğmesiyle kaydırma, imlecin sıçramasını önlemek için her zaman parmak hareketini izler. + Doğrudan + Göreli + Hareket algılama + İki veya üç parmak hareketinin kaydırma ya da yakınlaştırmaya dönüşmesi için bu mesafeyi aşın. + Görsel geri bildirim + Fare düğmesi davranışı + %1$d ms + Sayısal tuş takımı %1$s + Escape + Geri silme + Enter + Tab + Boşluk + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Yukarı ok + Aşağı ok + Sol ok + Sağ ok + Caps Lock + Num Lock + Scroll Lock + Sol %1$s + Sağ %1$s + Üst Karakter + diff --git a/app/src/main/res/values-uk/gestures.xml b/app/src/main/res/values-uk/gestures.xml new file mode 100644 index 0000000000..b5d4e1f414 --- /dev/null +++ b/app/src/main/res/values-uk/gestures.xml @@ -0,0 +1,103 @@ + + + Жести + Налаштування сенсорних жестів + Налаштуйте жести миші та клавіатури. Щоб використовувати їх, виберіть режим дотику «Жести». + Дотик + Перетягування одним пальцем + Тривале натискання + Подвійний дотик (подвійне клацання лівою кнопкою) + Дотик двома пальцями + Перетягування двома пальцями + Утримання двома пальцями + Дотик трьома пальцями + Перетягування трьома пальцями + Утримання трьома пальцями + Масштабування щипком + Утримувати кнопку натиснутою + Одне клацання + Затримка утримання + Інтервал подвійного дотику + Застосовується до поточної гри + Типові налаштування для всіх ігор + Відновити початкові налаштування жестів + Скасувати + Виберіть дію + Ліва кнопка миші + Права кнопка миші + Середня кнопка миші + Показати клавіатуру + Перетягування лівою кнопкою + Перетягування правою кнопкою + Переміщення середньою кнопкою миші + Переміщення середньою кнопкою миші (зворотне) + Клавіші зі стрілками + Клавіші зі стрілками (зворотні) + WASD (зворотне) + Коліщатко миші + Поріг жестів: %1$d пікс. + Показувати розпізнаний жест + Керування мишею та клавіатурою за жестами + Один палець + Два пальці + Три пальці + Параметри + Виберіть дію для дотику, перетягування чи утримання. + Налаштуйте переміщення камери, масштабування та додаткові клацання. + Тримайте додаткові команди під рукою. + Налаштуйте рух, розпізнавання та візуальний відгук. + Стандартні + Ця гра + Використовувати типові + Використовуються типові налаштування. Зміна створить налаштування для цієї гри. + Зберегти зміни + Закрити + ДІЯ + Для %1$s + Пошук дій миші або клавіш клавіатури + Очистити пошук + Усі + Відповідних дій немає. Спробуйте іншу назву клавіші або дії. + Миша + Дії застосунку + Навігація + Літери + Цифри + Функціональні клавіші + Клавіші-модифікатори + Цифровий блок + Символи + Рух миші + Пряме перетягування відповідає положенню дотику. Відносне відповідає руху пальця й корисне, коли гра повертає мишу до центру. + Переміщення середньою кнопкою завжди відповідає руху пальця, щоб уникнути стрибків курсора. + Пряме + Відносний + Розпізнавання жестів + Подолайте цю відстань, перш ніж жест двома чи трьома пальцями стане переміщенням камери або масштабуванням. + Візуальний відгук + Поведінка кнопки миші + %1$d мс + Цифровий блок: %1$s + Esc + Backspace + Enter + Tab + Пробіл + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Стрілка вгору + Стрілка вниз + Стрілка ліворуч + Стрілка праворуч + Caps Lock + Num Lock + Scroll Lock + Лівий %1$s + Правий %1$s + Shift + diff --git a/app/src/main/res/values-vi/gestures.xml b/app/src/main/res/values-vi/gestures.xml new file mode 100644 index 0000000000..cf6f95eef3 --- /dev/null +++ b/app/src/main/res/values-vi/gestures.xml @@ -0,0 +1,103 @@ + + + Cử chỉ + Cài đặt cử chỉ cảm ứng + Tùy chỉnh cử chỉ chuột và bàn phím. Chọn Cử chỉ làm chế độ cảm ứng để sử dụng. + Chạm + Kéo bằng một ngón tay + Nhấn giữ + Chạm hai lần (nhấp đúp chuột trái) + Chạm bằng hai ngón tay + Kéo bằng hai ngón tay + Giữ bằng hai ngón tay + Chạm bằng ba ngón tay + Kéo bằng ba ngón tay + Giữ bằng ba ngón tay + Chụm hoặc mở hai ngón tay để thu phóng + Giữ nút được nhấn + Nhấp một lần + Độ trễ nhấn giữ + Khoảng thời gian chạm hai lần + Áp dụng cho trò chơi hiện tại + Cài đặt mặc định cho mọi trò chơi + Khôi phục cài đặt cử chỉ ban đầu + Hủy + Chọn thao tác + Nhấp chuột trái + Nhấp chuột phải + Nhấp chuột giữa + Hiện bàn phím + Nhấp chuột trái và kéo + Nhấp chuột phải và kéo + Di chuyển bằng nút chuột giữa + Di chuyển bằng nút chuột giữa (đảo ngược) + Phím mũi tên + Phím mũi tên (đảo ngược) + WASD (đảo ngược) + Con lăn chuột + Ngưỡng cử chỉ: %1$d px + Hiện cử chỉ đã nhận dạng + Điều khiển chuột và bàn phím theo từng cử chỉ + Một ngón tay + Hai ngón tay + Ba ngón tay + Tùy chọn + Chọn thao tác cho chạm, kéo hoặc giữ. + Cấu hình di chuyển camera, thu phóng và nhấp phụ. + Giữ các phím tắt bổ sung trong tầm tay. + Tinh chỉnh chuyển động, nhận dạng và phản hồi hình ảnh. + Mặc định + Trò chơi này + Dùng mặc định + Đang dùng cài đặt mặc định. Chỉnh sửa sẽ tạo cài đặt riêng cho trò chơi. + Lưu thay đổi + Đóng + THAO TÁC + Cho %1$s + Tìm thao tác chuột hoặc phím bàn phím + Xóa tìm kiếm + Tất cả + Không có thao tác phù hợp. Thử tên phím hoặc thao tác khác. + Chuột + Thao tác ứng dụng + Điều hướng + Chữ cái + Chữ số + Phím chức năng + Phím bổ trợ + Bàn phím số + Ký hiệu + Chuyển động chuột + Kéo trực tiếp theo vị trí chạm. Kéo tương đối theo chuyển động ngón tay, hữu ích khi trò chơi đưa chuột về giữa. + Di chuyển bằng nút chuột giữa luôn theo chuyển động ngón tay để tránh con trỏ nhảy vị trí. + Trực tiếp + Tương đối + Nhận dạng cử chỉ + Di chuyển khoảng cách này trước khi cử chỉ hai hoặc ba ngón tay trở thành di chuyển camera hoặc thu phóng. + Phản hồi hình ảnh + Cách hoạt động của nút chuột + %1$d ms + Bàn phím số %1$s + Escape + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Mũi tên lên + Mũi tên xuống + Mũi tên trái + Mũi tên phải + Caps Lock + Num Lock + Scroll Lock + %1$s trái + %1$s phải + Shift + diff --git a/app/src/main/res/values-zh-rCN/gestures.xml b/app/src/main/res/values-zh-rCN/gestures.xml new file mode 100644 index 0000000000..c3b12946c2 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/gestures.xml @@ -0,0 +1,103 @@ + + + 手势 + 触屏手势设置 + 自定义鼠标和键盘手势。请选择“手势”触控模式以使用这些功能。 + 点按 + 单指拖动 + 长按 + 双击(鼠标左键双击) + 双指点按 + 双指拖动 + 双指按住 + 三指点按 + 三指拖动 + 三指按住 + 双指缩放 + 持续按住按钮 + 单击一次 + 按住延迟 + 双击间隔 + 应用于当前游戏 + 所有游戏的默认设置 + 恢复初始手势设置 + 取消 + 选择操作 + 左键单击 + 右键单击 + 中键单击 + 显示键盘 + 按住左键拖动 + 按住右键拖动 + 鼠标中键平移 + 鼠标中键平移(反向) + 方向键 + 方向键(反向) + WASD(反向) + 鼠标滚轮 + 手势阈值:%1$d 像素 + 显示识别到的手势 + 按手势分类的鼠标和键盘控制 + 单指 + 双指 + 三指 + 选项 + 选择点按、拖动或按住时执行的操作。 + 配置镜头平移、缩放和辅助单击。 + 随手使用更多快捷操作。 + 调整移动、识别和视觉反馈。 + 默认值 + 此游戏 + 使用默认设置 + 正在使用默认设置。修改后会创建此游戏的专用设置。 + 保存更改 + 关闭 + 操作 + 用于%1$s + 搜索鼠标操作或键盘按键 + 清除搜索 + 全部 + 没有匹配的操作。请尝试其他按键或操作名称。 + 鼠标 + 应用操作 + 导航 + 字母 + 数字 + 功能键 + 修饰键 + 数字小键盘 + 符号 + 鼠标移动 + 直接拖动跟随触摸位置。相对拖动跟随手指移动,适用于会将鼠标重置到中心的游戏。 + 鼠标中键平移始终跟随手指移动,以避免光标跳动。 + 直接 + 相对 + 手势识别 + 双指或三指移动达到此距离后,才会识别为平移或缩放。 + 视觉反馈 + 鼠标按钮行为 + %1$d 毫秒 + 数字小键盘 %1$s + Esc + 退格 + 回车 + Tab + 空格 + 删除 + 插入 + Home + End + 向上翻页 + 向下翻页 + 打印屏幕 + 向上箭头 + 向下箭头 + 向左箭头 + 向右箭头 + 大写锁定 + 数字锁定 + 滚动锁定 + 左 %1$s + 右 %1$s + Shift + diff --git a/app/src/main/res/values-zh-rHK/gestures.xml b/app/src/main/res/values-zh-rHK/gestures.xml new file mode 100644 index 0000000000..50d00f4108 --- /dev/null +++ b/app/src/main/res/values-zh-rHK/gestures.xml @@ -0,0 +1,103 @@ + + + 手勢 + 觸控手勢設定 + 自訂滑鼠與鍵盤手勢。請選擇「手勢」觸控模式以使用這些功能。 + 點按 + 單指拖曳 + 長按 + 連點兩下(滑鼠左鍵連按兩下) + 雙指點按 + 雙指拖曳 + 雙指按住 + 三指點按 + 三指拖曳 + 三指按住 + 雙指縮放 + 持續按住按鈕 + 按一下 + 按住延遲 + 連點兩下間隔 + 套用至目前遊戲 + 所有遊戲的預設設定 + 還原初始手勢設定 + 取消 + 選擇動作 + 按一下左鍵 + 按一下右鍵 + 按一下中鍵 + 顯示鍵盤 + 按住左鍵拖曳 + 按住右鍵拖曳 + 滑鼠中鍵平移 + 滑鼠中鍵平移(反向) + 方向鍵 + 方向鍵(反向) + WASD(反向) + 滑鼠滾輪 + 手勢閾值:%1$d 像素 + 顯示辨識到的手勢 + 依手勢分類的滑鼠與鍵盤控制 + 單指 + 雙指 + 三指 + 選項 + 選擇點按、拖曳或按住時執行的動作。 + 設定鏡頭平移、縮放與輔助點擊。 + 隨手使用更多快捷操作。 + 調整移動、辨識與視覺回饋。 + 預設值 + 此遊戲 + 使用預設值 + 正在使用預設設定。修改後會建立此遊戲的專用設定。 + 儲存變更 + 關閉 + 動作 + 用於%1$s + 搜尋滑鼠動作或鍵盤按鍵 + 清除搜尋 + 全部 + 沒有符合的動作。請嘗試其他按鍵或動作名稱。 + 滑鼠 + 應用程式動作 + 導覽 + 字母 + 數字 + 功能鍵 + 修飾鍵 + 數字鍵盤 + 符號 + 滑鼠移動 + 直接拖曳會跟隨觸控位置。相對拖曳會跟隨手指移動,適用於會將滑鼠重設到中央的遊戲。 + 滑鼠中鍵平移一律跟隨手指移動,以避免游標跳動。 + 直接 + 相對 + 手勢辨識 + 雙指或三指移動達到此距離後,才會辨識為平移或縮放。 + 視覺回饋 + 滑鼠按鈕行為 + %1$d 毫秒 + 數字鍵盤 %1$s + Esc + 退格 + Enter + Tab + 空格 + 刪除 + 插入 + Home + End + 上一頁 + 下一頁 + 列印螢幕 + 向上箭頭 + 向下箭頭 + 向左箭頭 + 向右箭頭 + 大寫鎖定 + 數字鎖定 + 捲動鎖定 + 左 %1$s + 右 %1$s + Shift + diff --git a/app/src/main/res/values-zh-rTW/gestures.xml b/app/src/main/res/values-zh-rTW/gestures.xml new file mode 100644 index 0000000000..b51d68f112 --- /dev/null +++ b/app/src/main/res/values-zh-rTW/gestures.xml @@ -0,0 +1,103 @@ + + + 手勢 + 觸控手勢設定 + 自訂滑鼠與鍵盤手勢。請選擇「手勢」觸控模式以使用這些功能。 + 點按 + 單指拖曳 + 長按 + 連點兩下(滑鼠左鍵連按兩下) + 雙指點按 + 雙指拖曳 + 雙指按住 + 三指點按 + 三指拖曳 + 三指按住 + 雙指縮放 + 持續按住按鈕 + 按一下 + 按住延遲 + 連點兩下間隔 + 套用至目前遊戲 + 所有遊戲的預設設定 + 還原初始手勢設定 + 取消 + 選擇動作 + 按一下左鍵 + 按一下右鍵 + 按一下中鍵 + 顯示鍵盤 + 按住左鍵拖曳 + 按住右鍵拖曳 + 滑鼠中鍵平移 + 滑鼠中鍵平移(反向) + 方向鍵 + 方向鍵(反向) + WASD(反向) + 滑鼠滾輪 + 手勢閾值:%1$d 像素 + 顯示辨識到的手勢 + 依手勢分類的滑鼠與鍵盤控制 + 單指 + 雙指 + 三指 + 選項 + 選擇點按、拖曳或按住時執行的動作。 + 設定鏡頭平移、縮放與輔助點擊。 + 隨手使用更多快捷操作。 + 調整移動、辨識與視覺回饋。 + 預設值 + 此遊戲 + 使用預設值 + 正在使用預設設定。修改後會建立此遊戲的專用設定。 + 儲存變更 + 關閉 + 動作 + 用於%1$s + 搜尋滑鼠動作或鍵盤按鍵 + 清除搜尋 + 全部 + 沒有符合的動作。請嘗試其他按鍵或動作名稱。 + 滑鼠 + 應用程式動作 + 導覽 + 字母 + 數字 + 功能鍵 + 修飾鍵 + 數字鍵盤 + 符號 + 滑鼠移動 + 直接拖曳會跟隨觸控位置。相對拖曳會跟隨手指移動,適用於會將滑鼠重設到中央的遊戲。 + 滑鼠中鍵平移一律跟隨手指移動,以避免游標跳動。 + 直接 + 相對 + 手勢辨識 + 雙指或三指移動達到此距離後,才會辨識為平移或縮放。 + 視覺回饋 + 滑鼠按鈕行為 + %1$d 毫秒 + 數字鍵盤 %1$s + Esc + 退格 + Enter + Tab + Space + 刪除 + 插入 + Home + End + 上一頁 + 下一頁 + 列印螢幕 + 向上箭頭 + 向下箭頭 + 向左箭頭 + 向右箭頭 + 大寫鎖定 + 數字鎖定 + 捲動鎖定 + 左 %1$s + 右 %1$s + Shift + diff --git a/app/src/main/res/values/gestures.xml b/app/src/main/res/values/gestures.xml new file mode 100644 index 0000000000..0a7c5c25bf --- /dev/null +++ b/app/src/main/res/values/gestures.xml @@ -0,0 +1,103 @@ + + + Gestures + Touch gesture settings + Customize mouse and keyboard gestures. Select Gestures as the touch mode to use them. + Tap + One-finger drag + Long press + Double tap (double left click) + Two-finger tap + Two-finger drag + Two-finger hold + Three-finger tap + Three-finger drag + Three-finger hold + Pinch to zoom + Keep button held + Click once + Hold delay + Double-tap interval + Applies to the current game + Default settings for all games + Reset to original gesture settings + Cancel + Choose action + Left click + Right click + Middle click + Show keyboard + Left click and drag + Right click and drag + Middle mouse pan + Middle mouse pan (inverted) + Arrow keys + Arrow keys (inverted) + WASD (inverted) + Mouse wheel + Gesture threshold: %1$d px + Show recognized gesture + Mouse and keyboard controls, organized by gesture + One finger + Two fingers + Three fingers + Options + Choose what a tap, drag, or hold should do. + Configure camera panning, zoom, and secondary clicks. + Keep extra shortcuts within reach. + Fine-tune movement, recognition, and visual feedback. + Defaults + This game + Use defaults + Using default settings. Editing creates a game override. + Save changes + Close + ACTION + For %1$s + Search mouse actions or keyboard keys + Clear search + All + No matching actions. Try another key or action name. + Mouse + App actions + Navigation + Letters + Numbers + Function keys + Modifiers + Numpad + Symbols + Mouse movement + Direct drags follow your touch position. Relative drags follow finger movement, useful when a game recenters the mouse. + Middle mouse pan always follows finger movement to avoid cursor jumps. + Direct + Relative + Gesture recognition + Move this far before a two- or three-finger gesture becomes a pan or zoom. + Visual feedback + Mouse button behavior + %1$d ms + Numpad %1$s + Escape + Backspace + Enter + Tab + Space + Delete + Insert + Home + End + Page Up + Page Down + Print Screen + Up arrow + Down arrow + Left arrow + Right arrow + Caps Lock + Num Lock + Scroll Lock + Left %1$s + Right %1$s + Shift + diff --git a/app/src/test/java/com/droiddeck/launcher/input/GesturePrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/GesturePrefsTest.kt new file mode 100644 index 0000000000..b210be520a --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/GesturePrefsTest.kt @@ -0,0 +1,36 @@ +package com.droiddeck.launcher.input + +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class GesturePrefsTest { + @Test fun removedOptionsAreIgnoredWhenLoadingExistingSettings() { + val old = """{"holdMouseButtonWhileTouchingEnabled":true,"holdMouseButtonWhileTouchingAction":"right_click", + "showClickHighlight":true,"showCursorInTouchscreenMode":true,"tapAction":"key_E","longPressDelay":650}""" + val config = TouchGestureConfig.fromJson(old) + assertEquals("key_E", config.tapAction) + assertEquals(650, config.longPressDelay) + assertFalse(config.toJson().contains("holdMouseButtonWhileTouching")) + assertFalse(config.toJson().contains("showClickHighlight")) + assertFalse(config.toJson().contains("showCursorInTouchscreenMode")) + } + + @Test fun gameOverridesFallBackToDefaultsAndSurviveSerialization() { + val context = RuntimeEnvironment.getApplication() + val defaults = TouchGestureConfig(tapAction = "key_E", mouseDragMovementMode = "relative") + GesturePrefs.save(context, null, defaults) + assertEquals(defaults, GesturePrefs.read(context, "123")) + val game = defaults.copy(twoFingerTapAction = "show_keyboard", longPressDelay = 650) + GesturePrefs.save(context, "123", game) + assertEquals(game, GesturePrefs.read(context, "123")) + assertEquals(defaults, GesturePrefs.read(context, "456")) + GesturePrefs.clear(context, "123") + assertEquals(defaults, GesturePrefs.read(context, "123")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/GestureRoutingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/GestureRoutingTest.kt new file mode 100644 index 0000000000..a9e672ea5e --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/GestureRoutingTest.kt @@ -0,0 +1,61 @@ +package com.droiddeck.launcher.input + +import android.os.Looper +import android.os.SystemClock +import android.view.Gravity +import android.view.InputDevice +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.widget.FrameLayout +import java.time.Duration +import org.junit.Assert.assertEquals +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 + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class GestureRoutingTest { + @Test fun controlFingerDoesNotCountTowardGestureWhenControlIsTouchedFirst() = checkOrder(controlFirst = true) + @Test fun controlFingerDoesNotCountTowardGestureWhenScreenIsTouchedFirst() = checkOrder(controlFirst = false) + + private fun checkOrder(controlFirst: Boolean) { + val context = RuntimeEnvironment.getApplication() + val buttons = mutableListOf>() + val gestures = TouchscreenGestures(ViewConfiguration.get(context).scaledTouchSlop.toFloat(), object : TouchscreenGestures.Output { + override fun moveTo(x: Float, y: Float) {} + override fun moveBy(dx: Float, dy: Float, relative: Boolean) {} + override fun button(code: Int, down: Boolean) { buttons += code to down } + override fun key(code: Int, down: Boolean) {} + override fun wheel(steps: Int) {} + override fun showKeyboard() {} + }) + val root = FrameLayout(context).apply { isMotionEventSplittingEnabled = true } + root.addView(View(context).apply { setOnTouchListener { _, e -> gestures.onTouch(e) } }, FrameLayout.LayoutParams(1000, 600)) + root.addView(View(context).apply { setOnTouchListener { _, _ -> true } }, FrameLayout.LayoutParams(200, 600, Gravity.RIGHT)) + root.measure(View.MeasureSpec.makeMeasureSpec(1000, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY)) + root.layout(0, 0, 1000, 600) + val firstX = if (controlFirst) 900f else 400f + val secondX = if (controlFirst) 400f else 900f + val downTime = SystemClock.uptimeMillis() + fun send(action: Int, index: Int, vararg points: Pair) { + val properties = points.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray() + val coords = points.map { (_, px) -> MotionEvent.PointerCoords().apply { x = px; y = 300f; pressure = 1f; size = 1f } }.toTypedArray() + MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), points.size, + properties, coords, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0).also { + root.dispatchTouchEvent(it); it.recycle() + } + } + send(MotionEvent.ACTION_DOWN, 0, 3 to firstX) + send(MotionEvent.ACTION_POINTER_DOWN, 1, 3 to firstX, 8 to secondX) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(30)) + send(MotionEvent.ACTION_POINTER_UP, 1, 3 to firstX, 8 to secondX) + send(MotionEvent.ACTION_UP, 0, 3 to firstX) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(100)) + assertEquals(listOf(272 to true, 272 to false), buttons) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionGestureRoutingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionGestureRoutingTest.kt new file mode 100644 index 0000000000..7b2a55e2e0 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionGestureRoutingTest.kt @@ -0,0 +1,266 @@ +package com.droiddeck.launcher.input + +import android.os.Looper +import android.os.SystemClock +import android.content.res.Configuration +import android.view.InputDevice +import android.view.MotionEvent +import android.view.SurfaceView +import com.droiddeck.launcher.SessionActivity +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState +import com.droiddeck.launcher.wayland.WaylandCompositor +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.Implementation +import org.robolectric.annotation.Implements +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE, shadows = [SessionGestureRoutingTest.CompositorShadow::class]) +class SessionGestureRoutingTest { + private lateinit var activity: SessionActivity + private lateinit var gestures: TouchscreenGestures + private lateinit var steamTap: ThreeFingerTap + private lateinit var launcherScroll: ScrollTouchGestures + private lateinit var directHold: DirectTouchHold + private val keys = mutableListOf>() + private val directButtons = mutableListOf>() + private val scrollPositions = mutableListOf>() + private val scrollDeltas = mutableListOf>() + private var keyboards = 0 + + @After fun tearDown() { + if (::gestures.isInitialized) gestures.cancel() + if (::launcherScroll.isInitialized) launcherScroll.cancel() + if (::directHold.isInitialized) directHold.cancel() + SessionState.mode = SessionService.MODE_STEAM + SessionState.steamUi = null + SessionState.suspended = false + } + + @Test fun configuredThreeFingerActionTakesPrecedenceOverSteamShortcut() { + prepare(SessionPrefs.TOUCH_GESTURES, TouchGestureConfig(threeFingerTapAction = "key_E")) + tapThreeFingers(expectSteamGesture = false) + assertEquals(listOf(18 to true, 18 to false), keys) + assertEquals(0, keyboards) + } + + @Test fun disablingThreeFingerTapDoesNotFallBackToSteamShortcut() { + prepare(SessionPrefs.TOUCH_GESTURES, TouchGestureConfig(threeFingerTapEnabled = false)) + tapThreeFingers(expectSteamGesture = false) + assertTrue(keys.isEmpty()) + assertEquals(0, keyboards) + } + + @Test fun defaultThreeFingerActionOpensPcKeyboardOnce() { + prepare(SessionPrefs.TOUCH_GESTURES) + tapThreeFingers(expectSteamGesture = false) + assertEquals(1, keyboards) + assertTrue(keys.isEmpty()) + } + + @Test fun gestureModeKeepsItsBindingsWhileLauncherMouseIsAvailable() { + prepare(SessionPrefs.TOUCH_GESTURES, TouchGestureConfig(threeFingerTapAction = "key_E")) + setField("padMouseOn", true) + tapThreeFingers(expectSteamGesture = false) + assertEquals(listOf(18 to true, 18 to false), keys) + assertTrue(scrollPositions.isEmpty()) + assertTrue(scrollDeltas.isEmpty()) + } + + @Test fun directModeStillRoutesLauncherTouchesToScrolling() { + prepare(SessionPrefs.TOUCH_DIRECT) + setField("padMouseOn", true) + val down = SystemClock.uptimeMillis() + for ((index, action) in listOf(MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE, MotionEvent.ACTION_UP).withIndex()) { + val event = MotionEvent.obtain(down, down + index * 32L, action, 400f, if (index == 0) 300f else 200f, 0) + try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() } + } + assertEquals(listOf(400f to 300f), scrollPositions) + assertTrue(scrollDeltas.isNotEmpty()) + assertTrue(keys.isEmpty()) + assertFalse(steamTap.active) + } + + @Test fun upstreamSteamShortcutStillReceivesTouchesInLegacyModes() { + for (mode in listOf(SessionPrefs.TOUCH_DIRECT, SessionPrefs.TOUCH_PAD)) { + prepare(mode) + tapThreeFingers(expectSteamGesture = true) + assertTrue(keys.isEmpty()) + assertEquals(0, keyboards) + } + } + + @Test fun configurationChangeReleasesHeldGestureAndResetsPointerAnchor() { + startLongPress() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350)) + assertEquals(listOf(18 to true), keys) + activity.onConfigurationChanged(Configuration(activity.resources.configuration).apply { + orientation = Configuration.ORIENTATION_PORTRAIT + }) + assertEquals(listOf(18 to true, 18 to false), keys) + assertFalse(SessionActivity::class.java.getDeclaredField("gesturePointerReady").apply { isAccessible = true }.getBoolean(activity)) + } + + @Test fun surfaceResizeCancelsPendingHoldAndResetsPointerAnchor() { + startLongPress() + setField("surfaceW", 1000) + setField("surfaceH", 600) + val window = android.view.Surface(android.graphics.SurfaceTexture(0)) + var activeHolder: android.view.SurfaceHolder? = null + val surface = object : SurfaceView(RuntimeEnvironment.getApplication()) { + override fun getHolder() = activeHolder ?: super.getHolder() + }.apply { layout(0, 0, 1000, 600) } + activeHolder = object : android.view.SurfaceHolder by surface.holder { + override fun getSurface() = window + } + setField("surfaceView", surface) + try { activity.surfaceChanged(surface.holder, 0, 800, 600) } finally { window.release() } + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350)) + assertTrue(keys.isEmpty()) + assertFalse(SessionActivity::class.java.getDeclaredField("gesturePointerReady").apply { isAccessible = true }.getBoolean(activity)) + } + + @Test fun unchangedSurfaceDimensionsDoNotInterruptPendingHold() { + startLongPress() + setField("surfaceW", 1000) + setField("surfaceH", 600) + val surface = SessionActivity::class.java.getDeclaredField("surfaceView").apply { isAccessible = true }.get(activity) as SurfaceView + activity.surfaceChanged(surface.holder, 0, 1000, 600) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350)) + assertEquals(listOf(18 to true), keys) + } + + @Test fun inactiveSurfaceDestructionDoesNotInterruptCurrentGesture() { + startLongPress() + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(350)) + val staleSurface = SurfaceView(RuntimeEnvironment.getApplication()) + activity.surfaceDestroyed(staleSurface.holder) + assertEquals(listOf(18 to true), keys) + assertTrue(SessionActivity::class.java.getDeclaredField("gesturePointerReady").apply { isAccessible = true }.getBoolean(activity)) + } + + @Test fun pausingCancelsPendingHoldsInBothTouchModes() { + for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) { + prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E")) + val now = SystemClock.uptimeMillis() + val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0) + try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() } + ReflectionHelpers.callInstanceMethod(activity, "onPause") + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(700)) + assertTrue(keys.isEmpty()) + assertTrue(directButtons.isEmpty()) + } + } + + @Test fun pausingReleasesActiveHoldsInBothTouchModes() { + for (mode in listOf(SessionPrefs.TOUCH_GESTURES, SessionPrefs.TOUCH_DIRECT)) { + keys.clear() + directButtons.clear() + prepare(mode, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E")) + val now = SystemClock.uptimeMillis() + val event = MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0) + try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() } + val gestureMode = mode == SessionPrefs.TOUCH_GESTURES + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(if (gestureMode) 350 else 500)) + assertEquals(if (gestureMode) listOf(18 to true) else emptyList(), keys) + assertEquals(if (gestureMode) emptyList() else listOf(PointerGestures.BTN_RIGHT to true), directButtons) + ReflectionHelpers.callInstanceMethod(activity, "onPause") + assertEquals(if (gestureMode) listOf(18 to true, 18 to false) else emptyList(), keys) + assertEquals(if (gestureMode) emptyList() else listOf(PointerGestures.BTN_RIGHT to true, PointerGestures.BTN_RIGHT to false), directButtons) + } + } + + private fun startLongPress() { + prepare(SessionPrefs.TOUCH_GESTURES, TouchGestureConfig(longPressEnabled = true, longPressAction = "key_E")) + val now = SystemClock.uptimeMillis() + MotionEvent.obtain(now, now, MotionEvent.ACTION_DOWN, 400f, 300f, 0).also { + try { assertTrue(activity.onTouchEvent(it)) } finally { it.recycle() } + } + setField("gesturePointerReady", true) + } + + private fun prepare(mode: String, config: TouchGestureConfig = TouchGestureConfig()) { + SessionState.mode = SessionService.MODE_STEAM + SessionState.steamUi = "bigpicture" + SessionState.suspended = false + activity = Robolectric.buildActivity(SessionActivity::class.java).get() + steamTap = ThreeFingerTap(8f) + gestures = TouchscreenGestures(8f, object : TouchscreenGestures.Output { + override fun moveTo(x: Float, y: Float) {} + override fun moveBy(dx: Float, dy: Float, relative: Boolean) {} + override fun button(code: Int, down: Boolean) { fail("Unexpected mouse button: $code $down") } + override fun key(code: Int, down: Boolean) { keys += code to down } + override fun wheel(steps: Int) { fail("Unexpected wheel input") } + override fun showKeyboard() { keyboards++ } + }).also { it.configure(config) } + setField("routedTouchMode", mode) + setField("padMouseCheckedAt", SystemClock.uptimeMillis()) + setField("threeFingerTap", steamTap) + setField("touchscreenGestures", gestures) + setField("surfaceView", SurfaceView(RuntimeEnvironment.getApplication()).apply { layout(0, 0, 1000, 600) }) + setField("touchpad", TouchpadGestures(8f, object : PointerGestures.Listener { + override fun onMove(x: Float, y: Float) {} + override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) {} + override fun onWheel(steps: Int) {} + override fun onLongPress() {} + })) + directHold = DirectTouchHold(8f, object : PointerGestures.Listener { + override fun onMove(x: Float, y: Float) {} + override fun onButton(button: Int, pressed: Boolean, x: Float, y: Float) { directButtons += button to pressed } + override fun onWheel(steps: Int) {} + override fun onLongPress() {} + }) {} + setField("directTouchHold", directHold) + launcherScroll = ScrollTouchGestures(8f, 50f, object : ScrollTouchGestures.Listener { + override fun onMove(x: Float, y: Float) { scrollPositions += x to y } + override fun onButton(button: Int, pressed: Boolean) {} + override fun onScroll(dx: Float, dy: Float) { scrollDeltas += dx to dy } + override fun onLongPress() {} + }) + setField("scrollTouch", launcherScroll) + } + + private fun tapThreeFingers(expectSteamGesture: Boolean) { + val down = SystemClock.uptimeMillis() + fun send(action: Int, index: Int, count: Int) { + val properties = Array(count) { MotionEvent.PointerProperties().apply { id = it; toolType = MotionEvent.TOOL_TYPE_FINGER } } + val coordinates = Array(count) { MotionEvent.PointerCoords().apply { x = 300f + it * 100; y = 300f; pressure = 1f } } + val event = MotionEvent.obtain(down, SystemClock.uptimeMillis(), action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), + count, properties, coordinates, 0, 0, 1f, 1f, 0, 0, InputDevice.SOURCE_TOUCHSCREEN, 0) + try { assertTrue(activity.onTouchEvent(event)) } finally { event.recycle() } + } + send(MotionEvent.ACTION_DOWN, 0, 1) + send(MotionEvent.ACTION_POINTER_DOWN, 1, 2) + send(MotionEvent.ACTION_POINTER_DOWN, 2, 3) + assertEquals(expectSteamGesture, steamTap.active) + send(MotionEvent.ACTION_POINTER_UP, 2, 3) + send(MotionEvent.ACTION_POINTER_UP, 1, 2) + send(MotionEvent.ACTION_UP, 0, 1) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(200)) + assertFalse(steamTap.active) + } + + private fun setField(name: String, value: Any) { + SessionActivity::class.java.getDeclaredField(name).apply { isAccessible = true }.set(activity, value) + } + + @Implements(value = WaylandCompositor::class, isInAndroidSdk = false) + class CompositorShadow { + companion object { + @JvmStatic @Implementation fun __staticInitializer__() {} + @JvmStatic @Implementation fun nativeSendTouch(action: Int, id: Int, x: Int, y: Int) {} + @JvmStatic @Implementation fun nativeSendSceneInput(type: Int, code: Int, value: Int) {} + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/TouchscreenGesturesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/TouchscreenGesturesTest.kt new file mode 100644 index 0000000000..ad85d62453 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/TouchscreenGesturesTest.kt @@ -0,0 +1,1055 @@ +package com.droiddeck.launcher.input + +import android.os.Looper +import android.os.SystemClock +import android.view.MotionEvent +import android.view.ViewConfiguration +import java.time.Duration +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 + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class TouchscreenGesturesTest { + private val events = mutableListOf() + private data class ButtonEvent(val time: Long, val down: Boolean, val position: Pair) + private val leftClicks = mutableListOf() + private val rightClicks = mutableListOf() + private val timedKeys = mutableListOf>() + private val absoluteMoves = mutableListOf>() + private val relativeMoves = mutableListOf>() + private val recognized = mutableListOf() + private var cursor = 0f to 0f + private lateinit var gestures: TouchscreenGestures + private var downTime = 0L + private val a = 7 to (400f to 300f) + private val b = 12 to (600f to 300f) + private val c = 19 to (800f to 300f) + private val d = 24 to (1000f to 300f) + + @Before fun setUp() { + advance(1000) + gestures = TouchscreenGestures(ViewConfiguration.get(RuntimeEnvironment.getApplication()).scaledTouchSlop.toFloat(), object : TouchscreenGestures.Output { + override fun moveTo(x: Float, y: Float) { + cursor = x to y; absoluteMoves += cursor; events += "move" + } + override fun moveBy(dx: Float, dy: Float, relative: Boolean) { + if (relative) relativeMoves += dx to dy + events += "delta $relative" + } + override fun button(code: Int, down: Boolean) { + events += "button $code $down" + if (code == 272) leftClicks += ButtonEvent(SystemClock.uptimeMillis(), down, cursor) + if (code == 273) rightClicks += ButtonEvent(SystemClock.uptimeMillis(), down, cursor) + } + override fun key(code: Int, down: Boolean) { + events += "key $code $down" + timedKeys += Triple(SystemClock.uptimeMillis(), code, down) + } + override fun wheel(steps: Int) { events += "wheel $steps" } + override fun showKeyboard() { events += "keyboard" } + override fun prepareRelativePan() { events += "prepare pan" } + override fun gesture(gesture: TouchscreenGestures.Gesture) { recognized += gesture } + }) + } + + @Test fun tapHasOnePressAndADelayedRelease() { + tap() + assertEquals(listOf("button 272 true"), buttons()) + advance(60) + assertEquals(listOf("button 272 true", "button 272 false"), buttons()) + } + + @Test fun recognizedFeedbackIsTypedAndOnlyEmittedWhenEnabled() { + tap(); advance(150) + assertTrue(recognized.isEmpty()) + gestures.configure(TouchGestureConfig(showGestureDebugOverlay = true)) + tap() + assertEquals(listOf(TouchscreenGestures.Gesture.TAP), recognized) + } + + @Test fun doubleTapProducesTwoClicksRatherThanThree() { + tap(); advance(80); tap(); advance(80) + assertEquals(listOf("button 272 true", "button 272 false", "button 272 true", "button 272 false"), buttons()) + } + + @Test fun aVeryFastDoubleTapKeepsFullPressesAndAReleaseGap() { + tap(); tap(); advance(250) + assertEquals(4, leftClicks.size) + assertTrue(leftClicks[1].time - leftClicks[0].time >= 50) + assertTrue(leftClicks[2].time - leftClicks[1].time >= 50) + assertTrue(leftClicks[3].time - leftClicks[2].time >= 50) + } + + @Test fun doubleTapUsesTheFirstClickLocationDespiteNormalFingerDrift() { + tap(); advance(80) + touch(MotionEvent.ACTION_DOWN, 0, 7 to (404f to 303f)) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (406f to 304f)) + advance(30) + touch(MotionEvent.ACTION_UP, 0, 7 to (406f to 304f)) + advance(200) + assertEquals(4, leftClicks.size) + assertTrue(leftClicks.all { it.position == a.second }) + } + + @Test fun quickTapsOnVerticallyAdjacentIconsClickEachIconOnce() { + val below = 7 to (400f to 345f) + tap(); tap(below); advance(250) + assertEquals(listOf(a.second, below.second), leftClicks.filter { it.down }.map { it.position }) + } + + @Test fun quickTapsOnHorizontallyAdjacentIconsClickEachIconOnce() { + val beside = 7 to (445f to 300f) + tap(); tap(beside); advance(250) + assertEquals(listOf(a.second, beside.second), leftClicks.filter { it.down }.map { it.position }) + } + + @Test fun fastClicksAcrossThreeIconsDoNotSnapBackToEarlierIcons() { + val below = 7 to (400f to 345f) + val bottom = 7 to (400f to 390f) + tap(); tap(below); tap(bottom); advance(350) + assertEquals(listOf(a.second, below.second, bottom.second), leftClicks.filter { it.down }.map { it.position }) + } + + @Test fun aDoubleTapWithoutASingleTapHasAReleaseGapBetweenSynthesizedClicks() { + gestures.configure(TouchGestureConfig(tapEnabled = false)) + tap(); tap(); advance(250) + assertEquals(4, leftClicks.size) + assertTrue(leftClicks[2].time - leftClicks[1].time >= 50) + } + + @Test fun aRapidThirdTapDoesNotDiscardThePendingSecondClick() { + tap(); tap(); tap(); advance(350) + assertEquals(6, leftClicks.size) + assertEquals(listOf(true, false, true, false, true, false), leftClicks.map { it.down }) + } + + @Test fun cancellingBetweenDoubleClicksStopsTheQueuedClick() { + tap(); tap() + gestures.cancel() + events.clear(); advance(2000) + assertTrue(events.isEmpty()) + } + + @Test fun aTouchCancelDoesNotPrimeTheFollowingTapAsADoubleTap() { + tap(); advance(80) + touch(MotionEvent.ACTION_CANCEL, 0, a) + events.clear() + touch(MotionEvent.ACTION_DOWN, 0, a) + advance(100) + assertTrue(buttons().isEmpty()) + } + + @Test fun firstTapNearOriginIsNotMistakenForADoubleTap() { + touch(MotionEvent.ACTION_DOWN, 0, 1 to (1f to 1f)) + assertTrue(buttons().isEmpty()) + } + + @Test fun doubleClickIsNotCommittedUntilTheSecondFingerLifts() { + tap(); advance(80) + touch(MotionEvent.ACTION_DOWN, 0, a) + advance(30) + assertEquals(2, leftClicks.size) + touch(MotionEvent.ACTION_UP, 0, a) + advance(60) + assertEquals(listOf(true, false, true, false), leftClicks.map { it.down }) + } + + @Test fun aTapFollowedByADragAtTheSamePlaceDoesNotSwallowTheDrag() { + tap(); advance(80) + touch(MotionEvent.ACTION_DOWN, 0, a) + assertEquals(2, leftClicks.size) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f)) + assertEquals(3, leftClicks.size) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (520f to 300f)) + assertEquals(520f to 300f, cursor) + touch(MotionEvent.ACTION_UP, 0, 7 to (520f to 300f)) + advance(500) + assertEquals(listOf(true, false, true, false), leftClicks.map { it.down }) + } + + @Test fun aTapFollowedByARelativeDragStartsAtTheNewTouchOrigin() { + gestures.configure(TouchGestureConfig(mouseDragMovementMode = "relative")) + tap(); advance(80) + val second = 7 to (404f to 303f) + touch(MotionEvent.ACTION_DOWN, 0, second) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (484f to 303f)) + assertEquals(second.second, leftClicks.last().position) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (494f to 303f)) + assertEquals(10f to 0f, relativeMoves.last()) + gestures.cancel() + assertEquals(4, leftClicks.size) + } + + @Test fun aTapFollowedByALongPressUsesItsHoldBindingInsteadOfDoubleClicking() { + gestures.configure(TouchGestureConfig(longPressEnabled = true, longPressAction = "right_click")) + tap(); advance(80) + val second = 7 to (404f to 303f) + touch(MotionEvent.ACTION_DOWN, 0, second) + advance(350) + assertEquals(2, leftClicks.size) + assertEquals(listOf("button 273 true"), buttons().filter { it.contains("273") }) + assertEquals(second.second, rightClicks.single().position) + touch(MotionEvent.ACTION_UP, 0, second) + advance(500) + assertEquals(listOf(true, false), rightClicks.map { it.down }) + assertEquals(2, leftClicks.size) + } + + @Test fun aLongSecondTouchIsNotASynthesizedDoubleTapWhenHoldsAreDisabled() { + gestures.configure(TouchGestureConfig(tapEnabled = false, longPressEnabled = false)) + tap(); advance(80) + touch(MotionEvent.ACTION_DOWN, 0, a) + advance(ViewConfiguration.getLongPressTimeout().toLong() + 20) + touch(MotionEvent.ACTION_UP, 0, a) + advance(500) + assertTrue(buttons().isEmpty()) + } + + @Test fun addingAnotherFingerToAPotentialDoubleTapDoesNotClickLeftAgain() { + tap(); advance(80) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(30) + touch(MotionEvent.ACTION_POINTER_UP, 1, a, b) + touch(MotionEvent.ACTION_UP, 0, a) + advance(80) + assertEquals(2, leftClicks.size) + assertEquals(listOf(true, false), rightClicks.map { it.down }) + } + + @Test fun movingTheSecondTouchToANeighboringIconKeepsThatTarget() { + tap(); advance(80) + touch(MotionEvent.ACTION_DOWN, 0, a) + val beside = 7 to (445f to 300f) + touch(MotionEvent.ACTION_MOVE, 0, beside) + touch(MotionEvent.ACTION_UP, 0, beside) + advance(80) + assertEquals(listOf(a.second, beside.second), leftClicks.filter { it.down }.map { it.position }) + } + + @Test fun endingTheSecondTouchOnAnotherIconWithoutAMoveEventKeepsItsTarget() { + tap(); advance(80) + touch(MotionEvent.ACTION_DOWN, 0, a) + val beside = 7 to (445f to 300f) + touch(MotionEvent.ACTION_UP, 0, beside) + advance(80) + assertEquals(listOf(a.second, beside.second), leftClicks.filter { it.down }.map { it.position }) + } + + @Test fun cancellingAPotentialDoubleTapCannotLeaveAQueuedClick() { + tap(); advance(80) + touch(MotionEvent.ACTION_DOWN, 0, a) + gestures.cancel(); advance(1000) + assertEquals(listOf(true, false), leftClicks.map { it.down }) + } + + @Test fun doubleTapStillDoubleClicksWhenSingleTapIsDisabled() { + gestures.configure(TouchGestureConfig(tapEnabled = false)) + tap(); advance(80); tap(); advance(150) + assertEquals(listOf("button 272 true", "button 272 false", "button 272 true", "button 272 false"), buttons()) + } + + @Test fun doubleTapStillDoubleClicksWhenSingleTapIsAKeyboardAction() { + gestures.configure(TouchGestureConfig(tapAction = "key_E")) + tap(); advance(80); tap(); advance(150) + assertEquals(listOf("button 272 true", "button 272 false", "button 272 true", "button 272 false"), buttons()) + assertEquals(listOf("key 18 true", "key 18 false"), events.filter { it.startsWith("key") }) + } + + @Test fun shortDragPressesBeforeLiftAndDoesNotPrimeADoubleTap() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f)) + assertEquals(listOf("button 272 true"), buttons()) + touch(MotionEvent.ACTION_UP, 0, 7 to (480f to 300f)) + touch(MotionEvent.ACTION_DOWN, 0, 7 to (480f to 300f)) + assertEquals(listOf("button 272 true", "button 272 false"), buttons()) + } + + @Test fun twoFingerTapIsRightClickWithoutALeftClickOnFinalLift() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(80) + touch(MotionEvent.ACTION_POINTER_UP, 1, a, b) + touch(MotionEvent.ACTION_UP, 0, a) + advance(80) + assertEquals(listOf("button 273 true", "button 273 false"), buttons()) + } + + @Test fun twoFingerTapKeepsItsPressAfterTheLastFingerLifts() { + twoFingerTap() + assertEquals(listOf("button 273 true"), buttons()) + advance(49) + assertEquals(1, rightClicks.size) + advance(1) + assertEquals(listOf(true, false), rightClicks.map { it.down }) + assertEquals(50L, rightClicks[1].time - rightClicks[0].time) + } + + @Test fun threeFingerKeyboardTapHasAnObservablePressAndReleases() { + gestures.configure(TouchGestureConfig(threeFingerTapAction = "key_E")) + threeFingerTap() + assertEquals(listOf("key 18 true"), events.filter { it.startsWith("key") }) + advance(50) + assertEquals(listOf("key 18 true", "key 18 false"), events.filter { it.startsWith("key") }) + assertEquals(50L, timedKeys.last().first - timedKeys.first().first) + } + + @Test fun twoFingerKeyboardTapHasAnObservablePressAndReleases() { + gestures.configure(TouchGestureConfig(twoFingerTapAction = "key_E")) + twoFingerTap(); advance(50) + assertEquals(listOf(true, false), timedKeys.map { it.third }) + assertEquals(50L, timedKeys.last().first - timedKeys.first().first) + } + + @Test fun threeFingerMouseTapHasAnObservablePressAndReleases() { + gestures.configure(TouchGestureConfig(threeFingerTapAction = "right_click")) + threeFingerTap() + assertEquals(listOf("button 273 true"), buttons()) + advance(50) + assertEquals(listOf(true, false), rightClicks.map { it.down }) + assertEquals(50L, rightClicks[1].time - rightClicks[0].time) + } + + @Test fun cancellingAMultiFingerTapReleasesItsButtonAndStopsCallbacks() { + twoFingerTap(); advance(10) + gestures.cancel() + assertEquals(listOf("button 273 true", "button 273 false"), buttons()) + events.clear(); advance(2000) + assertTrue(events.isEmpty()) + } + + @Test fun changingConfigDuringAThreeFingerKeyTapReleasesTheKey() { + gestures.configure(TouchGestureConfig(threeFingerTapAction = "key_E")) + threeFingerTap(); advance(10) + gestures.configure(TouchGestureConfig()) + assertEquals(listOf("key 18 true", "key 18 false"), events.filter { it.startsWith("key") }) + events.clear(); advance(2000) + assertTrue(events.isEmpty()) + } + + @Test fun rapidRightClicksKeepAReleaseGapBetweenThem() { + gestures.configure(TouchGestureConfig(tapAction = "right_click", doubleTapEnabled = false)) + tap(); tap(); advance(250) + assertEquals(listOf(true, false, true, false), rightClicks.map { it.down }) + assertTrue(rightClicks[2].time - rightClicks[1].time >= 50) + } + + @Test fun aFastTwoFingerSwipeDuringSettlingDoesNotClick() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(30) + val movedA = 7 to (480f to 300f) + val movedB = 12 to (680f to 300f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB) + touch(MotionEvent.ACTION_POINTER_UP, 1, movedA, movedB) + touch(MotionEvent.ACTION_UP, 0, movedA) + advance(1000) + assertTrue(buttons().isEmpty()) + assertFalse(events.any { it.startsWith("key") || it.startsWith("wheel") }) + } + + @Test fun aFastPinchDuringSettlingDoesNotClick() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(30) + val movedA = 7 to (370f to 300f) + val movedB = 12 to (630f to 300f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB) + touch(MotionEvent.ACTION_POINTER_UP, 1, movedA, movedB) + touch(MotionEvent.ACTION_UP, 0, movedA) + advance(1000) + assertTrue(buttons().isEmpty()) + } + + @Test fun earlySwipeMovementCancelsTheHoldEvenIfFingersThenStop() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(30) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f), 12 to (680f to 300f)) + advance(600) + assertTrue(buttons().isEmpty()) + gestures.cancel() + } + + @Test fun movementOnlyReportedOnLiftCannotBecomeATwoFingerTap() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(30) + touch(MotionEvent.ACTION_POINTER_UP, 1, 7 to (480f to 300f), 12 to (680f to 300f)) + touch(MotionEvent.ACTION_UP, 0, 7 to (480f to 300f)) + advance(600) + assertTrue(buttons().isEmpty()) + } + + @Test fun smallTwoFingerPlacementJitterStillAllowsATap() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(20) + val movedA = 7 to (404f to 303f) + val movedB = 12 to (596f to 297f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB) + touch(MotionEvent.ACTION_POINTER_UP, 1, movedA, movedB) + touch(MotionEvent.ACTION_UP, 0, movedA) + advance(80) + assertEquals(listOf("button 273 true", "button 273 false"), buttons()) + } + + @Test fun smallTwoFingerPlacementJitterStillAllowsAHold() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(20) + val movedA = 7 to (404f to 303f) + val movedB = 12 to (596f to 297f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB) + advance(350) + assertEquals(listOf("button 274 true"), buttons()) + touch(MotionEvent.ACTION_POINTER_UP, 1, movedA, movedB) + touch(MotionEvent.ACTION_UP, 0, movedA) + assertEquals(listOf("button 274 true", "button 274 false"), buttons()) + } + + @Test fun smallThreeFingerPlacementJitterStillAllowsAHold() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(20) + val movedA = 7 to (404f to 303f) + val movedB = 12 to (604f to 303f) + val movedC = 19 to (804f to 303f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB, movedC) + advance(350) + assertEquals(listOf("key 1 true"), events.filter { it.startsWith("key") }) + touch(MotionEvent.ACTION_POINTER_UP, 2, movedA, movedB, movedC) + touch(MotionEvent.ACTION_POINTER_UP, 1, movedA, movedB) + touch(MotionEvent.ACTION_UP, 0, movedA) + assertEquals(listOf("key 1 true", "key 1 false"), events.filter { it.startsWith("key") }) + assertFalse(events.contains("keyboard")) + } + + @Test fun aFastThreeFingerSwipeDuringSettlingDoesNotTapOrHold() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(20) + val movedA = 7 to (460f to 300f) + val movedB = 12 to (660f to 300f) + val movedC = 19 to (860f to 300f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB, movedC) + touch(MotionEvent.ACTION_POINTER_UP, 2, movedA, movedB, movedC) + touch(MotionEvent.ACTION_POINTER_UP, 1, movedA, movedB) + touch(MotionEvent.ACTION_UP, 0, movedA) + advance(1000) + assertFalse(events.any { it == "keyboard" || it.startsWith("key") || it.startsWith("button") }) + } + + @Test fun addingAThirdFingerResetsTheMovementOriginsForItsTap() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(20) + val movedA = 7 to (435f to 300f) + val movedB = 12 to (635f to 300f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, movedA, movedB, c) + advance(20) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (440f to 300f), 12 to (640f to 300f), 19 to (805f to 300f)) + touch(MotionEvent.ACTION_POINTER_UP, 2, 7 to (440f to 300f), 12 to (640f to 300f), 19 to (805f to 300f)) + touch(MotionEvent.ACTION_POINTER_UP, 1, 7 to (440f to 300f), 12 to (640f to 300f)) + touch(MotionEvent.ACTION_UP, 0, 7 to (440f to 300f)) + advance(80) + assertEquals(1, events.count { it == "keyboard" }) + assertTrue(buttons().isEmpty()) + } + + @Test fun replacingAFingerAfterAPanCannotRestartATapBeforeAllFingersLift() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + val movedA = 7 to (480f to 300f) + val movedB = 12 to (680f to 300f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB) + touch(MotionEvent.ACTION_POINTER_UP, 1, movedA, movedB) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, movedA, b) + advance(30) + touch(MotionEvent.ACTION_POINTER_UP, 1, movedA, b) + touch(MotionEvent.ACTION_UP, 0, movedA) + advance(600) + assertTrue(buttons().isEmpty()) + assertEquals(listOf("key 106 true", "key 106 false"), events.filter { it.startsWith("key") }) + } + + @Test fun cancellingAnActiveLongPressReleasesItsButton() { + gestures.configure(TouchGestureConfig(longPressEnabled = true, longPressAction = "right_click")) + touch(MotionEvent.ACTION_DOWN, 0, a) + advance(350) + assertEquals(listOf("button 273 true"), buttons()) + gestures.cancel(); advance(2000) + assertEquals(listOf("button 273 true", "button 273 false"), buttons()) + } + + @Test fun changingConfigurationReleasesAnActiveHold() { + gestures.configure(TouchGestureConfig(longPressEnabled = true, longPressAction = "left_click")) + touch(MotionEvent.ACTION_DOWN, 0, a) + advance(350) + gestures.configure(TouchGestureConfig()) + assertEquals(listOf("button 272 true", "button 272 false"), buttons()) + } + + @Test fun relativeDragEmitsDeltasInsteadOfAbsoluteMotion() { + gestures.configure(TouchGestureConfig(mouseDragMovementMode = "relative")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f)) + events.clear() + touch(MotionEvent.ACTION_MOVE, 0, 7 to (490f to 300f)) + assertEquals(listOf("delta true"), events) + } + + @Test fun directSelectionBoxTracksEveryMoveBackThroughItsStartingPoint() { + checkDirectDragThroughOrigin("left_click_drag", 272) + } + + @Test fun directRightDragAlsoTracksEveryMoveBackThroughItsStartingPoint() { + checkDirectDragThroughOrigin("right_click_drag", 273) + } + + private fun checkDirectDragThroughOrigin(action: String, code: Int) { + gestures.configure(TouchGestureConfig(dragAction = action)) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 330f)) + absoluteMoves.clear() + val path = listOf(430f to 315f, 410f to 305f, 400f to 300f, 390f to 295f, 370f to 285f, 320f to 270f) + path.forEach { touch(MotionEvent.ACTION_MOVE, 0, 7 to it) } + assertEquals(path, absoluteMoves) + assertEquals(listOf("button $code true"), buttons()) + touch(MotionEvent.ACTION_UP, 0, 7 to path.last()) + advance(100) + assertEquals(listOf("button $code true", "button $code false"), buttons()) + } + + @Test fun relativeDragReportsSmallMovementsWhileCrossingItsStartingPoint() { + gestures.configure(TouchGestureConfig(mouseDragMovementMode = "relative")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f)) + relativeMoves.clear() + listOf(430f, 410f, 400f, 390f, 370f, 320f).forEach { + touch(MotionEvent.ACTION_MOVE, 0, 7 to (it to 300f)) + } + assertEquals(listOf(-50f, -20f, -10f, -10f, -20f, -50f), relativeMoves.map { it.first }) + assertTrue(relativeMoves.all { it.second == 0f }) + gestures.cancel() + assertEquals(listOf("button 272 true", "button 272 false"), buttons()) + } + + @Test fun longPressCanSendAClickInsteadOfHolding() { + gestures.configure(TouchGestureConfig(longPressEnabled = true, longPressMouseBehavior = "click")) + touch(MotionEvent.ACTION_DOWN, 0, a) + advance(400) + assertEquals(listOf("button 273 true", "button 273 false"), buttons()) + touch(MotionEvent.ACTION_UP, 0, a); advance(80) + assertEquals(2, buttons().size) + } + + @Test fun aThirdFingerReleasesTheTwoFingerHold() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(350) + assertEquals(listOf("button 274 true"), buttons()) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + assertEquals(listOf("button 274 true", "button 274 false"), buttons()) + gestures.cancel() + } + + @Test fun threeFingerTapOpensKeyboardOnceAndDoesNotClick() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(80) + touch(MotionEvent.ACTION_POINTER_UP, 0, a, b, c) + touch(MotionEvent.ACTION_POINTER_UP, 0, b, c) + touch(MotionEvent.ACTION_UP, 0, c) + advance(400) + assertEquals(1, events.count { it == "keyboard" }) + assertTrue(buttons().isEmpty()) + } + + @Test fun fourToThreeFingersDoesNotReleaseTheThreeFingerHold() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(350) + assertTrue(events.contains("key 1 true")) + touch(MotionEvent.ACTION_POINTER_DOWN, 3, a, b, c, d) + touch(MotionEvent.ACTION_POINTER_UP, 3, a, b, c, d) + assertFalse(events.contains("key 1 false")) + gestures.cancel() + assertTrue(events.contains("key 1 false")) + } + + @Test fun cancelStopsPendingHoldAndTapCallbacks() { + gestures.configure(TouchGestureConfig(longPressEnabled = true)) + touch(MotionEvent.ACTION_DOWN, 0, a) + gestures.cancel() + events.clear(); advance(2000) + assertTrue(events.isEmpty()) + } + + @Test fun twoFingerPanHoldsTheArrowAndReleasesItOnLift() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f), 12 to (680f to 300f)) + assertTrue(events.contains("key 106 true")) + assertFalse(events.any { it.startsWith("wheel") }) + touch(MotionEvent.ACTION_POINTER_UP, 1, 7 to (480f to 300f), 12 to (680f to 300f)) + assertTrue(events.contains("key 106 false")) + touch(MotionEvent.ACTION_UP, 0, 7 to (480f to 300f)) + advance(400) + assertTrue(buttons().isEmpty()) + } + + @Test fun pinchZoomDoesNotAlsoStartAPan() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (320f to 300f), 12 to (680f to 300f)) + assertTrue(events.contains("wheel -1")) + assertFalse(events.any { it.startsWith("key") }) + gestures.cancel(); advance(400) + assertTrue(buttons().isEmpty()) + } + + @Test fun threeFingerRightDragReleasesOnCancel() { + gestures.configure(TouchGestureConfig(threeFingerDragEnabled = true, threeFingerDragAction = "right_click_drag")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(100) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f), 12 to (680f to 300f), 19 to (880f to 300f)) + assertEquals(listOf("button 273 true"), buttons()) + gestures.cancel() + assertEquals(listOf("button 273 true", "button 273 false"), buttons()) + } + + @Test fun slowMiddlePanRetainsOnePixelMovesAfterRecognition() { + startTwoFingerPan("middle_mouse_pan") + relativeMoves.clear() + for (offset in 81..90) { + advance(8) + moveTwoFingerPan(offset.toFloat()) + } + assertEquals(List(10) { 1f to 0f }, relativeMoves) + gestures.cancel() + assertEquals("button 274 false", buttons().last()) + } + + @Test fun slowInvertedMiddlePanRetainsInvertedOnePixelMoves() { + startTwoFingerPan("inverted_middle_mouse_pan") + relativeMoves.clear() + for (offset in 81..90) moveTwoFingerPan(offset.toFloat()) + assertEquals(List(10) { -1f }, relativeMoves.map { it.first }) + assertTrue(relativeMoves.all { it.second == 0f }) + gestures.cancel() + } + + @Test fun slowThreeFingerMiddlePanRetainsSmallMoves() { + gestures.configure(TouchGestureConfig(threeFingerDragEnabled = true, threeFingerDragAction = "middle_mouse_pan")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(100) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f), 12 to (680f to 300f), 19 to (880f to 300f)) + relativeMoves.clear() + for (offset in 81..85) { + touch(MotionEvent.ACTION_MOVE, 0, 7 to (400f + offset to 300f), 12 to (600f + offset to 300f), 19 to (800f + offset to 300f)) + } + assertEquals(List(5) { 1f to 0f }, relativeMoves) + gestures.cancel() + } + + @Test fun slowKeyboardPanCanStartUsingOnlySmallMovementEvents() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + for (offset in 1..45) { advance(8); moveTwoFingerPan(offset.toFloat()) } + assertTrue(events.contains("key 106 true")) + gestures.cancel() + assertEquals("key 106 false", events.filter { it.startsWith("key") }.last()) + } + + @Test fun slowKeyboardPanReversalReleasesTheOldDirection() { + startTwoFingerPan("arrow_keys") + events.clear() + for (offset in 79 downTo 75) moveTwoFingerPan(offset.toFloat()) + assertEquals(listOf("key 106 false", "key 105 true"), events.filter { it.startsWith("key") }) + gestures.cancel() + assertEquals("key 105 false", events.filter { it.startsWith("key") }.last()) + } + + @Test fun slowDiagonalKeyboardPanCanHoldBothDirections() { + startTwoFingerPan("arrow_keys") + events.clear() + for (i in 1..4) { + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f + i to 300f + i), 12 to (680f + i to 300f + i)) + } + assertEquals(listOf("key 108 true"), events.filter { it.startsWith("key") }) + gestures.cancel() + assertTrue(events.contains("key 106 false")) + assertTrue(events.contains("key 108 false")) + } + + @Test fun keyboardPanRemainderDoesNotSurviveCancellation() { + startTwoFingerPan("arrow_keys") + for (offset in 79 downTo 76) moveTwoFingerPan(offset.toFloat()) + gestures.cancel() + startTwoFingerPan("arrow_keys") + events.clear() + moveTwoFingerPan(79f) + assertTrue(events.none { it.startsWith("key") }) + gestures.cancel() + } + + @Test fun slowPinchAccumulatesFractionalMovementIntoAWheelStep() { + startPinch() + events.clear() + for (i in 1..20) { advance(8); movePinch(i * .25f) } + assertEquals(listOf("wheel -1"), events.filter { it.startsWith("wheel") }) + gestures.cancel() + } + + @Test fun slowPinchCanStartUsingOnlySmallMovementEvents() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + for (offset in 1..25) { + advance(8) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (400f - offset to 300f), 12 to (600f + offset to 300f)) + } + assertEquals(listOf("wheel -1"), events.filter { it.startsWith("wheel") }) + assertTrue(events.none { it.startsWith("key") }) + gestures.cancel() + } + + @Test fun pinchReversalDoesNotConsumeOldDirectionRemainder() { + startPinch() + events.clear() + movePinch(4.5f) // Nine pixels toward zooming in, short of a step. + assertTrue(events.none { it.startsWith("wheel") }) + for (i in 1..10) movePinch(4.5f - i * .5f) + assertEquals(listOf("wheel 1"), events.filter { it.startsWith("wheel") }) + gestures.cancel() + } + + @Test fun pinchRemainderDoesNotLeakIntoTheNextGesture() { + startPinch() + movePinch(4.5f) + gestures.cancel() + startPinch() + events.clear() + movePinch(.5f) + assertTrue(events.none { it.startsWith("wheel") }) + gestures.cancel() + } + + @Test fun aLargePinchStillEmitsOneStepWithoutQueuedZoomAfterRelease() { + startPinch() + events.clear() + movePinch(40f) + assertEquals(listOf("wheel -1"), events.filter { it.startsWith("wheel") }) + gestures.cancel() + events.clear(); advance(1000) + assertTrue(events.isEmpty()) + } + + @Test fun slowPinchKeyboardBindingsReleaseTheirKeys() { + startPinch("plus_minus") + events.clear(); timedKeys.clear() + for (i in 1..20) { advance(8); movePinch(i * .25f) } + assertEquals(listOf("key 13 true"), events.filter { it.startsWith("key") }) + advance(50) + assertEquals(listOf("key 13 true", "key 13 false"), events.filter { it.startsWith("key") }) + gestures.cancel() + events.clear(); advance(1000) + assertTrue(events.isEmpty()) + } + + @Test fun middlePanDoesNotJumpBackToTheTouchAnchorAfterTheClientRecenters() { + checkRecenteredPan("middle_mouse_pan", 1040f) + } + + @Test fun invertedMiddlePanUsesOnlyInvertedFingerDeltasAfterRecentering() { + checkRecenteredPan("inverted_middle_mouse_pan", 880f) + } + + private fun checkRecenteredPan(action: String, expected: Float) { + var cachedX = 0f + var clientX = 0f + var middleDown = false + gestures = TouchscreenGestures(ViewConfiguration.get(RuntimeEnvironment.getApplication()).scaledTouchSlop.toFloat(), object : TouchscreenGestures.Output { + override fun moveTo(x: Float, y: Float) { cachedX = x; clientX = x } + override fun prepareRelativePan() { cachedX = 960f; clientX = 960f } + override fun moveBy(dx: Float, dy: Float, relative: Boolean) { + // Before pointer lock, the compositor delivers an absolute + // position even when we inject a relative delta. The game + // only requests lock after seeing this first pan movement. + cachedX += dx + clientX = cachedX + } + override fun button(code: Int, down: Boolean) { + if (code == 274) { + middleDown = down + if (down) clientX = 960f // The client warps to the middle when pan starts. + } + } + override fun key(code: Int, down: Boolean) {} + override fun wheel(steps: Int) {} + override fun showKeyboard() {} + }) + gestures.configure(TouchGestureConfig(twoFingerDragAction = action)) + touch(MotionEvent.ACTION_DOWN, 0, 7 to (1200f to 300f)) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, 7 to (1200f to 300f), 12 to (1400f to 300f)) + advance(150) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (1280f to 300f), 12 to (1480f to 300f)) + assertTrue(middleDown) + assertEquals(expected, clientX, 0.01f) + touch(MotionEvent.ACTION_POINTER_UP, 1, 7 to (1280f to 300f), 12 to (1480f to 300f)) + assertFalse(middleDown) + } + + @Test fun middlePanPreparesItsOriginBeforePressAndOnlyOncePerDrag() { + gestures.configure(TouchGestureConfig(twoFingerDragAction = "middle_mouse_pan")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + events.clear() + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f), 12 to (680f to 300f)) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (490f to 300f), 12 to (690f to 300f)) + assertEquals(listOf("prepare pan", "button 274 true", "delta true", "delta true"), events) + gestures.cancel() + assertEquals("button 274 false", events.last()) + } + + @Test fun leftClickDragDoesNotPrepareARelativePanOrigin() { + gestures.configure(TouchGestureConfig(twoFingerDragAction = "left_click_drag")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + events.clear() + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f), 12 to (680f to 300f)) + assertFalse(events.contains("prepare pan")) + assertTrue(buttons().contains("button 272 true")) + } + + @Test fun keyboardActionsUseEvdevCodesAndReleaseOnCancel() { + gestures.configure(TouchGestureConfig(longPressEnabled = true, longPressAction = "key_CTRL_R")) + touch(MotionEvent.ACTION_DOWN, 0, a); advance(350) + assertTrue(events.contains("key 97 true")) + gestures.cancel() + assertTrue(events.contains("key 97 false")) + assertEquals(96, GestureKeys.code("KP_ENTER")) + assertEquals(99, GestureKeys.code("PRTSCN")) + } + + + @Test fun replacingAnOriginalFingerDoesNotInjectThreeFingerPanMotion() { + gestures.configure(TouchGestureConfig(threeFingerDragEnabled = true, threeFingerDragAction = "middle_mouse_pan")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(100) + val movedA = 7 to (480f to 300f) + val movedB = 12 to (680f to 300f) + val movedC = 19 to (880f to 300f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB, movedC) + touch(MotionEvent.ACTION_POINTER_DOWN, 3, movedA, movedB, movedC, d) + relativeMoves.clear() + touch(MotionEvent.ACTION_POINTER_UP, 0, movedA, movedB, movedC, d) + touch(MotionEvent.ACTION_MOVE, 0, movedB, movedC, d) + assertTrue("No finger moved; observed deltas: $relativeMoves", relativeMoves.isEmpty()) + touch(MotionEvent.ACTION_MOVE, 0, 12 to (690f to 300f), 19 to (890f to 300f), 24 to (1010f to 300f)) + assertEquals(listOf(10f to 0f), relativeMoves) + assertEquals(1, events.count { it == "prepare pan" }) + gestures.cancel() + } + + @Test fun twoFingerDirectDragStartsAtItsOwnCentroid() { + gestures.configure(TouchGestureConfig(twoFingerDragAction = "left_click_drag")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f), 12 to (680f to 300f)) + assertEquals(500f to 300f, leftClicks.single().position) + gestures.cancel() + } + + @Test fun threeFingerDirectDragStartsAtItsOwnCentroid() { + gestures.configure(TouchGestureConfig(threeFingerDragEnabled = true, threeFingerDragAction = "right_click_drag")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(100) + touch(MotionEvent.ACTION_MOVE, 0, 7 to (480f to 300f), 12 to (680f to 300f), 19 to (880f to 300f)) + assertEquals(600f to 300f, rightClicks.single().position) + gestures.cancel() + } + + @Test fun batchedTwoFingerExcursionCannotBecomeATap() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(20) + batchedReturn(7 to (480f to 300f), 12 to (680f to 300f)) + touch(MotionEvent.ACTION_POINTER_UP, 1, a, b) + touch(MotionEvent.ACTION_UP, 0, a) + advance(1000) + assertTrue("An out-and-back swipe generated: ${buttons()}", buttons().isEmpty()) + } + + @Test fun batchedSingleFingerExcursionCannotBecomeATapWithDragDisabled() { + gestures.configure(TouchGestureConfig(dragEnabled = false)) + touch(MotionEvent.ACTION_DOWN, 0, a) + advance(20) + batchedReturn(7 to (480f to 300f)) + touch(MotionEvent.ACTION_UP, 0, a) + advance(1000) + assertTrue("An out-and-back swipe generated: ${buttons()}", buttons().isEmpty()) + } + + @Test fun replacingAFingerDuringDirectDragPreservesPositionAndContinuesMoving() { + gestures.configure(TouchGestureConfig(threeFingerDragEnabled = true, threeFingerDragAction = "right_click_drag")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(100) + val movedA = 7 to (480f to 300f) + val movedB = 12 to (680f to 300f) + val movedC = 19 to (880f to 300f) + touch(MotionEvent.ACTION_MOVE, 0, movedA, movedB, movedC) + val before = cursor + touch(MotionEvent.ACTION_POINTER_DOWN, 3, movedA, movedB, movedC, d) + touch(MotionEvent.ACTION_POINTER_UP, 0, movedA, movedB, movedC, d) + touch(MotionEvent.ACTION_MOVE, 0, movedB, movedC, d) + assertEquals(before, cursor) + touch(MotionEvent.ACTION_MOVE, 0, 12 to (692f to 300f), 19 to (892f to 300f), 24 to (1012f to 300f)) + assertEquals(before.first + 12f to before.second, cursor) + gestures.cancel() + assertEquals(listOf("button 273 true", "button 273 false"), buttons()) + } + + @Test fun batchedPinchExcursionCancelsTapEvenWhenEachFingerStaysInsidePanTolerance() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(20) + batchedReturn(7 to (375f to 300f), 12 to (625f to 300f)) + advance(350) + touch(MotionEvent.ACTION_POINTER_UP, 1, a, b) + touch(MotionEvent.ACTION_UP, 0, a) + advance(100) + assertTrue(events.none { it.startsWith("button") || it.startsWith("key") || it == "keyboard" }) + } + + @Test fun batchedSingleFingerExcursionCancelsPendingLongPress() { + gestures.configure(TouchGestureConfig(dragEnabled = false, longPressEnabled = true, longPressAction = "key_E")) + touch(MotionEvent.ACTION_DOWN, 0, a) + batchedReturn(7 to (480f to 300f)) + advance(350) + assertTrue(timedKeys.isEmpty()) + gestures.cancel() + } + + @Test fun batchedJitterPreservesTwoFingerHold() { + gestures.configure(TouchGestureConfig(twoFingerHoldAction = "key_E")) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + batchedReturn(7 to (403f to 302f), 12 to (603f to 302f)) + advance(350) + assertTrue(events.contains("key 18 true")) + gestures.cancel() + assertEquals("key 18 false", events.last()) + } + + @Test fun batchedThreeFingerExcursionCannotBecomeATapOrHold() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + batchedReturn(7 to (480f to 300f), 12 to (680f to 300f), 19 to (880f to 300f)) + advance(350) + touch(MotionEvent.ACTION_POINTER_UP, 2, a, b, c) + touch(MotionEvent.ACTION_POINTER_UP, 1, a, b) + touch(MotionEvent.ACTION_UP, 0, a) + advance(100) + assertTrue(events.none { it.startsWith("button") || it.startsWith("key") || it == "keyboard" }) + } + + private fun batchedReturn(vararg excursion: Pair>) { + val originals = listOf(a, b, c).take(excursion.size) + val properties = excursion.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray() + fun coords(points: List>>) = points.map { (_, pos) -> MotionEvent.PointerCoords().apply { x = pos.first; y = pos.second; pressure = 1f; size = 1f } }.toTypedArray() + val event = MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_MOVE, excursion.size, + properties, coords(excursion.toList()), 0, 0, 1f, 1f, 0, 0, 0, 0) + advance(10) + event.addBatch(SystemClock.uptimeMillis(), coords(originals), 0) + assertEquals(1, event.historySize) + gestures.onTouch(event) + event.recycle() + } + + private fun buttons() = events.filter { it.startsWith("button") } + private fun startTwoFingerPan(action: String) { + gestures.configure(TouchGestureConfig(twoFingerDragAction = action)) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + moveTwoFingerPan(80f) + advance(110) + } + private fun moveTwoFingerPan(offset: Float) { + touch(MotionEvent.ACTION_MOVE, 0, 7 to (400f + offset to 300f), 12 to (600f + offset to 300f)) + } + private fun startPinch(action: String = "scroll_wheel") { + gestures.configure(TouchGestureConfig(pinchAction = action)) + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(150) + movePinch(0f) + advance(110) + } + private fun movePinch(offset: Float) { + touch(MotionEvent.ACTION_MOVE, 0, 7 to (370f - offset to 300f), 12 to (630f + offset to 300f)) + } + private fun twoFingerTap() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + advance(30) + touch(MotionEvent.ACTION_POINTER_UP, 1, a, b) + touch(MotionEvent.ACTION_UP, 0, a) + } + private fun threeFingerTap() { + touch(MotionEvent.ACTION_DOWN, 0, a) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, a, b) + touch(MotionEvent.ACTION_POINTER_DOWN, 2, a, b, c) + advance(30) + touch(MotionEvent.ACTION_POINTER_UP, 2, a, b, c) + touch(MotionEvent.ACTION_POINTER_UP, 1, a, b) + touch(MotionEvent.ACTION_UP, 0, a) + } + private fun tap(point: Pair> = a) { + touch(MotionEvent.ACTION_DOWN, 0, point) + advance(30) + touch(MotionEvent.ACTION_UP, 0, point) + } + private fun advance(ms: Long) = shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(ms)) + private fun touch(action: Int, index: Int, vararg points: Pair>) { + if (action == MotionEvent.ACTION_DOWN) downTime = SystemClock.uptimeMillis() + val properties = points.map { (id, _) -> MotionEvent.PointerProperties().apply { this.id = id; toolType = MotionEvent.TOOL_TYPE_FINGER } }.toTypedArray() + val coords = points.map { (_, pos) -> MotionEvent.PointerCoords().apply { x = pos.first; y = pos.second; pressure = 1f; size = 1f } }.toTypedArray() + MotionEvent.obtain(downTime, SystemClock.uptimeMillis(), action or (index shl MotionEvent.ACTION_POINTER_INDEX_SHIFT), points.size, + properties, coords, 0, 0, 1f, 1f, 0, 0, 0, 0).also { event -> + gestures.onTouch(event); event.recycle() + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GestureActionsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GestureActionsTest.kt new file mode 100644 index 0000000000..4111aec790 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/GestureActionsTest.kt @@ -0,0 +1,37 @@ +package com.droiddeck.launcher.ui + +import org.junit.Assert.* +import org.junit.Test + +class GestureActionsTest { + @Test fun categoryActionsAreAlphabeticalIncludingFilteredResults() { + val actions = listOf("Z", "C", "A", "B").map { GestureAction("key_$it", it, GestureActionGroup.LETTERS) } + + listOf("Right click", "Middle click", "Left click").map { GestureAction(it, it, GestureActionGroup.MOUSE) } + assertEquals(listOf("A", "B", "C", "Z"), filterGestureActions(actions, "", GestureActionGroup.LETTERS).map { it.title }) + assertEquals(listOf("Left click", "Middle click", "Right click"), filterGestureActions(actions, "click", null).map { it.title }) + } + + @Test fun numberedFunctionKeysStayInNumericOrder() { + val actions = listOf(12, 2, 10, 1).map { GestureAction("key_F$it", "F$it", GestureActionGroup.FUNCTION) } + assertEquals(listOf("F1", "F2", "F10", "F12"), filterGestureActions(actions, "", null).map { it.title }) + } + + @Test fun actionGroupsKeepKeysAndMouseBindingsInTheirOwnCategories() { + assertEquals(GestureActionGroup.MOUSE, gestureActionGroup("middle_mouse_pan")) + assertEquals(GestureActionGroup.LETTERS, gestureActionGroup("key_F")) + assertEquals(GestureActionGroup.FUNCTION, gestureActionGroup("key_F12")) + assertEquals(GestureActionGroup.NUMPAD, gestureActionGroup("key_KP_ENTER")) + assertEquals(GestureActionGroup.MODIFIERS, gestureActionGroup("key_CTRL_R")) + } + + @Test fun searchCombinesWordsAndCategoryWithoutChangingTheSelection() { + val actions = listOf( + GestureAction("key_ENTER", "Enter", GestureActionGroup.NAVIGATION), + GestureAction("key_KP_ENTER", "Numpad Enter", GestureActionGroup.NUMPAD), + GestureAction("key_KP_1", "Numpad 1", GestureActionGroup.NUMPAD), + ) + assertEquals(listOf(actions[1]), filterGestureActions(actions, " ENTER numpad ", null)) + assertEquals(listOf(actions[1]), filterGestureActions(actions, "enter", GestureActionGroup.NUMPAD)) + assertTrue(filterGestureActions(actions, "not a key", null).isEmpty()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/GestureLocalizationTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/GestureLocalizationTest.kt new file mode 100644 index 0000000000..e70caf7ddf --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/GestureLocalizationTest.kt @@ -0,0 +1,90 @@ +package com.droiddeck.launcher.ui + +import android.app.Application +import android.view.View +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.Text +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.test.* +import androidx.compose.ui.unit.Density +import com.droiddeck.launcher.R +import com.droiddeck.launcher.input.GesturePrefs +import com.droiddeck.launcher.input.TouchGestureConfig +import com.droiddeck.launcher.input.TouchscreenGestures.Gesture +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.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = Application::class, qualifiers = "w400dp-h850dp-port") +class GestureLocalizationTest { + @get:Rule val compose = createRobolectricComposeRule() + private val context get() = RuntimeEnvironment.getApplication() + + @Before fun clearPrefs() { + context.getSharedPreferences("touch_gestures", 0).edit().clear().commit() + } + + @Test + @Config(qualifiers = "fr-rFR-w400dp-h850dp-port") + fun pageKeysAndModifierNamesUseLocalizedResources() { + compose.setContent { + DroidDeckTheme { + Column { + Text(gestureActionTitle("page_up_down")) + Text(gestureActionTitle("key_SHIFT_L")) + } + } + } + compose.onNodeWithText("Page précédente / Page suivante").assertIsDisplayed() + compose.onNodeWithText("Maj gauche").assertIsDisplayed() + } + + @Test + @Config(qualifiers = "de-rDE-w400dp-h850dp-port") + fun longTranslationsKeepDefaultRestorationAndSaveUsable() { + GesturePrefs.save(context, "123", TouchGestureConfig(tapAction = "key_E")) + compose.setContent { + val density = LocalDensity.current + CompositionLocalProvider(LocalDensity provides Density(density.density, fontScale = 1.5f)) { + DroidDeckTheme { TouchGestureDialog("123", {}, {}) } + } + } + val restore = compose.onNodeWithTag("gesture-inherit") + restore.assertIsDisplayed() + val scope = compose.onNodeWithTag("gesture-scope-game").fetchSemanticsNode().boundsInRoot + assertTrue("The restore action must have room for its translated label", restore.fetchSemanticsNode().boundsInRoot.width > scope.width) + restore.performClick() + compose.onNodeWithTag("gesture-save").assertIsDisplayed().performClick() + compose.runOnIdle { assertFalse(GesturePrefs.hasOverride(context, "123")) } + } + + @Test + @Config(qualifiers = "ar-rEG-w400dp-h850dp-port") + fun arabicPickerSearchPreservesBindingsAndMirrorsFooter() { + assertEquals(View.LAYOUT_DIRECTION_RTL, context.resources.configuration.layoutDirection) + compose.setContent { DroidDeckTheme { TouchGestureDialog(null, {}, {}) } } + compose.onNodeWithText("إعدادات إيماءات اللمس").assertIsDisplayed() + val save = compose.onNodeWithTag("gesture-save").fetchSemanticsNode().boundsInRoot + val cancel = compose.onNodeWithText(context.getString(R.string.gesture_cancel)).fetchSemanticsNode().boundsInRoot + assertTrue("Save $save and Cancel $cancel should follow the right-to-left layout", save.left < cancel.left) + compose.onNodeWithTag("gesture-choice-tap").performScrollTo().performClick() + compose.onNodeWithTag("gesture-action-search").performTextInput("هروب") + compose.onNodeWithTag("gesture-action-key_ESC").assertIsDisplayed().performClick() + compose.onNodeWithTag("gesture-save").performClick() + compose.runOnIdle { assertEquals("key_ESC", GesturePrefs.read(context).tapAction) } + } + + @Test + @Config(qualifiers = "ja-rJP-w400dp-h850dp-port") + fun recognizedGestureFeedbackUsesTheActiveLanguage() { + compose.setContent { DroidDeckTheme { GestureFeedback(Gesture.TWO_FINGER_HOLD) } } + compose.onNodeWithText("2本指で長押し").assertIsDisplayed() + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/TouchGestureDialogTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/TouchGestureDialogTest.kt new file mode 100644 index 0000000000..3189deba68 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/TouchGestureDialogTest.kt @@ -0,0 +1,112 @@ +package com.droiddeck.launcher.ui + +import android.app.Application +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.snapshots.Snapshot +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density +import androidx.compose.ui.test.* +import com.droiddeck.launcher.input.GesturePrefs +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.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], application = Application::class, qualifiers = "w960dp-h640dp-land") +class TouchGestureDialogTest { + @get:Rule val compose = createRobolectricComposeRule() + private val context get() = RuntimeEnvironment.getApplication() + + @Before fun clearPrefs() { + context.getSharedPreferences("touch_gestures", 0).edit().clear().commit() + } + + @Test fun searchSelectAndSaveAKeyboardAction() { + compose.setContent { DroidDeckTheme { TouchGestureDialog(null, {}, {}) } } + compose.onNodeWithTag("gesture-choice-tap").performScrollTo().performClick() + compose.onNodeWithTag("gesture-action-left_click").assertIsSelected() + compose.onNodeWithTag("gesture-action-search").performTextInput("numpad enter") + compose.onNodeWithTag("gesture-action-key_KP_ENTER").assertIsDisplayed().performClick() + compose.onNodeWithTag("gesture-save").performClick() + compose.runOnIdle { assertEquals("key_KP_ENTER", GesturePrefs.read(context).tapAction) } + } + + @Test fun switchingTabsKeepsEditsAndLetsTwoFingerPanBeChanged() { + compose.setContent { DroidDeckTheme { TouchGestureDialog(null, {}, {}) } } + compose.onNodeWithTag("gesture-tab-1").performClick() + compose.onNodeWithTag("gesture-choice-two-drag").performScrollTo().performClick() + compose.onNodeWithTag("gesture-action-search").performTextInput("middle mouse pan") + compose.onNodeWithTag("gesture-action-middle_mouse_pan").performClick() + compose.onNodeWithTag("gesture-tab-3").performClick() + compose.onNodeWithTag("gesture-tab-1").performClick() + compose.onNodeWithText("Middle mouse pan").performScrollTo().assertIsDisplayed() + compose.onNodeWithTag("gesture-save").performClick() + compose.runOnIdle { assertEquals("middle_mouse_pan", GesturePrefs.read(context).twoFingerDragAction) } + } + + @Test fun closingWithoutSavingDiscardsTheDraft() { + val open = mutableStateOf(true) + compose.setContent { DroidDeckTheme { if (open.value) TouchGestureDialog(null, { open.value = false }, {}) } } + chooseTap("Escape", "key_ESC") + compose.onNodeWithContentDescription("Close").performClick() + compose.runOnIdle { assertEquals("left_click", GesturePrefs.read(context).tapAction) } + } + + @Test fun defaultsAndGameDraftsSurviveScopeChangesAndSaveTogether() { + compose.setContent { DroidDeckTheme { TouchGestureDialog("123", {}, {}) } } + chooseTap("numpad enter", "key_KP_ENTER") + compose.onNodeWithTag("gesture-scope-default").performClick() + chooseTap("Escape", "key_ESC") + compose.onNodeWithTag("gesture-scope-game").performClick() + compose.onNodeWithTag("gesture-choice-tap").performScrollTo() + compose.onNodeWithText("Numpad Enter").assertIsDisplayed() + compose.onNodeWithTag("gesture-save").performClick() + compose.runOnIdle { + assertEquals("key_ESC", GesturePrefs.read(context).tapAction) + assertEquals("key_KP_ENTER", GesturePrefs.read(context, "123").tapAction) + } + } + + @Test fun aFocusChangeCannotRetargetAnOpenGameEditor() { + val game = mutableStateOf("123") + compose.setContent { DroidDeckTheme { TouchGestureDialog(game.value, {}, {}) } } + chooseTap("Escape", "key_ESC") + compose.runOnIdle { + game.value = "456" + Snapshot.sendApplyNotifications() + } + compose.onNodeWithTag("gesture-save").performClick() + compose.runOnIdle { + assertEquals("key_ESC", GesturePrefs.read(context, "123").tapAction) + assertFalse(GesturePrefs.hasOverride(context, "456")) + } + } + + @Test + @Config(qualifiers = "w400dp-h850dp-port") + fun aNarrowWindowWithLargeTextKeepsNavigationAndSaveReachable() { + compose.setContent { + val density = LocalDensity.current + CompositionLocalProvider(LocalDensity provides Density(density.density, fontScale = 1.5f)) { + DroidDeckTheme { TouchGestureDialog("123", {}, {}) } + } + } + compose.onNodeWithContentDescription("Close").assertIsDisplayed() + compose.onNodeWithTag("gesture-save").assertIsDisplayed() + compose.onNodeWithTag("gesture-tab-3").performScrollTo().performClick() + compose.onNodeWithText("Mouse movement").performScrollTo().assertIsDisplayed() + compose.onNodeWithTag("gesture-save").assertIsDisplayed() + } + + private fun chooseTap(search: String, id: String) { + compose.onNodeWithTag("gesture-choice-tap").performScrollTo().performClick() + compose.onNodeWithTag("gesture-action-search").performTextInput(search) + compose.onNodeWithTag("gesture-action-$id").performClick() + } +} diff --git a/tools/tests/test_esync_packs.py b/tools/tests/test_esync_packs.py index e836eaad11..863a1003ba 100644 --- a/tools/tests/test_esync_packs.py +++ b/tools/tests/test_esync_packs.py @@ -1164,7 +1164,9 @@ class BundleTest(unittest.TestCase): bundle = steps["Bundle the droiddeck-esync packs"] self.assertNotIn("if", bundle) self.assertIn("tools/droiddeck-esync/release.env", bundle["run"]) - self.assertEqual(bundle["run"].count('-R "$SYNC_BUNDLE_REPO"'), 2) + self.assertIn('release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"', bundle["run"]) + self.assertIn('curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"', bundle["run"]) + self.assertIn('curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"', bundle["run"]) self.assertIn("sha256sum -c -", bundle["run"]) self.assertNotIn("revoked.txt", bundle["run"]) stage = next(step for step in apk["jobs"]["build"]["steps"] if "overlay/usr/local/bin/droiddeck-*" in step.get("run", ""))