From 8a27ea841c18f85b3bd8d2ba9025661e4acf0314 Mon Sep 17 00:00:00 2001 From: K11MCH1 <81425424+K11MCH1@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:38:03 +0900 Subject: [PATCH] Add RedMagic Air Triggers to the session's controller settings (#3737) * Add RedMagic Air Triggers to the session's controller settings Controller > Device settings gets a "Redmagic Air Triggers" panel on RedMagic phones whose Game Space exposes its trigger provider. The toggle switches the shoulder triggers to plain F7/F8 keys through Game Space's exported TgkDataProvider (no permission, no trigger panel or markers), and each trigger presses a button of the active touch layout: LT and RT by default, or any button picked in the dropdowns, saved per layout. The triggers go back to their earlier state when the toggle is off, the session pauses or ends, or the app is killed mid-session (the next session start closes what this app opened). A distribute state another app turned on is left alone. * Show Air Trigger presses on screen and light the triggers A trigger now presses its button through the on-screen controls when that button is shown, so it shows as pressed and shares a toggle button's state with touches. A hidden button still gets the trigger's own input source. Game Space lights the triggers only from its own trigger view, through ColorfulLightManager, which apps cannot call. DroidDeck sends the same requestColorfulLight to the ColorfulLightService binder: the shoulder scene while the triggers are on, and the press/release lights the user's RedMagic lighting settings ask for. * Set the trigger light effect so the Air Trigger LEDs turn on RedMagic's light service writes no trigger light until a shoulder effect has been set, and only Game Space's own trigger view sets one. After entering the shoulder light scene, send the effect the user picked in RedMagic's lighting settings (selection in lighting_shoulder_config_json). * Cancel forced Air Trigger releases and close the triggers while paused A trigger press that DroidDeck ends itself (focus loss, the triggers closing, another button chosen mid-press) now cancels the button like a cancelled touch, so a command button such as the keyboard does not run. A toggle latched while its button was hidden is handed to the visible button on the next trigger press instead of staying held underneath it. The triggers also close while the session is paused and reopen when it resumes. * Keep an Air Trigger hold when a touch on the same button is cancelled A cancelled touch stream cleared every press of the button, including the Air Trigger still holding it, so the button let go while the trigger stayed down. Touch cancels now end only the finger presses. Releasing all input still clears the button completely. * Release Air Trigger-only button holds when all input is released Releasing all input only cancelled buttons a finger owned. A button held only by an Air Trigger kept its pressed state after its output was released, so it stayed lit and a finger on it did nothing until the trigger was lifted. A full release now cancels every button. --- .../com/droiddeck/launcher/SessionActivity.kt | 65 +++++- .../launcher/input/RedMagicAirTriggers.kt | 203 ++++++++++++++++++ .../droiddeck/launcher/ui/InputSurfaceView.kt | 20 +- .../droiddeck/launcher/ui/SessionOverlay.kt | 72 ++++++- app/src/main/res/values-ar/strings.xml | 7 + app/src/main/res/values-b+es+419/strings.xml | 7 + app/src/main/res/values-bg/strings.xml | 7 + app/src/main/res/values-cs/strings.xml | 7 + app/src/main/res/values-da/strings.xml | 7 + app/src/main/res/values-de/strings.xml | 7 + app/src/main/res/values-el/strings.xml | 7 + app/src/main/res/values-es/strings.xml | 7 + app/src/main/res/values-fi/strings.xml | 7 + app/src/main/res/values-fr/strings.xml | 7 + app/src/main/res/values-hi/strings.xml | 7 + app/src/main/res/values-hu/strings.xml | 7 + app/src/main/res/values-in/strings.xml | 7 + app/src/main/res/values-it/strings.xml | 7 + app/src/main/res/values-ja/strings.xml | 7 + app/src/main/res/values-ko/strings.xml | 7 + app/src/main/res/values-ms/strings.xml | 7 + app/src/main/res/values-nb/strings.xml | 7 + app/src/main/res/values-nl/strings.xml | 7 + app/src/main/res/values-pl/strings.xml | 7 + app/src/main/res/values-pt-rPT/strings.xml | 7 + app/src/main/res/values-pt/strings.xml | 7 + app/src/main/res/values-ro/strings.xml | 7 + app/src/main/res/values-ru/strings.xml | 7 + app/src/main/res/values-sv/strings.xml | 7 + app/src/main/res/values-th/strings.xml | 7 + app/src/main/res/values-tr/strings.xml | 7 + app/src/main/res/values-uk/strings.xml | 7 + app/src/main/res/values-vi/strings.xml | 7 + app/src/main/res/values-zh-rCN/strings.xml | 7 + app/src/main/res/values-zh-rHK/strings.xml | 7 + app/src/main/res/values-zh-rTW/strings.xml | 7 + app/src/main/res/values/strings.xml | 7 + .../launcher/input/RedMagicAirTriggersTest.kt | 178 +++++++++++++++ .../launcher/ui/InputSurfaceTouchTest.kt | 53 +++++ 39 files changed, 806 insertions(+), 16 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 2fc1b15edc..cd6e8127e0 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -100,6 +100,11 @@ import com.droiddeck.launcher.input.SteamControllerBle import com.droiddeck.launcher.input.DirectTouchHold import com.droiddeck.launcher.input.GestureTouchStreamGate import com.droiddeck.launcher.input.PenRouter +import com.droiddeck.launcher.input.AirTrigger +import com.droiddeck.launcher.input.AirTriggerButtons +import com.droiddeck.launcher.input.AirTriggerInput +import com.droiddeck.launcher.input.AirTriggerPrefs +import com.droiddeck.launcher.input.RedMagicAirTriggers import com.droiddeck.launcher.input.PenStream import com.droiddeck.launcher.input.PointerGestures import com.droiddeck.launcher.input.PointerSpace @@ -241,6 +246,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private lateinit var sessionRoot: FrameLayout private var inputRouter: InputRouter? = null private var physicalInputBindings: com.droiddeck.launcher.input.PhysicalInputBindings? = null + private var airTriggerInput: AirTriggerInput? = null + private var airTriggersOpen = false + private var airTriggerMenu by mutableStateOf(null) private var inputSettingsOpen by mutableStateOf(false) @Volatile private var inputUsesLocalActions = false private var inputUsesPointer = false @@ -974,6 +982,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this)) padBridge = bridge inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it) } + if (RedMagicAirTriggers.supported(this)) { + airTriggerInput = AirTriggerInput(bridge, ::holdOnScreen, RedMagicAirTriggers::light) + RedMagicAirTriggers.restore(this) + } refreshInputProfile() bridge.setOnChordInput(backQamInput::onChordInput) SessionState.padBridge = bridge @@ -1383,6 +1395,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) { updateOnScreenControls() + refreshAirTriggers() padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended) if (!drawerOpen && backTapOpenedDrawer) { backTaps.cancel() @@ -1936,6 +1949,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde wowChat = wowChat.remembered, onWowChat = wowChat::choose, controller = controllerSettings, + airTriggers = airTriggerMenu, + onAirTriggers = { on -> AirTriggerPrefs.setEnabled(this@SessionActivity, on); refreshAirTriggers() }, + onAirTriggerButton = { trigger, id -> + AirTriggerPrefs.setButton(this@SessionActivity, primaryInputLayout?.id.orEmpty(), trigger, id) + refreshAirTriggers() + }, onControllerSize = { percent -> updateControllerPrefs { ControllerPrefs.setSize(this@SessionActivity, percent) } }, onControllerOpacity = { percent -> ControllerPrefs.setOnScreenOpacity(this@SessionActivity, percent) @@ -3680,6 +3699,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun onSessionEnded(status: Int) { ended = true + runOnUiThread { refreshAirTriggers() } ++steamVrRequestGeneration if (isInPictureInPictureMode) { runOnUiThread { finish() } @@ -3737,6 +3757,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun releasePads(keepBackTap: Boolean = false) { inputMotion.stop() physicalInputBindings?.release() + airTriggerInput?.release() com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this) backQamInput.cancel(keepTap = keepBackTap) padBridge?.releaseAll() @@ -3869,6 +3890,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde return dispatchSessionKeyEvent(normalized, orderedImeKey) } + private fun physicalInputAccepted() = resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && + !inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible + private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean { if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true when (event.keyCode) { @@ -3888,10 +3912,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event) + if (airTriggerInput?.onKey(event) { physicalInputAccepted() && !pipUi && !appTextFocus } == true) return true if (appTextFocus) return super.dispatchKeyEvent(event) if (!pipUi) { - if (physicalInputBindings?.onKey(event, resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && - !inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true + if (physicalInputBindings?.onKey(event, physicalInputAccepted()) == true) return true if (physicalShortcuts.onKey( event, enabled = resumed && SessionState.running && !SessionState.suspended && @@ -5116,6 +5140,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde || inputProfile.keys.any { it.action is InputAction.MouseButton } physicalInputBindings?.configure(inputProfile.keys) padBridge?.setInputProfile(inputProfile) + refreshAirTriggers() DeckControls.refresh() onScreenControls?.updateLayout(primaryInputLayout) bottomInputControls?.updateLayout(primaryInputLayout) @@ -5126,6 +5151,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenPresentation?.refreshControls() } + private fun refreshAirTriggers() { + val input = airTriggerInput ?: return + val layout = primaryInputLayout + val enabled = AirTriggerPrefs.enabled(this) + val chosen = AirTrigger.entries.associateWith { AirTriggerButtons.resolve(layout, it, AirTriggerPrefs.button(this, layout?.id.orEmpty(), it)) } + val active = enabled && resumed && !ended && !SessionState.suspended + input.configure(if (active) chosen else emptyMap()) + if (active != airTriggersOpen) { + airTriggersOpen = active + if (active) RedMagicAirTriggers.open(this) else RedMagicAirTriggers.restore(this) + } + airTriggerMenu = com.droiddeck.launcher.ui.AirTriggerMenu(enabled, chosen.mapValues { it.value.id }, + AirTriggerButtons.options(layout).map { it.id to it.name }) + } + private fun tapQam() { if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam() } @@ -5582,10 +5622,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var sessionTouchDown = false private var screenTapsClick = true - private fun onScreenLeftMouseButtonShown(): Boolean = listOfNotNull( + private fun inputSurfaces() = listOfNotNull( onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface, secondScreenPresentation?.controlsView, swappedInputSurface, - ).any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) } + ) + + private fun onScreenLeftMouseButtonShown(): Boolean = + inputSurfaces().any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) } + + private fun holdOnScreen(elementId: String, trigger: AirTrigger, held: Boolean, cancelled: Boolean): Boolean { + val surfaces = inputSurfaces().filter { it.inputRole == InputRole.PRIMARY } + if (held) return surfaces.any { it.isShown && it.hold(elementId, trigger.ordinal, true) } + surfaces.forEach { it.hold(elementId, trigger.ordinal, false, cancelled) } + return true + } override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) } @@ -6703,6 +6753,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (::scrollTouch.isInitialized) scrollTouch.cancel() if (::padMouse.isInitialized) padMouse.reset() resumed = false + refreshAirTriggers() boostGpuClock(false) updateKeyboardRoute() updatePointerCapture() @@ -7296,7 +7347,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!hasFocus) { cancelTouchGestures() releaseHeldGuestInput() + airTriggerInput?.release() } + // Game Space clears the distribute state when the launcher or Game Space itself comes to the front. + if (hasFocus && airTriggersOpen) RedMagicAirTriggers.open(this) if (hasFocus && !pipUi) { retryFieldKeyboard(true) goFullscreen() @@ -7384,6 +7438,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde inputMotion.stop() padBridge?.setInputEnabled(false) physicalInputBindings?.close() + airTriggerInput?.close() + airTriggerInput = null + if (airTriggersOpen) RedMagicAirTriggers.restore(this) padBridge?.stop() DeckControls.clearRouter(inputRouter) inputRouter = null diff --git a/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt b/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt new file mode 100644 index 0000000000..633564558c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt @@ -0,0 +1,203 @@ +package com.droiddeck.launcher.input + +import android.content.Context +import android.content.SharedPreferences +import android.net.Uri +import android.os.IBinder +import android.os.Parcel +import android.provider.Settings +import android.util.Log +import android.view.InputDevice +import android.view.KeyEvent +import java.util.EnumMap +import java.util.EnumSet +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit +import org.json.JSONObject + +enum class AirTrigger(val keyCode: Int, val control: InputControl, val pressLight: Int, val releaseLight: Int) { + LEFT(KeyEvent.KEYCODE_F7, InputControl.LT, 106, 107), RIGHT(KeyEvent.KEYCODE_F8, InputControl.RT, 108, 109); + + companion object { + // InputReader merges both trigger nodes into one device named after the left one. + private const val DEVICE_PREFIX = "nubia_tgk" + + fun isTriggerDevice(name: String?) = name?.startsWith(DEVICE_PREFIX) == true + fun of(keyCode: Int, deviceName: String?): AirTrigger? = + if (isTriggerDevice(deviceName)) entries.firstOrNull { it.keyCode == keyCode } else null + } +} + +object AirTriggerButtons { + fun options(layout: SavedInputLayout?): List { + val placed = layout?.let { (it.elements + it.rotated).distinctBy { element -> element.id } }.orEmpty() + .filter { it.kind == InputElementKind.BUTTON || it.kind == InputElementKind.TRIGGER } + return placed + AirTrigger.entries.filter { trigger -> placed.none { it.control == trigger.control } } + .map { InputSurfaceElement(it.control, 0f, 0f, 0f, 0f) } + } + + fun resolve(layout: SavedInputLayout?, trigger: AirTrigger, chosen: String?): InputSurfaceElement { + val options = options(layout) + return chosen?.let { id -> options.firstOrNull { it.id == id } } ?: options.first { it.control == trigger.control } + } +} + +object AirTriggerPrefs { + private const val FILE = "redmagic-air-triggers" + private const val ENABLED = "enabled" + internal const val OWNED = "distribute-owned" + + fun prefs(context: Context): SharedPreferences = context.getSharedPreferences(FILE, Context.MODE_PRIVATE) + fun enabled(context: Context) = prefs(context).getBoolean(ENABLED, false) + fun setEnabled(context: Context, on: Boolean) = prefs(context).edit().putBoolean(ENABLED, on).apply() + fun button(context: Context, layoutId: String, trigger: AirTrigger): String? = prefs(context).getString(key(layoutId, trigger), null) + fun setButton(context: Context, layoutId: String, trigger: AirTrigger, elementId: String) = + prefs(context).edit().putString(key(layoutId, trigger), elementId).apply() + + private fun key(layoutId: String, trigger: AirTrigger) = "${trigger.name.lowercase()}.$layoutId" +} + +/** Game Space's exported provider switches the triggers to plain F7/F8 keys without its panel, and needs no permission. */ +object RedMagicAirTriggers { + private const val TAG = "AirTriggers" + private const val AUTHORITY = "cn.nubia.tgk.data.TgkDataProvider" + private val URI = Uri.parse("content://$AUTHORITY") + private const val OPEN = "openTouchGameKeyDistribute" + private const val CLOSE = "closeTouchGameKeyDistribute" + private const val LIGHT_SERVICE = "ColorfulLightService" + private const val LIGHT_INTERFACE = "com.zte.hardware.IColorfulLightManager" + // IColorfulLightManager transaction codes; its ColorfulLightManager wrapper is a blocked hidden API. + private const val REQUEST_LIGHT = IBinder.FIRST_CALL_TRANSACTION + private const val SET_SHOULDER_EFFECT = IBinder.FIRST_CALL_TRANSACTION + 2 + private const val SHOULDER_LIGHT_ON = 110 + private const val SHOULDER_LIGHT_OFF = 111 + private const val SHOULDER_SETTINGS = "lighting_shoulder_config_json" + private val worker = ThreadPoolExecutor(0, 1, 10, TimeUnit.SECONDS, LinkedBlockingQueue()) { Thread(it, "air-triggers") } + private val lights: IBinder? by lazy { + runCatching { Class.forName("android.os.ServiceManager").getMethod("getService", String::class.java).invoke(null, LIGHT_SERVICE) as IBinder? } + .getOrNull()?.takeIf { runCatching { it.interfaceDescriptor }.getOrNull() == LIGHT_INTERFACE } + } + + @Suppress("DEPRECATION") + fun supported(context: Context) = context.packageManager.resolveContentProvider(AUTHORITY, 0) != null && + InputDevice.getDeviceIds().any { AirTrigger.isTriggerDevice(InputDevice.getDevice(it)?.name) } + + fun open(context: Context) { + val app = context.applicationContext + worker.execute { + val prefs = AirTriggerPrefs.prefs(app) + if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false) && Settings.Global.getInt(app.contentResolver, OPEN, 0) != 1) + prefs.edit().putBoolean(AirTriggerPrefs.OWNED, true).commit() + call(app, OPEN) + if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false)) return@execute + requestLight(SHOULDER_LIGHT_ON) + // The light service drops every trigger light until an effect is set, which Game Space only does from its own view. + shoulderEffect(Settings.Global.getString(app.contentResolver, SHOULDER_SETTINGS))?.let { effect -> + transact(SET_SHOULDER_EFFECT) { writeString(effect) } + } + } + } + + /** The trigger light effect the user picked in RedMagic's lighting settings, such as "02101000" for steady. */ + internal fun shoulderEffect(settings: String?): String? = settings + ?.let { runCatching { JSONObject(it).optString("selection") }.getOrNull() } + ?.takeIf { it.length == 8 } + + /** Closes only what this app opened, so a distribute another app turned on stays on. */ + fun restore(context: Context) { + val app = context.applicationContext + worker.execute { + val prefs = AirTriggerPrefs.prefs(app) + if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false)) return@execute + requestLight(SHOULDER_LIGHT_OFF) + if (call(app, CLOSE)) prefs.edit().remove(AirTriggerPrefs.OWNED).commit() + } + } + + fun light(code: Int) = worker.execute { requestLight(code) } + + private fun requestLight(action: Int) = transact(REQUEST_LIGHT) { writeInt(action) } + + private fun transact(code: Int, write: Parcel.() -> Unit) { + val binder = lights ?: return + val data = Parcel.obtain() + val reply = Parcel.obtain() + try { + data.writeInterfaceToken(LIGHT_INTERFACE) + data.write() + binder.transact(code, data, reply, 0) + reply.readException() + } catch (e: Exception) { + Log.w(TAG, "light call $code failed", e) + } finally { + data.recycle() + reply.recycle() + } + } + + private fun call(context: Context, method: String) = runCatching { context.contentResolver.call(URI, method, null, null) != null } + .onFailure { Log.w(TAG, "$method failed", it) }.getOrDefault(false) +} + +/** Presses the chosen button on screen when it is shown, so it animates and keeps one toggle state; otherwise uses a source of its own. */ +class AirTriggerInput( + private val pad: PadBridge, + private val onScreen: (elementId: String, trigger: AirTrigger, held: Boolean, cancelled: Boolean) -> Boolean = { _, _, _, _ -> false }, + private val light: (Int) -> Unit = {}, +) { + private val sources = EnumMap(AirTrigger::class.java) + private val held = EnumSet.noneOf(AirTrigger::class.java) + private val heldOnScreen = EnumMap(AirTrigger::class.java) + + fun configure(elements: Map) { + for (trigger in AirTrigger.entries) { + val element = elements[trigger] + if (sources[trigger]?.element == element) continue + heldOnScreen.remove(trigger)?.let { onScreen(it, trigger, false, true) } + sources.remove(trigger)?.close() + if (element != null) sources[trigger] = InputSurfaceSource(pad, InputRole.PRIMARY, element) + } + } + + fun onKey(event: KeyEvent, enabled: () -> Boolean): Boolean { + if (AirTrigger.entries.none { it.keyCode == event.keyCode }) return false + val trigger = AirTrigger.of(event.keyCode, event.device?.name) ?: return false + return onKey(trigger, event.action, event.repeatCount, event.action == KeyEvent.ACTION_DOWN && enabled()) + } + + fun onKey(trigger: AirTrigger, action: Int, repeatCount: Int, enabled: Boolean): Boolean { + val source = sources[trigger] + when (action) { + KeyEvent.ACTION_DOWN -> if (source != null && enabled && repeatCount == 0 && held.add(trigger)) press(trigger, source) + KeyEvent.ACTION_UP -> if (held.remove(trigger)) { unpress(trigger, cancelled = false); return true } + } + return source != null + } + + private fun press(trigger: AirTrigger, source: InputSurfaceSource) { + if (onScreen(source.element.id, trigger, true, false)) { + heldOnScreen[trigger] = source.element.id + // The router counts held keys, so a toggle latched while its button was hidden is released before the button takes over. + if (source.latched) source.release() + } else source.update(1f) + light(trigger.pressLight) + } + + private fun unpress(trigger: AirTrigger, cancelled: Boolean) { + heldOnScreen.remove(trigger)?.let { onScreen(it, trigger, false, cancelled) } + ?: sources[trigger]?.let { if (cancelled) it.cancel() else it.update(0f) } + light(trigger.releaseLight) + } + + fun release() { + held.toList().forEach { held.remove(it); unpress(it, cancelled = true) } + sources.values.forEach { it.release() } + } + + fun close() { + release() + sources.values.forEach { it.close() } + sources.clear() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index e0d0207ff3..95f22a5bea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -137,7 +137,7 @@ class InputSurfaceView( val views = owners.values.distinct() owners.clear() for (view in views) { - if (view is HoldButton) { view.cancel(); continue } + if (view is HoldButton) { view.cancelTouches(); continue } val cancel = MotionEvent.obtain(event.downTime, event.eventTime, MotionEvent.ACTION_CANCEL, 0f, 0f, 0) try { view.dispatchTouchEvent(cancel) } finally { cancel.recycle() } } @@ -176,10 +176,23 @@ class InputSurfaceView( val now = android.os.SystemClock.uptimeMillis() val cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0) try { cancelOwners(cancel) } finally { cancel.recycle() } + customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) (canvas.getChildAt(i) as? HoldButton)?.cancel() } forwardedPointers = 0 elementSources.forEach { it.release() } } + /** Presses a button as a finger would, for input from outside the screen; [holder] tells holds apart. */ + fun hold(elementId: String, holder: Int, held: Boolean, cancelled: Boolean = false): Boolean { + val canvas = customCanvas ?: return false + for (i in 0 until canvas.childCount) { + val button = canvas.getChildAt(i) as? HoldButton ?: continue + if ((button.tag as? InputSurfaceElement)?.id != elementId) continue + button.press(-1 - holder, held, cancelled) + return true + } + return false + } + override fun onVisibilityChanged(changedView: View, visibility: Int) { super.onVisibilityChanged(changedView, visibility) if (visibility != VISIBLE) releaseInputs() @@ -487,6 +500,11 @@ class InputSurfaceView( fun cancel() { pointers.clear(); set(false, cancelled = true); source?.release() } + fun cancelTouches() { + pointers.removeAll { it >= 0 } + if (pointers.isEmpty()) cancel() + } + override fun onDetachedFromWindow() { cancel(); super.onDetachedFromWindow() } private fun set(pressed: Boolean, cancelled: Boolean = false) { 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 e4637355ce..a24c1c253c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -116,6 +116,7 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.HomeApp +import com.droiddeck.launcher.input.AirTrigger import com.droiddeck.launcher.input.ControllerPrefs import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState @@ -238,6 +239,8 @@ private class DrawerFocus { fun forget(page: SessionDrawerPage) { last.remove(page) } } +data class AirTriggerMenu(val enabled: Boolean, val selected: Map, val buttons: List>) + class DrawerActions( val steam: Boolean, val desktop: Boolean, @@ -343,6 +346,9 @@ class DrawerActions( val onControllerSize: (Int) -> Unit = {}, val onControllerOpacity: (Int) -> Unit = {}, val onRumble: (Boolean) -> Unit = {}, + val airTriggers: AirTriggerMenu? = null, + val onAirTriggers: (Boolean) -> Unit = {}, + val onAirTriggerButton: (AirTrigger, String) -> Unit = { _, _ -> }, val onSuspendPolicy: (String) -> Unit, val onSteamDownloadsInBackground: (Boolean) -> Unit = {}, val onBackActionsInverted: (Boolean) -> Unit, @@ -456,6 +462,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont remember { DrawerSectionState.load(drawerContext) } var appToChooseDisplay by remember { mutableStateOf(null) } var confirmStop by remember { mutableStateOf(false) } + var airTriggersShown by remember { mutableStateOf(false) } var sheetCoords by remember { mutableStateOf(null) } val widthContext = LocalContext.current var savedWidth by remember { mutableStateOf(SessionPrefs.drawerWidthDp(widthContext)) } @@ -467,15 +474,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont val focusManager = LocalFocusManager.current // A page kept inside More is one step deeper than the strip: back returns to More before it closes the menu. val insideMore = page in pages.inMore() + val airPanel = airTriggersShown && page == SessionDrawerPage.CONTROLLER && a.airTriggers != null BackHandler(enabled = open) { when { host.open != null -> host.open = null + airPanel -> airTriggersShown = false insideMore -> onPageChange(SessionDrawerPage.MORE) else -> a.onClose() } } BackHandler(enabled = open && confirmStop) { confirmStop = false } - val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore) + val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore || airPanel) LaunchedEffect(layerOpen) { onLayerChange(layerOpen) } var seenBackRequest by remember { mutableStateOf(backRequest) } LaunchedEffect(backRequest) { @@ -485,10 +494,23 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont confirmStop -> confirmStop = false appToChooseDisplay != null -> appToChooseDisplay = null host.open != null -> host.open = null + airPanel -> airTriggersShown = false insideMore -> onPageChange(SessionDrawerPage.MORE) } } - LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false } + LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false; airTriggersShown = false } + var airPanelFocused by remember { mutableStateOf(airPanel) } + LaunchedEffect(airPanel) { + val moved = airPanel != airPanelFocused + airPanelFocused = airPanel + if (!moved || !open || !controllerActive) return@LaunchedEffect + val target = if (airPanel) "air-triggers-toggle" else "air-triggers" + repeat(24) { + androidx.compose.runtime.withFrameNanos { } + focus.request(target) + if (focus.focused == target) return@LaunchedEffect + } + } LaunchedEffect(host.open) { if (host.open == "frame-generation") repeat(24) { androidx.compose.runtime.withFrameNanos { } @@ -574,6 +596,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont .controllerBack { when { host.open != null -> host.open = null + airPanel -> airTriggersShown = false managing -> DrawerPages.heldFrom?.let { held -> DrawerPages.rearrange(drawerContext, held) releaseSignal++ @@ -650,7 +673,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), 1)) } } - if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) } + if (insideMore && !managing && !airPanel) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) } + if (airPanel && !managing) DrawerMoreBack(stringResource(R.string.air_triggers_title), focus.track(page, "air-triggers-back"), + parent = stringResource(page.title)) { host.open = null; airTriggersShown = false } if (managing) ManageDrawerPages( offeredDrawerPages(a.achievementsGame != null), Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp), @@ -671,7 +696,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true, LocalDrawerSections provides sections) { DrawerColumns(two = sheetWidth >= DRAWER_TWO_COLUMN_WIDTH && page.inColumns) { when (page) { - SessionDrawerPage.CONTROLLER -> DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track) + SessionDrawerPage.CONTROLLER -> { + val airTriggers = a.airTriggers + if (airPanel && airTriggers != null) AirTriggersPanel(host, airTriggers, a, track) + else DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track) { host.open = null; airTriggersShown = true } + } SessionDrawerPage.HUD -> DrawerPerformancePage(host, a, track) SessionDrawerPage.FRAMEGEN -> DrawerFrameGenPage(host, a, track) SessionDrawerPage.DISPLAY -> DrawerDisplayPage(host, a, track) @@ -731,7 +760,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } @Composable -private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: Boolean, track: (String) -> Modifier) { +private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: Boolean, track: (String) -> Modifier, onAirTriggers: () -> Unit) { val on = stringResource(R.string.widgets_on) val off = stringResource(R.string.widgets_off) val padTag = if (padConnected) stringResource(R.string.drawer_tag_controller) else null @@ -746,9 +775,12 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense), SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360)) val rumbleLabel = stringResource(R.string.ctrl_rumble) - if (a.padType != null || c != null) SettingsGroup( + val airTriggers = a.airTriggers + val airTriggersLabel = stringResource(R.string.air_triggers_title) + if (a.padType != null || c != null || airTriggers != null) SettingsGroup( stringResource(R.string.input_device_settings), key = "controller-pad", tag = padTag, - detail = summary(a.padType?.let { padTypes.labelOf(it) }, c?.let { "$rumbleLabel ${if (it.rumble) on else off}" }), + detail = summary(a.padType?.let { padTypes.labelOf(it) }, c?.let { "$rumbleLabel ${if (it.rumble) on else off}" }, + airTriggers?.let { "$airTriggersLabel ${if (it.enabled) on else off}" }), ) { a.padType?.let { type -> ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), stringResource(R.string.input_virtual_controller_hint), @@ -757,6 +789,10 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: c?.let { ToggleRow(host, "rumble", rumbleLabel, null, it.rumble, chipModifier = track("rumble"), onChange = a.onRumble) } + airTriggers?.let { + ActionRow(airTriggersLabel, if (it.enabled) on else off, stringResource(R.string.air_triggers_open), onAirTriggers, + modifier = track("air-triggers")) + } } val oscChoices = 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)) @@ -1322,15 +1358,15 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List Unit) { +private fun DrawerMoreBack(title: String, modifier: Modifier, parent: String = stringResource(R.string.drawer_page_more), onBack: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val source = remember { MutableInteractionSource() } val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value val shape = RoundedCornerShape(12.dp) - val label = stringResource(R.string.drawer_more_back, stringResource(R.string.drawer_page_more)) + val label = stringResource(R.string.drawer_more_back, parent) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier.padding(top = 8.dp, start = 14.dp, end = 14.dp).fillMaxWidth().heightIn(min = 44.dp).clip(shape) @@ -1344,12 +1380,26 @@ private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit .padding(horizontal = 8.dp), ) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp)) - Text(stringResource(R.string.drawer_page_more), fontSize = 13.sp, color = colors.onSurfaceVariant) + Text(parent, fontSize = 13.sp, color = colors.onSurfaceVariant) Text("·", fontSize = 13.sp, color = colors.onSurfaceVariant) Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) } } +@Composable +private fun AirTriggersPanel(host: MenuHost, t: AirTriggerMenu, a: DrawerActions, track: (String) -> Modifier) { + CompositionLocalProvider(LocalDrawerSections provides null) { SettingsGroup(stringResource(R.string.air_triggers_title)) { + ToggleRow(host, "air-triggers-toggle", stringResource(R.string.air_triggers_use), stringResource(R.string.air_triggers_use_hint), t.enabled, + chipModifier = track("air-triggers-toggle"), onChange = a.onAirTriggers) + for (trigger in AirTrigger.entries) { + val key = "air-trigger-${trigger.name.lowercase()}" + val label = stringResource(if (trigger == AirTrigger.LEFT) R.string.air_trigger_left else R.string.air_trigger_right) + ChoiceRow(host, key, label, stringResource(R.string.air_trigger_button_hint), t.buttons, t.selected.getValue(trigger), + enabled = t.enabled, chipModifier = track(key)) { a.onAirTriggerButton(trigger, it) } + } + } } +} + /** The pages kept inside More, and the way into arranging which pages sit on the strip and which here. */ @Composable private fun DrawerMorePage(host: MenuHost, pages: List, a: DrawerActions, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index f2af52c651..410603eddb 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1337,6 +1337,13 @@ حجم الأزرار عصي تكيّفية اهتزاز اللعبة + Redmagic Air Triggers + فتح + استخدام Air Triggers + يشغّل أزرار الكتف دون لوحة الأزرار أو العلامات من RedMagic، وتضغط بدلاً من ذلك أزرار تخطيط اللمس. + Air Trigger الأيسر + Air Trigger الأيمن + محفوظ لهذا التخطيط المنطقة الميتة لعصا التحكم زر Steam زر QAM diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 109f454cba..965af4cb9a 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1343,6 +1343,13 @@ Tamaño de botones Sticks adaptables Vibración en juegos + Redmagic Air Triggers + Abrir + Usar los Air Triggers + Activa los gatillos de hombro sin el panel ni los marcadores de RedMagic. En su lugar, presionan botones de la disposición táctil. + Air Trigger izquierdo + Air Trigger derecho + Se guarda para esta disposición Zona muerta de la palanca Botón Steam Botón QAM diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 12846c1ab5..a9dbf6b484 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -1309,6 +1309,13 @@ Размер на бутоните Адаптивни стикове Вибрация от играта + Redmagic Air Triggers + Отвори + Използвай Air Triggers + Включва раменните спусъци без панела и маркерите на RedMagic. Вместо това те натискат бутони от сензорното разположение. + Ляв Air Trigger + Десен Air Trigger + Запазва се за това разположение Мъртва зона на стика Бутон Steam Бутон QAM diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index ba390d045d..894cfa3be2 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1323,6 +1323,13 @@ Velikost tlačítek Adaptivní páčky Vibrace ve hře + Redmagic Air Triggers + Otevřít + Používat Air Triggers + Zapne ramenní triggery bez panelu a značek RedMagic. Místo toho mačkají tlačítka dotykového rozložení. + Levý Air Trigger + Pravý Air Trigger + Uloženo pro toto rozložení Mrtvá zóna páčky Tlačítko Steam Tlačítko QAM diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 7dde6f63c7..3fe3f49902 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -1309,6 +1309,13 @@ Knapstørrelse Adaptive styrepinde Spilvibration + Redmagic Air Triggers + Åbn + Brug Air Triggers + Tænder skuldertriggerne uden RedMagics triggerpanel eller markører. De trykker i stedet på knapper i touch-layoutet. + Venstre Air Trigger + Højre Air Trigger + Gemt for dette layout Dødzone for styrepind Steam-knap QAM-knap diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 992d29d406..feec272275 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1301,6 +1301,13 @@ Tastengröße Adaptive Sticks Spielvibration + Redmagic Air Triggers + Öffnen + Air Triggers verwenden + Schaltet die Schultertrigger ohne das Trigger-Panel und die Markierungen von RedMagic ein. Sie drücken stattdessen Tasten des Touch-Layouts. + Linker Air Trigger + Rechter Air Trigger + Für dieses Layout gespeichert Stick-Totzone Steam-Taste QAM-Taste diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index a49dd4fbe4..ae6de19db8 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1309,6 +1309,13 @@ Μέγεθος κουμπιών Προσαρμοστικοί μοχλοί Κραδασμός παιχνιδιού + Redmagic Air Triggers + Άνοιγμα + Χρήση Air Triggers + Ενεργοποιεί τις σκανδάλες ώμου χωρίς τον πίνακα ή τους δείκτες του RedMagic. Αντί γι\' αυτό πατούν κουμπιά της διάταξης αφής. + Αριστερό Air Trigger + Δεξί Air Trigger + Αποθηκεύεται για αυτή τη διάταξη Νεκρή ζώνη μοχλού Κουμπί Steam Κουμπί QAM diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index c24fabe18d..69a3ee5ac2 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1316,6 +1316,13 @@ Tamaño de botones Sticks adaptables Vibración en juegos + Redmagic Air Triggers + Abrir + Usar los Air Triggers + Activa los gatillos de hombro sin el panel ni los marcadores de RedMagic. En su lugar, pulsan botones de la disposición táctil. + Air Trigger izquierdo + Air Trigger derecho + Se guarda para esta disposición Zona muerta de la palanca Botón Steam Botón QAM diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index 16713dbcb4..6287c77aa9 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -1309,6 +1309,13 @@ Painikkeiden koko Mukautuvat sauvat Pelin tärinä + Redmagic Air Triggers + Avaa + Käytä Air Triggereitä + Ottaa olkaliipaisimet käyttöön ilman RedMagicin liipaisinpaneelia tai merkkejä. Ne painavat sen sijaan kosketusasettelun painikkeita. + Vasen Air Trigger + Oikea Air Trigger + Tallennetaan tälle asettelulle Ohjaussauvan kuollut alue Steam-painike QAM-painike diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 6238a0cc16..6f417bfd8c 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1315,6 +1315,13 @@ Taille des boutons Joystick adaptatif Vibration du jeu + Redmagic Air Triggers + Ouvrir + Utiliser les Air Triggers + Active les gâchettes d\'épaule sans le panneau ni les repères de RedMagic. Elles appuient à la place sur des boutons de la disposition tactile. + Air Trigger gauche + Air Trigger droit + Enregistré pour cette disposition Zone morte du stick Bouton Steam Bouton QAM diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index e557f76d02..510eec9e67 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -1309,6 +1309,13 @@ बटन का आकार एडैप्टिव स्टिक गेम वाइब्रेशन + Redmagic Air Triggers + खोलें + Air Triggers इस्तेमाल करें + RedMagic के ट्रिगर पैनल या मार्कर के बिना शोल्डर ट्रिगर चालू करता है। इसके बजाय वे टच लेआउट के बटन दबाते हैं। + लेफ़्ट Air Trigger + राइट Air Trigger + इस लेआउट के लिए सहेजा गया स्टिक का डेड ज़ोन Steam बटन QAM बटन diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 497d330460..226e5c62a2 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -1309,6 +1309,13 @@ Gombméret Adaptív karok Játékvibráció + Redmagic Air Triggers + Megnyitás + Air Triggers használata + Bekapcsolja a vállravaszokat a RedMagic ravaszpanelje és jelölői nélkül. Helyettük az érintéses elrendezés gombjait nyomják meg. + Bal Air Trigger + Jobb Air Trigger + Ehhez az elrendezéshez mentve Kar holtzónája Steam gomb QAM gomb diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index cdbb9de406..b695673b87 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -1303,6 +1303,13 @@ Ukuran tombol Stik adaptif Getaran gim + Redmagic Air Triggers + Buka + Gunakan Air Triggers + Menyalakan trigger bahu tanpa panel atau penanda trigger RedMagic. Sebagai gantinya, trigger menekan tombol tata letak sentuh. + Air Trigger kiri + Air Trigger kanan + Disimpan untuk tata letak ini Zona mati stik Tombol Steam Tombol QAM diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index d37563a4d5..03ae2b9834 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1307,6 +1307,13 @@ Dimensione dei tasti Levette adattive Vibrazione di gioco + Redmagic Air Triggers + Apri + Usa gli Air Triggers + Attiva i grilletti dorsali senza il pannello né gli indicatori di RedMagic. Premono invece i pulsanti del layout touch. + Air Trigger sinistro + Air Trigger destro + Salvato per questo layout Zona morta dello stick Tasto Steam Tasto QAM diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index be60a37db5..a8ab8067c7 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -1303,6 +1303,13 @@ ボタンのサイズ アダプティブスティック ゲームの振動 + Redmagic エアトリガー + 開く + エアトリガーを使う + RedMagic のトリガーパネルやマーカーを出さずにショルダートリガーをオンにし、タッチレイアウトのボタンを押します。 + 左エアトリガー + 右エアトリガー + このレイアウトに保存されます スティックのデッドゾーン Steamボタン QAMボタン diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 89c839ce22..d886f0aa3c 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -1303,6 +1303,13 @@ 버튼 크기 적응형 스틱 게임 진동 + Redmagic 에어 트리거 + 열기 + 에어 트리거 사용 + RedMagic 트리거 패널이나 표시 없이 숄더 트리거를 켜고, 대신 터치 레이아웃의 버튼을 누릅니다. + 왼쪽 에어 트리거 + 오른쪽 에어 트리거 + 이 레이아웃에 저장됨 스틱 데드존 Steam 버튼 QAM 버튼 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index a13e0ba39f..8b790a1d9c 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -1303,6 +1303,13 @@ Saiz butang Stik adaptif Getaran permainan + Redmagic Air Triggers + Buka + Guna Air Triggers + Menghidupkan pencetus bahu tanpa panel atau penanda pencetus RedMagic. Sebaliknya, ia menekan butang susun atur sentuh. + Air Trigger kiri + Air Trigger kanan + Disimpan untuk susun atur ini Zon mati kayu bedik Butang Steam Butang QAM diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index e2130d6988..16b581fda5 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -1309,6 +1309,13 @@ Knappestørrelse Adaptive stikker Spillvibrasjon + Redmagic Air Triggers + Åpne + Bruk Air Triggers + Slår på skuldertriggerne uten RedMagics triggerpanel eller markører. De trykker i stedet på knapper i berøringsoppsettet. + Venstre Air Trigger + Høyre Air Trigger + Lagret for dette oppsettet Dødsone for styrespak Steam-knapp QAM-knapp diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 7563fbaf45..1b50e9593e 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1309,6 +1309,13 @@ Knopgrootte Adaptieve sticks Trillen in games + Redmagic Air Triggers + Openen + Air Triggers gebruiken + Zet de schoudertriggers aan zonder het triggerpaneel of de markeringen van RedMagic. Ze drukken in plaats daarvan knoppen van de aanraakindeling in. + Linker Air Trigger + Rechter Air Trigger + Opgeslagen voor deze indeling Dode zone van stick Steam-knop QAM-knop diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 383bc3aed3..be203d5abb 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1323,6 +1323,13 @@ Rozmiar przycisków Adaptacyjne gałki Wibracje gry + Redmagic Air Triggers + Otwórz + Używaj Air Triggers + Włącza spusty naramienne bez panelu i znaczników RedMagic. Zamiast tego naciskają przyciski układu dotykowego. + Lewy Air Trigger + Prawy Air Trigger + Zapisane dla tego układu Martwa strefa drążka Przycisk Steam Przycisk QAM diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index c18340904d..8a53b7ccda 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -1307,6 +1307,13 @@ Tamanho dos botões Analógicos adaptáveis Vibração do jogo + Redmagic Air Triggers + Abrir + Utilizar os Air Triggers + Liga os gatilhos de ombro sem o painel nem os marcadores da RedMagic. Em vez disso, premem botões do esquema tátil. + Air Trigger esquerdo + Air Trigger direito + Guardado para este esquema Zona morta do manípulo Botão Steam Botão QAM diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 6fea986206..42fc31c467 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1315,6 +1315,13 @@ Tamanho dos botões Analógicos adaptáveis Vibração do jogo + Redmagic Air Triggers + Abrir + Usar os Air Triggers + Liga os gatilhos de ombro sem o painel nem os marcadores da RedMagic. Em vez disso, eles apertam botões do layout de toque. + Air Trigger esquerdo + Air Trigger direito + Salvo para este layout Zona morta do analógico Botão Steam Botão QAM diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index fc7da00b02..879b8172f7 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -1316,6 +1316,13 @@ Dimensiunea butoanelor Manșe adaptive Vibrații de joc + Redmagic Air Triggers + Deschide + Folosește Air Triggers + Pornește triggerele de umăr fără panoul sau marcajele RedMagic. În schimb, ele apasă butoane din aranjamentul tactil. + Air Trigger stâng + Air Trigger drept + Salvat pentru acest aranjament Zonă moartă a manetei Butonul Steam Butonul QAM diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 5117873485..ebd87e6bf0 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1323,6 +1323,13 @@ Размер кнопок Адаптивные стики Вибрация в играх + Redmagic Air Triggers + Открыть + Использовать Air Triggers + Включает плечевые триггеры без панели и меток RedMagic. Вместо этого они нажимают кнопки сенсорной раскладки. + Левый Air Trigger + Правый Air Trigger + Сохраняется для этой раскладки Мёртвая зона стика Кнопка Steam Кнопка QAM diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 455c4d6472..f0fe8ddbc7 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -1309,6 +1309,13 @@ Knappstorlek Adaptiva spakar Spelvibration + Redmagic Air Triggers + Öppna + Använd Air Triggers + Slår på axelavtryckarna utan RedMagics avtryckarpanel eller markeringar. De trycker i stället på knappar i pekskärmslayouten. + Vänster Air Trigger + Höger Air Trigger + Sparas för den här layouten Styrspakens dödzon Steam-knappen QAM-knappen diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 104b5f6407..92ea1d9489 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -1303,6 +1303,13 @@ ขนาดปุ่ม สติ๊กแบบปรับอัตโนมัติ การสั่นของเกม + Redmagic Air Triggers + เปิด + ใช้ Air Triggers + เปิดทริกเกอร์ไหล่โดยไม่แสดงแผงทริกเกอร์หรือเครื่องหมายของ RedMagic และให้กดปุ่มในการจัดวางแบบสัมผัสแทน + Air Trigger ซ้าย + Air Trigger ขวา + บันทึกไว้สำหรับการจัดวางนี้ เดดโซนของแอนะล็อกสติ๊ก ปุ่ม Steam ปุ่ม QAM diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index bbe4bad308..0af0df394d 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -1301,6 +1301,13 @@ Düğme boyutu Uyarlanabilir çubuklar Oyun titreşimi + Redmagic Air Triggers + Aç + Air Triggers kullan + Omuz tetiklerini RedMagic tetik paneli veya işaretleri olmadan açar. Bunun yerine dokunmatik düzenin düğmelerine basarlar. + Sol Air Trigger + Sağ Air Trigger + Bu düzen için kaydedilir Çubuk ölü bölgesi Steam düğmesi QAM düğmesi diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 36ba31f001..2542adae60 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -1323,6 +1323,13 @@ Розмір кнопок Адаптивні стики Вібрація гри + Redmagic Air Triggers + Відкрити + Використовувати Air Triggers + Вмикає плечові тригери без панелі та міток RedMagic. Натомість вони натискають кнопки сенсорної розкладки. + Лівий Air Trigger + Правий Air Trigger + Зберігається для цієї розкладки Мертва зона стіка Кнопка Steam Кнопка QAM diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 9c9ec116bf..e1a8f73f01 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -1303,6 +1303,13 @@ Kích thước nút Cần thích ứng Rung khi chơi game + Redmagic Air Triggers + Mở + Dùng Air Triggers + Bật trigger vai mà không hiện bảng trigger hay điểm đánh dấu của RedMagic. Thay vào đó, chúng nhấn các nút của bố cục cảm ứng. + Air Trigger trái + Air Trigger phải + Được lưu cho bố cục này Vùng chết của cần điều khiển Nút Steam Nút QAM diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index d9a964ca6a..b6160404df 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1386,6 +1386,13 @@ 按钮大小 自适应摇杆 游戏震动 + 红魔肩键 + 打开 + 使用肩键 + 开启肩键,但不显示红魔的肩键面板和屏幕标记。肩键改为按下触控布局中的按钮。 + 左肩键 + 右肩键 + 按此布局保存 摇杆死区 Steam 按钮 QAM 按钮 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 1e921fb63e..ebf2e36cba 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -1302,6 +1302,13 @@ 按鍵大小 自動調整搖桿 遊戲震動 + 紅魔肩鍵 + 開啟 + 使用肩鍵 + 開啟肩鍵,但不顯示紅魔的肩鍵面板和螢幕標記。肩鍵改為按下觸控佈局中的按鈕。 + 左肩鍵 + 右肩鍵 + 按此佈局儲存 搖桿死區 Steam 按鈕 QAM 按鈕 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 7ea662de72..ecb0161f5d 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1302,6 +1302,13 @@ 按鍵大小 自適應搖桿 遊戲震動 + 紅魔肩鍵 + 開啟 + 使用肩鍵 + 開啟肩鍵,但不顯示紅魔的肩鍵面板和螢幕標記。肩鍵改為按下觸控版面配置中的按鈕。 + 左肩鍵 + 右肩鍵 + 依此版面配置儲存 搖桿死區 Steam 按鈕 QAM 按鈕 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 213b72aa62..830b327b42 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1499,6 +1499,13 @@ Button size Adaptive sticks Game vibration + Redmagic Air Triggers + Open + Use Air Triggers + Turns on the shoulder triggers without RedMagic\'s trigger panel or markers. They press buttons of the touch layout instead. + Left Air Trigger + Right Air Trigger + Saved for this layout Stick dead zone Steam button QAM button diff --git a/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt b/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt new file mode 100644 index 0000000000..16eb8de5b3 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt @@ -0,0 +1,178 @@ +package com.droiddeck.launcher.input + +import android.view.KeyEvent +import java.io.File +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class]) +class RedMagicAirTriggersTest { + private val events = mutableListOf() + private val router = InputRouter(object : InputOutput { + override fun key(code: Int, down: Boolean) { events += "key:$code:$down" } + override fun button(code: Int, down: Boolean) { events += "button:$code:$down" } + override fun pointer(dx: Float, dy: Float) {} + override fun scroll(steps: Int) {} + override fun command(command: InputCommand) { events += command.name } + override fun command(command: InputCommand, role: InputRole) { events += "${command.name}:$role" } + override fun requestMotion() {} + }) + private val context = RuntimeEnvironment.getApplication() + private val bridge = PadBridge(File(context.cacheDir, "air-trigger-input")) + private val input = AirTriggerInput(bridge) + private val lt = InputSurfaceElement(InputControl.LT, .1f, .1f, .1f, .1f) + private val rt = InputSurfaceElement(InputControl.RT, .8f, .1f, .1f, .1f) + private val jump = InputSurfaceElement(InputControl.A, .8f, .8f, .1f, .1f, id = "custom:jump", name = "Jump") + private val stick = InputSurfaceElement(InputControl.LS, .1f, .7f, .2f, .2f) + private val layout = SavedInputLayout("pad", "Pad", listOf(lt, rt, jump, stick)) + + @Before fun setup() { bridge.setInputRouter(router); DeckControls.setRouter(router) } + @After fun close() { input.close(); bridge.stop(); DeckControls.setRouter(null); DeckControls.releaseAll() } + + private fun bind(vararg actions: Pair) { + bridge.setInputProfile(InputProfile("test", elements = mapOf(InputRole.PRIMARY to mapOf(*actions)))) + } + private fun down(trigger: AirTrigger, enabled: Boolean = true, repeat: Int = 0) = input.onKey(trigger, KeyEvent.ACTION_DOWN, repeat, enabled) + private fun up(trigger: AirTrigger) = input.onKey(trigger, KeyEvent.ACTION_UP, 0, true) + + @Test fun onlyTheTriggerDeviceKeysAreAirTriggers() { + assertEquals(AirTrigger.LEFT, AirTrigger.of(KeyEvent.KEYCODE_F7, "nubia_tgk_aw_sar0_ch0")) + assertEquals(AirTrigger.RIGHT, AirTrigger.of(KeyEvent.KEYCODE_F8, "nubia_tgk_aw_sar0_ch0")) + assertNull(AirTrigger.of(KeyEvent.KEYCODE_F7, "Keychron K2")) + assertNull(AirTrigger.of(KeyEvent.KEYCODE_F8, null)) + assertNull(AirTrigger.of(KeyEvent.KEYCODE_VOLUME_DOWN, "nubia_tgk_aw_sar0_ch0")) + } + + @Test fun theTriggerLightUsesTheEffectPickedInRedMagicsSettings() { + val settings = """{"version":1,"left_up":{"enable":true,"id":"107"},"shoulder_effects":{"close":"02000000","steady":"02101000"},"selection":"02101000"}""" + assertEquals("02101000", RedMagicAirTriggers.shoulderEffect(settings)) + assertNull(RedMagicAirTriggers.shoulderEffect(null)) + assertNull(RedMagicAirTriggers.shoulderEffect("not json")) + assertNull(RedMagicAirTriggers.shoulderEffect("""{"version":1}""")) + assertNull(RedMagicAirTriggers.shoulderEffect("""{"selection":"021"}""")) + } + + @Test fun triggersDefaultToTheLayoutTriggersAndFollowAChoiceThatStillExists() { + assertEquals(lt, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, null)) + assertEquals(rt, AirTriggerButtons.resolve(layout, AirTrigger.RIGHT, null)) + assertEquals(jump, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, "custom:jump")) + assertEquals(lt, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, "custom:removed")) + assertEquals(listOf(lt, rt, jump), AirTriggerButtons.options(layout)) + } + + @Test fun aLayoutWithoutTriggersStillOffersTheControllerTriggers() { + val buttons = SavedInputLayout("buttons", "Buttons", listOf(jump)) + assertEquals(listOf("custom:jump", "legacy:lt", "legacy:rt"), AirTriggerButtons.options(buttons).map { it.id }) + assertEquals("legacy:rt", AirTriggerButtons.resolve(buttons, AirTrigger.RIGHT, null).id) + assertEquals("legacy:lt", AirTriggerButtons.resolve(null, AirTrigger.LEFT, null).id) + } + + @Test fun choicesAreSavedPerLayoutAndTheToggleStartsOff() { + assertFalse(AirTriggerPrefs.enabled(context)) + AirTriggerPrefs.setEnabled(context, true) + AirTriggerPrefs.setButton(context, "pad", AirTrigger.LEFT, "custom:jump") + assertTrue(AirTriggerPrefs.enabled(context)) + assertEquals("custom:jump", AirTriggerPrefs.button(context, "pad", AirTrigger.LEFT)) + assertNull(AirTriggerPrefs.button(context, "pad", AirTrigger.RIGHT)) + assertNull(AirTriggerPrefs.button(context, "other", AirTrigger.LEFT)) + } + + @Test fun aTriggerPressesTheChosenLayoutButton() { + bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57))) + input.configure(mapOf(AirTrigger.LEFT to lt, AirTrigger.RIGHT to jump)) + assertTrue(down(AirTrigger.LEFT)); assertTrue(down(AirTrigger.RIGHT)) + assertTrue(up(AirTrigger.RIGHT)); assertTrue(up(AirTrigger.LEFT)) + assertEquals(listOf("key:42:true", "key:57:true", "key:57:false", "key:42:false"), events) + } + + @Test fun keyRepeatsAndPressesWhileInputIsBlockedAreSwallowed() { + bind("legacy:lt" to InputAction.Keys(listOf(42))) + input.configure(mapOf(AirTrigger.LEFT to lt)) + assertTrue(down(AirTrigger.LEFT, enabled = false)) + assertTrue(up(AirTrigger.LEFT)) + assertTrue(down(AirTrigger.LEFT)); assertTrue(down(AirTrigger.LEFT, repeat = 1)) + assertTrue(up(AirTrigger.LEFT)) + assertEquals(listOf("key:42:true", "key:42:false"), events) + } + + @Test fun switchingOffReleasesAHeldButtonAndLetsTheKeysThrough() { + bind("legacy:lt" to InputAction.Keys(listOf(42))) + input.configure(mapOf(AirTrigger.LEFT to lt)) + assertFalse(down(AirTrigger.RIGHT)) + down(AirTrigger.LEFT) + input.configure(emptyMap()) + assertEquals(listOf("key:42:true", "key:42:false"), events) + assertTrue(up(AirTrigger.LEFT)) + assertFalse(down(AirTrigger.LEFT)) + assertEquals(2, events.size) + } + + @Test fun aButtonShownOnScreenTakesThePressAndTheTriggersLight() { + val screen = mutableListOf() + val lights = mutableListOf() + val onScreen = AirTriggerInput(bridge, { id, trigger, held, cancelled -> screen += "$id:$trigger:$held:$cancelled"; id == "custom:jump" }, { lights += it }) + bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57))) + onScreen.configure(mapOf(AirTrigger.LEFT to lt, AirTrigger.RIGHT to jump)) + onScreen.onKey(AirTrigger.RIGHT, KeyEvent.ACTION_DOWN, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + onScreen.onKey(AirTrigger.RIGHT, KeyEvent.ACTION_UP, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, false); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + onScreen.close() + assertEquals(listOf("custom:jump:RIGHT:true:false", "legacy:lt:LEFT:true:false", "custom:jump:RIGHT:false:false"), screen) + assertEquals(listOf("key:42:true", "key:42:false"), events) + assertEquals(listOf(108, 106, 109, 107), lights) + } + + @Test fun switchingOffLetsGoOfTheOnScreenButton() { + val screen = mutableListOf() + val onScreen = AirTriggerInput(bridge, { id, trigger, held, cancelled -> screen += "$id:$trigger:$held:$cancelled"; true }) + onScreen.configure(mapOf(AirTrigger.LEFT to jump)) + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + onScreen.configure(emptyMap()) + assertTrue(onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true)) + assertEquals(listOf("custom:jump:LEFT:true:false", "custom:jump:LEFT:false:true"), screen) + } + + @Test fun aForcedReleaseDoesNotRunACommandButtonButAKeyUpDoes() { + bind("custom:jump" to InputAction.Command(InputCommand.KEYBOARD)) + input.configure(mapOf(AirTrigger.LEFT to jump)) + down(AirTrigger.LEFT) + input.release() + up(AirTrigger.LEFT) + assertEquals(emptyList(), events) + down(AirTrigger.LEFT); up(AirTrigger.LEFT) + assertEquals(listOf("KEYBOARD:PRIMARY"), events) + } + + @Test fun aToggleLatchedWhileItsButtonWasHiddenIsHandedToTheShownButton() { + var shown = false + val screen = mutableListOf() + val onScreen = AirTriggerInput(bridge, { id, _, held, _ -> screen += "$id:$held"; shown }) + bind("custom:jump" to InputAction.Keys(listOf(57))) + onScreen.configure(mapOf(AirTrigger.LEFT to jump.copy(toggle = true))) + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + assertEquals(listOf("key:57:true"), events) + shown = true + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true) + assertEquals(listOf("key:57:true", "key:57:false"), events) + onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true) + onScreen.close() + assertEquals(listOf("custom:jump:true", "custom:jump:true", "custom:jump:false"), screen) + } + + @Test fun choosingAnotherButtonMovesTheTriggerWithoutLeavingTheOldOneHeld() { + bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57))) + input.configure(mapOf(AirTrigger.LEFT to lt)) + down(AirTrigger.LEFT) + input.configure(mapOf(AirTrigger.LEFT to jump)) + up(AirTrigger.LEFT) + down(AirTrigger.LEFT); up(AirTrigger.LEFT) + assertEquals(listOf("key:42:true", "key:42:false", "key:57:true", "key:57:false"), events) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt index a42a0bf76c..786ee5203a 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceTouchTest.kt @@ -77,6 +77,59 @@ class InputSurfaceTouchTest { assertFalse(state().isDown(PadState.A)) } + @Test fun anOutsideHoldPressesAndLightsTheButtonAlongsideAFinger() { + val surface = view.inputSurface + val button = (surface.javaClass.getDeclaredField("customCanvas").also { it.isAccessible = true }.get(surface) as ViewGroup).getChildAt(0) + fun lit() = button.javaClass.getDeclaredMethod("getHighlighted").also { it.isAccessible = true }.invoke(button) as Boolean + + assertTrue(surface.hold(a.id, 0, true)) + assertTrue(state().isDown(PadState.A)) + assertTrue(lit()) + touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) + touch(MotionEvent.ACTION_UP, 1 to (800f to 240f)) + assertTrue(state().isDown(PadState.A)) + assertTrue(surface.hold(a.id, 0, false)) + assertFalse(state().isDown(PadState.A)) + assertFalse(lit()) + assertFalse(surface.hold("custom:missing", 0, true)) + } + + @Test fun aCancelledTouchLeavesAnOutsideHoldOnTheButton() { + val surface = view.inputSurface + assertTrue(surface.hold(a.id, 0, true)) + touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) + touch(MotionEvent.ACTION_CANCEL, 1 to (800f to 240f)) + assertTrue(state().isDown(PadState.A)) + assertTrue(surface.hold(a.id, 0, false)) + assertFalse(state().isDown(PadState.A)) + } + + @Test fun releasingAllInputLetsGoOfAnOutsideHold() { + val surface = view.inputSurface + val button = (surface.javaClass.getDeclaredField("customCanvas").also { it.isAccessible = true }.get(surface) as ViewGroup).getChildAt(0) + fun lit() = button.javaClass.getDeclaredMethod("getHighlighted").also { it.isAccessible = true }.invoke(button) as Boolean + + assertTrue(surface.hold(a.id, 0, true)) + view.releaseAll() + assertFalse(state().isDown(PadState.A)) + assertFalse(lit()) + touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f)) + assertTrue(state().isDown(PadState.A)) + touch(MotionEvent.ACTION_UP, 1 to (800f to 240f)) + assertTrue(surface.hold(a.id, 0, false)) + assertFalse(state().isDown(PadState.A)) + } + + @Test fun aCancelledOutsideHoldDoesNotRunTheButtonsCommand() { + val surface = view.inputSurface + assertTrue(surface.hold(keyboard.id, 0, true)) + assertTrue(surface.hold(keyboard.id, 0, false, cancelled = true)) + assertEquals(emptyList(), events) + assertTrue(surface.hold(keyboard.id, 0, true)) + assertTrue(surface.hold(keyboard.id, 0, false)) + assertEquals(listOf("KEYBOARD:PRIMARY"), events) + } + @Test fun steamDeckStylingKeepsTheHeldButtonAndItsHitArea() { val button = a.copy(buttonShape = InputButtonShape.CIRCLE) show(button)