diff --git a/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt b/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt index 633564558c..71024f202e 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/RedMagicAirTriggers.kt @@ -3,7 +3,9 @@ package com.droiddeck.launcher.input import android.content.Context import android.content.SharedPreferences import android.net.Uri +import android.os.Handler import android.os.IBinder +import android.os.Looper import android.os.Parcel import android.provider.Settings import android.util.Log @@ -11,6 +13,7 @@ import android.view.InputDevice import android.view.KeyEvent import java.util.EnumMap import java.util.EnumSet +import java.util.concurrent.Executor import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit @@ -65,38 +68,41 @@ object RedMagicAirTriggers { 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 } - } + private val REAPPLY_MS = longArrayOf(1_000, 5_000) + internal var worker: Executor = ThreadPoolExecutor(0, 1, 10, TimeUnit.SECONDS, LinkedBlockingQueue()) { Thread(it, "air-triggers") } + internal var lights: TriggerLights = ColorfulLights + private val main = Handler(Looper.getMainLooper()) + private var reapply: Runnable? = null @Suppress("DEPRECATION") fun supported(context: Context) = context.packageManager.resolveContentProvider(AUTHORITY, 0) != null && InputDevice.getDeviceIds().any { AirTrigger.isTriggerDevice(InputDevice.getDevice(it)?.name) } + /** Call on the main thread. */ 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) } - } - } + cancelReapply() + worker.execute { apply(app) } + // Game Space runs its own trigger setup for the app that comes to the front, which switches the trigger keys and lights off again. + val again = Runnable { worker.execute { apply(app) } } + reapply = again + REAPPLY_MS.forEach { main.postDelayed(again, it) } + } + + private fun apply(app: Context) { + 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 + lights.request(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(lights::setEffect) + // Entering the scene turns the lights off; the release actions show the idle light picked in RedMagic's lighting settings. + AirTrigger.entries.forEach { lights.request(it.releaseLight) } } /** The trigger light effect the user picked in RedMagic's lighting settings, such as "02101000" for steady. */ @@ -104,27 +110,55 @@ object RedMagicAirTriggers { ?.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. */ + /** Closes only what this app opened, so a distribute another app turned on stays on. Call on the main thread. */ fun restore(context: Context) { val app = context.applicationContext + cancelReapply() worker.execute { val prefs = AirTriggerPrefs.prefs(app) if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false)) return@execute - requestLight(SHOULDER_LIGHT_OFF) + lights.request(SHOULDER_LIGHT_OFF) if (call(app, CLOSE)) prefs.edit().remove(AirTriggerPrefs.OWNED).commit() } } - fun light(code: Int) = worker.execute { requestLight(code) } + fun light(code: Int) = worker.execute { lights.request(code) } - private fun requestLight(action: Int) = transact(REQUEST_LIGHT) { writeInt(action) } + private fun cancelReapply() { + reapply?.let(main::removeCallbacks) + reapply = null + } + + 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) +} + +internal interface TriggerLights { + fun request(action: Int) + fun setEffect(effect: String) +} + +private object ColorfulLights : TriggerLights { + private const val TAG = "AirTriggers" + private const val SERVICE = "ColorfulLightService" + private const val 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 val binder: IBinder? by lazy { + runCatching { Class.forName("android.os.ServiceManager").getMethod("getService", String::class.java).invoke(null, SERVICE) as IBinder? } + .getOrNull()?.takeIf { runCatching { it.interfaceDescriptor }.getOrNull() == INTERFACE } + } + + override fun request(action: Int) = transact(REQUEST_LIGHT) { writeInt(action) } + override fun setEffect(effect: String) = transact(SET_SHOULDER_EFFECT) { writeString(effect) } private fun transact(code: Int, write: Parcel.() -> Unit) { - val binder = lights ?: return + val binder = binder ?: return val data = Parcel.obtain() val reply = Parcel.obtain() try { - data.writeInterfaceToken(LIGHT_INTERFACE) + data.writeInterfaceToken(INTERFACE) data.write() binder.transact(code, data, reply, 0) reply.readException() @@ -135,9 +169,6 @@ object RedMagicAirTriggers { 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. */ diff --git a/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt b/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt index 16eb8de5b3..4dda8859ec 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/RedMagicAirTriggersTest.kt @@ -1,7 +1,11 @@ package com.droiddeck.launcher.input +import android.os.Looper +import android.provider.Settings import android.view.KeyEvent import java.io.File +import java.time.Duration +import java.util.concurrent.Executor import org.junit.After import org.junit.Assert.* import org.junit.Before @@ -9,6 +13,7 @@ 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) @@ -59,6 +64,31 @@ class RedMagicAirTriggersTest { assertNull(RedMagicAirTriggers.shoulderEffect("""{"selection":"021"}""")) } + @Test fun openingShowsTheIdleLightAndAppliesAgainAfterGameSpacesOwnSetup() { + val calls = mutableListOf() + val worker = RedMagicAirTriggers.worker + val lights = RedMagicAirTriggers.lights + RedMagicAirTriggers.worker = Executor { it.run() } + RedMagicAirTriggers.lights = object : TriggerLights { + override fun request(action: Int) { calls += "$action" } + override fun setEffect(effect: String) { calls += effect } + } + Settings.Global.putString(context.contentResolver, "lighting_shoulder_config_json", """{"selection":"02101000"}""") + try { + val opened = listOf("110", "02101000", "107", "109") + RedMagicAirTriggers.open(context) + assertEquals(opened, calls) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1)) + assertEquals(opened + opened, calls) + RedMagicAirTriggers.restore(context) + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(10)) + assertEquals(opened + opened + "111", calls) + } finally { + RedMagicAirTriggers.worker = worker + RedMagicAirTriggers.lights = lights + } + } + @Test fun triggersDefaultToTheLayoutTriggersAndFollowAChoiceThatStillExists() { assertEquals(lt, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, null)) assertEquals(rt, AirTriggerButtons.resolve(layout, AirTrigger.RIGHT, null))