diff options
31 files changed, 2152 insertions, 1942 deletions
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg index e862cd9e0a95..843fde7baf2b 100644 --- a/PREUPLOAD.cfg +++ b/PREUPLOAD.cfg @@ -19,7 +19,7 @@ clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp tests/ tools/ bpfmt = -d -ktfmt = --kotlinlang-style --include-dirs=services/permission,packages/SystemUI,libs/WindowManager/Shell/src/com/android/wm/shell/freeform,libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode,libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode,apct-tests +ktfmt = --kotlinlang-style --include-dirs=services/permission,packages/SystemUI,libs/WindowManager/Shell/src/com/android/wm/shell/freeform,libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode,libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode,apct-tests,tests/Input [Hook Scripts] checkstyle_hook = ${REPO_ROOT}/prebuilts/checkstyle/checkstyle.py --sha ${PREUPLOAD_COMMIT} diff --git a/tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt b/tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt index a1e165551b5b..c58287760d0e 100644 --- a/tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt +++ b/tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt @@ -44,14 +44,12 @@ import org.mockito.junit.MockitoJUnitRunner /** * Tests for [InputManager.InputDeviceBatteryListener]. * - * Build/Install/Run: - * atest InputTests:InputDeviceBatteryListenerTest + * Build/Install/Run: atest InputTests:InputDeviceBatteryListenerTest */ @Presubmit @RunWith(MockitoJUnitRunner::class) class InputDeviceBatteryListenerTest { - @get:Rule - val rule = MockitoJUnit.rule()!! + @get:Rule val rule = MockitoJUnit.rule()!! private lateinit var testLooper: TestLooper private var registeredListener: IInputDeviceBatteryListener? = null @@ -60,8 +58,7 @@ class InputDeviceBatteryListenerTest { private lateinit var context: Context private lateinit var inputManager: InputManager - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val inputManagerRule = MockInputManagerRule() @Before fun setUp() { @@ -71,41 +68,48 @@ class InputDeviceBatteryListenerTest { registeredListener = null monitoredDevices.clear() inputManager = InputManager(context) - `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))) - .thenReturn(inputManager) + `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager) // Handle battery listener registration. doAnswer { - val deviceId = it.getArgument(0) as Int - val listener = it.getArgument(1) as IInputDeviceBatteryListener - if (registeredListener != null && - registeredListener!!.asBinder() != listener.asBinder()) { - // There can only be one registered battery listener per process. - fail("Trying to register a new listener when one already exists") + val deviceId = it.getArgument(0) as Int + val listener = it.getArgument(1) as IInputDeviceBatteryListener + if ( + registeredListener != null && + registeredListener!!.asBinder() != listener.asBinder() + ) { + // There can only be one registered battery listener per process. + fail("Trying to register a new listener when one already exists") + } + if (monitoredDevices.contains(deviceId)) { + fail("Trying to start monitoring a device that was already being monitored") + } + monitoredDevices.add(deviceId) + registeredListener = listener + null } - if (monitoredDevices.contains(deviceId)) { - fail("Trying to start monitoring a device that was already being monitored") - } - monitoredDevices.add(deviceId) - registeredListener = listener - null - }.`when`(inputManagerRule.mock).registerBatteryListener(anyInt(), any()) + .`when`(inputManagerRule.mock) + .registerBatteryListener(anyInt(), any()) // Handle battery listener being unregistered. doAnswer { - val deviceId = it.getArgument(0) as Int - val listener = it.getArgument(1) as IInputDeviceBatteryListener - if (registeredListener == null || - registeredListener!!.asBinder() != listener.asBinder()) { - fail("Trying to unregister a listener that is not registered") - } - if (!monitoredDevices.remove(deviceId)) { - fail("Trying to stop monitoring a device that is not being monitored") + val deviceId = it.getArgument(0) as Int + val listener = it.getArgument(1) as IInputDeviceBatteryListener + if ( + registeredListener == null || + registeredListener!!.asBinder() != listener.asBinder() + ) { + fail("Trying to unregister a listener that is not registered") + } + if (!monitoredDevices.remove(deviceId)) { + fail("Trying to stop monitoring a device that is not being monitored") + } + if (monitoredDevices.isEmpty()) { + registeredListener = null + } } - if (monitoredDevices.isEmpty()) { - registeredListener = null - } - }.`when`(inputManagerRule.mock).unregisterBatteryListener(anyInt(), any()) + .`when`(inputManagerRule.mock) + .unregisterBatteryListener(anyInt(), any()) } private fun notifyBatteryStateChanged( @@ -113,15 +117,17 @@ class InputDeviceBatteryListenerTest { isPresent: Boolean = true, status: Int = BatteryState.STATUS_FULL, capacity: Float = 1.0f, - eventTime: Long = 12345L + eventTime: Long = 12345L, ) { - registeredListener!!.onBatteryStateChanged(IInputDeviceBatteryState().apply { - this.deviceId = deviceId - this.updateTime = eventTime - this.isPresent = isPresent - this.status = status - this.capacity = capacity - }) + registeredListener!!.onBatteryStateChanged( + IInputDeviceBatteryState().apply { + this.deviceId = deviceId + this.updateTime = eventTime + this.isPresent = isPresent + this.status = status + this.capacity = capacity + } + ) } @Test @@ -130,7 +136,9 @@ class InputDeviceBatteryListenerTest { // Add a battery listener to monitor battery changes. inputManager.addInputDeviceBatteryListener(1 /*deviceId*/, executor) { - deviceId: Int, eventTime: Long, batteryState: BatteryState -> + deviceId: Int, + eventTime: Long, + batteryState: BatteryState -> callbackCount++ assertEquals(1, deviceId) assertEquals(true, batteryState.isPresent) @@ -149,8 +157,13 @@ class InputDeviceBatteryListenerTest { assertEquals(0, callbackCount) // Notifying battery change for the registered device will notify the listener. - notifyBatteryStateChanged(1 /*deviceId*/, true /*isPresent*/, - BatteryState.STATUS_DISCHARGING, 0.5f /*capacity*/, 8675309L /*eventTime*/) + notifyBatteryStateChanged( + 1 /*deviceId*/, + true /*isPresent*/, + BatteryState.STATUS_DISCHARGING, + 0.5f /*capacity*/, + 8675309L, /*eventTime*/ + ) testLooper.dispatchNext() assertEquals(1, callbackCount) } diff --git a/tests/Input/src/android/hardware/input/InputManagerTest.kt b/tests/Input/src/android/hardware/input/InputManagerTest.kt index 4c6bb849155c..e6bec077d9d4 100644 --- a/tests/Input/src/android/hardware/input/InputManagerTest.kt +++ b/tests/Input/src/android/hardware/input/InputManagerTest.kt @@ -38,8 +38,7 @@ import org.mockito.junit.MockitoJUnitRunner /** * Tests for [InputManager]. * - * Build/Install/Run: - * atest InputTests:InputManagerTest + * Build/Install/Run: atest InputTests:InputManagerTest */ @Presubmit @RunWith(MockitoJUnitRunner::class) @@ -51,8 +50,7 @@ class InputManagerTest { const val THIRD_DEVICE_ID = 99 } - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val inputManagerRule = MockInputManagerRule() private lateinit var devicesChangedListener: IInputDevicesChangedListener private val deviceGenerationMap = mutableMapOf<Int /*deviceId*/, Int /*generation*/>() @@ -64,9 +62,7 @@ class InputManagerTest { context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext())) inputManager = InputManager(context) `when`(context.getSystemService(eq(Context.INPUT_SERVICE))).thenReturn(inputManager) - `when`(inputManagerRule.mock.inputDeviceIds).then { - deviceGenerationMap.keys.toIntArray() - } + `when`(inputManagerRule.mock.inputDeviceIds).then { deviceGenerationMap.keys.toIntArray() } } private fun notifyDeviceChanged( @@ -74,8 +70,9 @@ class InputManagerTest { associatedDisplayId: Int, usiVersion: HostUsiVersion?, ) { - val generation = deviceGenerationMap[deviceId]?.plus(1) - ?: throw IllegalArgumentException("Device $deviceId was never added!") + val generation = + deviceGenerationMap[deviceId]?.plus(1) + ?: throw IllegalArgumentException("Device $deviceId was never added!") deviceGenerationMap[deviceId] = generation `when`(inputManagerRule.mock.getInputDevice(deviceId)) diff --git a/tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt b/tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt index c62bd0b72584..7f7d4590c322 100644 --- a/tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt +++ b/tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt @@ -23,6 +23,11 @@ import android.platform.test.flag.junit.SetFlagsRule import android.view.KeyEvent import androidx.test.core.app.ApplicationProvider import com.android.test.input.MockInputManagerRule +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.fail +import org.junit.Assert.assertThrows import org.junit.Before import org.junit.Rule import org.junit.Test @@ -31,17 +36,11 @@ import org.mockito.Mockito import org.mockito.Mockito.doAnswer import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner -import kotlin.test.assertEquals -import kotlin.test.assertNotNull -import kotlin.test.assertNull -import kotlin.test.fail -import org.junit.Assert.assertThrows /** * Tests for [InputManager.KeyGestureEventHandler]. * - * Build/Install/Run: - * atest InputTests:KeyGestureEventHandlerTest + * Build/Install/Run: atest InputTests:KeyGestureEventHandlerTest */ @Presubmit @RunWith(MockitoJUnitRunner::class) @@ -49,24 +48,24 @@ class KeyGestureEventHandlerTest { companion object { const val DEVICE_ID = 1 - val HOME_GESTURE_EVENT = KeyGestureEvent.Builder() - .setDeviceId(DEVICE_ID) - .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H)) - .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() - val BACK_GESTURE_EVENT = KeyGestureEvent.Builder() - .setDeviceId(DEVICE_ID) - .setKeycodes(intArrayOf(KeyEvent.KEYCODE_DEL)) - .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build() + val HOME_GESTURE_EVENT = + KeyGestureEvent.Builder() + .setDeviceId(DEVICE_ID) + .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H)) + .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build() + val BACK_GESTURE_EVENT = + KeyGestureEvent.Builder() + .setDeviceId(DEVICE_ID) + .setKeycodes(intArrayOf(KeyEvent.KEYCODE_DEL)) + .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build() } - @get:Rule - val rule = SetFlagsRule() - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val rule = SetFlagsRule() + @get:Rule val inputManagerRule = MockInputManagerRule() private var registeredListener: IKeyGestureHandler? = null private lateinit var context: Context @@ -76,31 +75,38 @@ class KeyGestureEventHandlerTest { fun setUp() { context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext())) inputManager = InputManager(context) - `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))) - .thenReturn(inputManager) + `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager) // Handle key gesture handler registration. doAnswer { - val listener = it.getArgument(1) as IKeyGestureHandler - if (registeredListener != null && - registeredListener!!.asBinder() != listener.asBinder()) { - // There can only be one registered key gesture handler per process. - fail("Trying to register a new listener when one already exists") + val listener = it.getArgument(1) as IKeyGestureHandler + if ( + registeredListener != null && + registeredListener!!.asBinder() != listener.asBinder() + ) { + // There can only be one registered key gesture handler per process. + fail("Trying to register a new listener when one already exists") + } + registeredListener = listener + null } - registeredListener = listener - null - }.`when`(inputManagerRule.mock).registerKeyGestureHandler(Mockito.any(), Mockito.any()) + .`when`(inputManagerRule.mock) + .registerKeyGestureHandler(Mockito.any(), Mockito.any()) // Handle key gesture handler being unregistered. doAnswer { - val listener = it.getArgument(0) as IKeyGestureHandler - if (registeredListener == null || - registeredListener!!.asBinder() != listener.asBinder()) { - fail("Trying to unregister a listener that is not registered") + val listener = it.getArgument(0) as IKeyGestureHandler + if ( + registeredListener == null || + registeredListener!!.asBinder() != listener.asBinder() + ) { + fail("Trying to unregister a listener that is not registered") + } + registeredListener = null + null } - registeredListener = null - null - }.`when`(inputManagerRule.mock).unregisterKeyGestureHandler(Mockito.any()) + .`when`(inputManagerRule.mock) + .unregisterKeyGestureHandler(Mockito.any()) } private fun handleKeyGestureEvent(event: KeyGestureEvent) { @@ -143,7 +149,7 @@ class KeyGestureEventHandlerTest { // Adding the handler should register the callback with InputManagerService. inputManager.registerKeyGestureEventHandler( listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), - callback1 + callback1, ) assertNotNull(registeredListener) @@ -151,7 +157,7 @@ class KeyGestureEventHandlerTest { val currListener = registeredListener inputManager.registerKeyGestureEventHandler( listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK), - callback2 + callback2, ) assertEquals(currListener, registeredListener) } @@ -164,11 +170,11 @@ class KeyGestureEventHandlerTest { inputManager.registerKeyGestureEventHandler( listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), - callback1 + callback1, ) inputManager.registerKeyGestureEventHandler( listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK), - callback2 + callback2, ) // Only removing all handlers should remove the internal callback @@ -184,24 +190,26 @@ class KeyGestureEventHandlerTest { var callbackCount1 = 0 var callbackCount2 = 0 // Handler 1 captures all home gestures - val callback1 = InputManager.KeyGestureEventHandler { event, _ -> - callbackCount1++ - assertEquals(KeyGestureEvent.KEY_GESTURE_TYPE_HOME, event.keyGestureType) - } + val callback1 = + InputManager.KeyGestureEventHandler { event, _ -> + callbackCount1++ + assertEquals(KeyGestureEvent.KEY_GESTURE_TYPE_HOME, event.keyGestureType) + } // Handler 2 captures all back gestures - val callback2 = InputManager.KeyGestureEventHandler { event, _ -> - callbackCount2++ - assertEquals(KeyGestureEvent.KEY_GESTURE_TYPE_BACK, event.keyGestureType) - } + val callback2 = + InputManager.KeyGestureEventHandler { event, _ -> + callbackCount2++ + assertEquals(KeyGestureEvent.KEY_GESTURE_TYPE_BACK, event.keyGestureType) + } // Add both key gesture event handlers inputManager.registerKeyGestureEventHandler( listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), - callback1 + callback1, ) inputManager.registerKeyGestureEventHandler( listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK), - callback2 + callback2, ) // Request handling for home key gesture event, should notify only callback1 @@ -228,12 +236,13 @@ class KeyGestureEventHandlerTest { inputManager.registerKeyGestureEventHandler( listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), - handler + handler, ) assertThrows(IllegalArgumentException::class.java) { inputManager.registerKeyGestureEventHandler( - listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK), handler + listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK), + handler, ) } } @@ -245,12 +254,13 @@ class KeyGestureEventHandlerTest { inputManager.registerKeyGestureEventHandler( listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), - handler1 + handler1, ) assertThrows(IllegalArgumentException::class.java) { inputManager.registerKeyGestureEventHandler( - listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), handler2 + listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), + handler2, ) } } diff --git a/tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt b/tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt index cf0bfcc4f6df..bf3a9c389c7e 100644 --- a/tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt +++ b/tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt @@ -43,8 +43,7 @@ import org.mockito.junit.MockitoJUnitRunner /** * Tests for [InputManager.KeyGestureEventListener]. * - * Build/Install/Run: - * atest InputTests:KeyGestureEventListenerTest + * Build/Install/Run: atest InputTests:KeyGestureEventListenerTest */ @Presubmit @RunWith(MockitoJUnitRunner::class) @@ -52,18 +51,17 @@ class KeyGestureEventListenerTest { companion object { const val DEVICE_ID = 1 - val HOME_GESTURE_EVENT = KeyGestureEvent.Builder() - .setDeviceId(DEVICE_ID) - .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H)) - .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() + val HOME_GESTURE_EVENT = + KeyGestureEvent.Builder() + .setDeviceId(DEVICE_ID) + .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H)) + .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build() } - @get:Rule - val rule = SetFlagsRule() - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val rule = SetFlagsRule() + @get:Rule val inputManagerRule = MockInputManagerRule() private val testLooper = TestLooper() private val executor = HandlerExecutor(Handler(testLooper.looper)) @@ -75,31 +73,38 @@ class KeyGestureEventListenerTest { fun setUp() { context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext())) inputManager = InputManager(context) - `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))) - .thenReturn(inputManager) + `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager) // Handle key gesture event listener registration. doAnswer { - val listener = it.getArgument(0) as IKeyGestureEventListener - if (registeredListener != null && - registeredListener!!.asBinder() != listener.asBinder()) { - // There can only be one registered key gesture event listener per process. - fail("Trying to register a new listener when one already exists") + val listener = it.getArgument(0) as IKeyGestureEventListener + if ( + registeredListener != null && + registeredListener!!.asBinder() != listener.asBinder() + ) { + // There can only be one registered key gesture event listener per process. + fail("Trying to register a new listener when one already exists") + } + registeredListener = listener + null } - registeredListener = listener - null - }.`when`(inputManagerRule.mock).registerKeyGestureEventListener(any()) + .`when`(inputManagerRule.mock) + .registerKeyGestureEventListener(any()) // Handle key gesture event listener being unregistered. doAnswer { - val listener = it.getArgument(0) as IKeyGestureEventListener - if (registeredListener == null || - registeredListener!!.asBinder() != listener.asBinder()) { - fail("Trying to unregister a listener that is not registered") + val listener = it.getArgument(0) as IKeyGestureEventListener + if ( + registeredListener == null || + registeredListener!!.asBinder() != listener.asBinder() + ) { + fail("Trying to unregister a listener that is not registered") + } + registeredListener = null + null } - registeredListener = null - null - }.`when`(inputManagerRule.mock).unregisterKeyGestureEventListener(any()) + .`when`(inputManagerRule.mock) + .unregisterKeyGestureEventListener(any()) } private fun notifyKeyGestureEvent(event: KeyGestureEvent) { @@ -119,8 +124,7 @@ class KeyGestureEventListenerTest { var callbackCount = 0 // Add a key gesture event listener - inputManager.registerKeyGestureEventListener(executor) { - event: KeyGestureEvent -> + inputManager.registerKeyGestureEventListener(executor) { event: KeyGestureEvent -> assertEquals(HOME_GESTURE_EVENT, event) callbackCount++ } diff --git a/tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt b/tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt index d25dee1d402c..9e419439fba4 100644 --- a/tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt +++ b/tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt @@ -42,15 +42,13 @@ import org.mockito.junit.MockitoJUnitRunner /** * Tests for [InputManager.KeyboardBacklightListener]. * - * Build/Install/Run: - * atest InputTests:KeyboardBacklightListenerTest + * Build/Install/Run: atest InputTests:KeyboardBacklightListenerTest */ @Presubmit @RunWith(MockitoJUnitRunner::class) class KeyboardBacklightListenerTest { - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val inputManagerRule = MockInputManagerRule() private lateinit var testLooper: TestLooper private var registeredListener: IKeyboardBacklightListener? = null @@ -65,43 +63,54 @@ class KeyboardBacklightListenerTest { executor = HandlerExecutor(Handler(testLooper.looper)) registeredListener = null inputManager = InputManager(context) - `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))) - .thenReturn(inputManager) + `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager) // Handle keyboard backlight listener registration. doAnswer { - val listener = it.getArgument(0) as IKeyboardBacklightListener - if (registeredListener != null && - registeredListener!!.asBinder() != listener.asBinder()) { - // There can only be one registered keyboard backlight listener per process. - fail("Trying to register a new listener when one already exists") + val listener = it.getArgument(0) as IKeyboardBacklightListener + if ( + registeredListener != null && + registeredListener!!.asBinder() != listener.asBinder() + ) { + // There can only be one registered keyboard backlight listener per process. + fail("Trying to register a new listener when one already exists") + } + registeredListener = listener + null } - registeredListener = listener - null - }.`when`(inputManagerRule.mock).registerKeyboardBacklightListener(any()) + .`when`(inputManagerRule.mock) + .registerKeyboardBacklightListener(any()) // Handle keyboard backlight listener being unregistered. doAnswer { - val listener = it.getArgument(0) as IKeyboardBacklightListener - if (registeredListener == null || - registeredListener!!.asBinder() != listener.asBinder()) { - fail("Trying to unregister a listener that is not registered") + val listener = it.getArgument(0) as IKeyboardBacklightListener + if ( + registeredListener == null || + registeredListener!!.asBinder() != listener.asBinder() + ) { + fail("Trying to unregister a listener that is not registered") + } + registeredListener = null + null } - registeredListener = null - null - }.`when`(inputManagerRule.mock).unregisterKeyboardBacklightListener(any()) + .`when`(inputManagerRule.mock) + .unregisterKeyboardBacklightListener(any()) } private fun notifyKeyboardBacklightChanged( deviceId: Int, brightnessLevel: Int, maxBrightnessLevel: Int = 10, - isTriggeredByKeyPress: Boolean = true + isTriggeredByKeyPress: Boolean = true, ) { - registeredListener!!.onBrightnessChanged(deviceId, IKeyboardBacklightState().apply { - this.brightnessLevel = brightnessLevel - this.maxBrightnessLevel = maxBrightnessLevel - }, isTriggeredByKeyPress) + registeredListener!!.onBrightnessChanged( + deviceId, + IKeyboardBacklightState().apply { + this.brightnessLevel = brightnessLevel + this.maxBrightnessLevel = maxBrightnessLevel + }, + isTriggeredByKeyPress, + ) } @Test @@ -110,9 +119,9 @@ class KeyboardBacklightListenerTest { // Add a keyboard backlight listener inputManager.registerKeyboardBacklightListener(executor) { - deviceId: Int, - keyboardBacklightState: KeyboardBacklightState, - isTriggeredByKeyPress: Boolean -> + deviceId: Int, + keyboardBacklightState: KeyboardBacklightState, + isTriggeredByKeyPress: Boolean -> callbackCount++ assertEquals(1, deviceId) assertEquals(2, keyboardBacklightState.brightnessLevel) diff --git a/tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt b/tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt index bcff2fcfca93..a59cbaf5fd55 100644 --- a/tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt +++ b/tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt @@ -28,8 +28,7 @@ import org.mockito.junit.MockitoJUnitRunner /** * Tests for Keyboard layout preview * - * Build/Install/Run: - * atest InputTests:KeyboardLayoutPreviewTests + * Build/Install/Run: atest InputTests:KeyboardLayoutPreviewTests */ @Presubmit @RunWith(MockitoJUnitRunner::class) @@ -52,4 +51,4 @@ class KeyboardLayoutPreviewTests { assertEquals(WIDTH, drawable.intrinsicWidth) assertEquals(HEIGHT, drawable.intrinsicHeight) } -}
\ No newline at end of file +} diff --git a/tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt b/tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt index cc58bbc38e2d..620cb015911e 100644 --- a/tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt +++ b/tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt @@ -43,15 +43,13 @@ import org.mockito.junit.MockitoJUnitRunner /** * Tests for [InputManager.StickyModifierStateListener]. * - * Build/Install/Run: - * atest InputTests:StickyModifierStateListenerTest + * Build/Install/Run: atest InputTests:StickyModifierStateListenerTest */ @Presubmit @RunWith(MockitoJUnitRunner::class) class StickyModifierStateListenerTest { - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val inputManagerRule = MockInputManagerRule() private val testLooper = TestLooper() private val executor = HandlerExecutor(Handler(testLooper.looper)) @@ -63,31 +61,38 @@ class StickyModifierStateListenerTest { fun setUp() { context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext())) inputManager = InputManager(context) - `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))) - .thenReturn(inputManager) + `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager) // Handle sticky modifier state listener registration. doAnswer { - val listener = it.getArgument(0) as IStickyModifierStateListener - if (registeredListener != null && - registeredListener!!.asBinder() != listener.asBinder()) { - // There can only be one registered sticky modifier state listener per process. - fail("Trying to register a new listener when one already exists") + val listener = it.getArgument(0) as IStickyModifierStateListener + if ( + registeredListener != null && + registeredListener!!.asBinder() != listener.asBinder() + ) { + // There can only be one registered sticky modifier state listener per process. + fail("Trying to register a new listener when one already exists") + } + registeredListener = listener + null } - registeredListener = listener - null - }.`when`(inputManagerRule.mock).registerStickyModifierStateListener(any()) + .`when`(inputManagerRule.mock) + .registerStickyModifierStateListener(any()) // Handle sticky modifier state listener being unregistered. doAnswer { - val listener = it.getArgument(0) as IStickyModifierStateListener - if (registeredListener == null || - registeredListener!!.asBinder() != listener.asBinder()) { - fail("Trying to unregister a listener that is not registered") + val listener = it.getArgument(0) as IStickyModifierStateListener + if ( + registeredListener == null || + registeredListener!!.asBinder() != listener.asBinder() + ) { + fail("Trying to unregister a listener that is not registered") + } + registeredListener = null + null } - registeredListener = null - null - }.`when`(inputManagerRule.mock).unregisterStickyModifierStateListener(any()) + .`when`(inputManagerRule.mock) + .unregisterStickyModifierStateListener(any()) } private fun notifyStickyModifierStateChanged(modifierState: Int, lockedModifierState: Int) { @@ -99,9 +104,7 @@ class StickyModifierStateListenerTest { var callbackCount = 0 // Add a sticky modifier state listener - inputManager.registerStickyModifierStateListener(executor) { - callbackCount++ - } + inputManager.registerStickyModifierStateListener(executor) { callbackCount++ } // Notifying sticky modifier state change will notify the listener. notifyStickyModifierStateChanged(0, 0) @@ -112,8 +115,7 @@ class StickyModifierStateListenerTest { @Test fun testListenerHasCorrectModifierStateNotified() { // Add a sticky modifier state listener - inputManager.registerStickyModifierStateListener(executor) { - state: StickyModifierState -> + inputManager.registerStickyModifierStateListener(executor) { state: StickyModifierState -> assertTrue(state.isAltModifierOn) assertTrue(state.isAltModifierLocked) assertTrue(state.isShiftModifierOn) @@ -128,9 +130,11 @@ class StickyModifierStateListenerTest { // Notifying sticky modifier state change will notify the listener. notifyStickyModifierStateChanged( - KeyEvent.META_ALT_ON or KeyEvent.META_ALT_LEFT_ON or - KeyEvent.META_SHIFT_ON or KeyEvent.META_SHIFT_LEFT_ON, - KeyEvent.META_ALT_ON or KeyEvent.META_ALT_LEFT_ON + KeyEvent.META_ALT_ON or + KeyEvent.META_ALT_LEFT_ON or + KeyEvent.META_SHIFT_ON or + KeyEvent.META_SHIFT_LEFT_ON, + KeyEvent.META_ALT_ON or KeyEvent.META_ALT_LEFT_ON, ) testLooper.dispatchNext() } diff --git a/tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt b/tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt index ad481dff810c..075a3ab8cc73 100644 --- a/tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt +++ b/tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt @@ -54,8 +54,7 @@ import org.mockito.junit.MockitoJUnit /** * Tests for {@link AmbientKeyboardBacklightController}. * - * Build/Install/Run: - * atest InputTests:AmbientKeyboardBacklightControllerTests + * Build/Install/Run: atest InputTests:AmbientKeyboardBacklightControllerTests */ @Presubmit class AmbientKeyboardBacklightControllerTests { @@ -66,24 +65,19 @@ class AmbientKeyboardBacklightControllerTests { const val SENSOR_TYPE = "test_sensor_type" } - @get:Rule - val rule = MockitoJUnit.rule()!! + @get:Rule val rule = MockitoJUnit.rule()!! private lateinit var context: Context private lateinit var testLooper: TestLooper private lateinit var ambientController: AmbientKeyboardBacklightController - @Mock - private lateinit var resources: Resources + @Mock private lateinit var resources: Resources - @Mock - private lateinit var lightSensorInfo: InputSensorInfo + @Mock private lateinit var lightSensorInfo: InputSensorInfo - @Mock - private lateinit var sensorManager: SensorManager + @Mock private lateinit var sensorManager: SensorManager - @Mock - private lateinit var displayManagerInternal: DisplayManagerInternal + @Mock private lateinit var displayManagerInternal: DisplayManagerInternal private lateinit var lightSensor: Sensor private var currentDisplayInfo = DisplayInfo() @@ -114,26 +108,26 @@ class AmbientKeyboardBacklightControllerTests { `when`(resources.getIntArray(R.array.config_autoKeyboardBacklightIncreaseLuxThreshold)) .thenReturn(increaseThresholds) `when`( - resources.getValue( - eq(R.dimen.config_autoKeyboardBrightnessSmoothingConstant), - any(TypedValue::class.java), - anyBoolean() + resources.getValue( + eq(R.dimen.config_autoKeyboardBrightnessSmoothingConstant), + any(TypedValue::class.java), + anyBoolean(), + ) ) - ).then { - val args = it.arguments - val outValue = args[1] as TypedValue - outValue.data = java.lang.Float.floatToRawIntBits(1.0f) - Unit - } + .then { + val args = it.arguments + val outValue = args[1] as TypedValue + outValue.data = java.lang.Float.floatToRawIntBits(1.0f) + Unit + } } private fun setupSensor() { LocalServices.removeServiceForTest(DisplayManagerInternal::class.java) LocalServices.addService(DisplayManagerInternal::class.java, displayManagerInternal) currentDisplayInfo.uniqueId = DEFAULT_DISPLAY_UNIQUE_ID - `when`(displayManagerInternal.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn( - currentDisplayInfo - ) + `when`(displayManagerInternal.getDisplayInfo(Display.DEFAULT_DISPLAY)) + .thenReturn(currentDisplayInfo) val sensorData = DisplayManagerInternal.AmbientLightSensorData(SENSOR_NAME, SENSOR_TYPE) `when`(displayManagerInternal.getAmbientLightSensorData(Display.DEFAULT_DISPLAY)) .thenReturn(sensorData) @@ -144,26 +138,28 @@ class AmbientKeyboardBacklightControllerTests { `when`(context.getSystemService(eq(Context.SENSOR_SERVICE))).thenReturn(sensorManager) `when`(sensorManager.getSensorList(anyInt())).thenReturn(listOf(lightSensor)) `when`( - sensorManager.registerListener( - any(), - eq(lightSensor), - anyInt(), - any(Handler::class.java) + sensorManager.registerListener( + any(), + eq(lightSensor), + anyInt(), + any(Handler::class.java), + ) ) - ).then { - listenerRegistered = true - listenerRegistrationCount++ - true - } + .then { + listenerRegistered = true + listenerRegistrationCount++ + true + } `when`( - sensorManager.unregisterListener( - any(SensorEventListener::class.java), - eq(lightSensor) + sensorManager.unregisterListener( + any(SensorEventListener::class.java), + eq(lightSensor), + ) ) - ).then { - listenerRegistered = false - Unit - } + .then { + listenerRegistered = false + Unit + } } private fun setupSensorWithInitialLux(luxValue: Float) { @@ -181,7 +177,7 @@ class AmbientKeyboardBacklightControllerTests { assertEquals( "Should receive immediate callback for first lux change", 100, - lastBrightnessCallback + lastBrightnessCallback, ) } @@ -190,15 +186,13 @@ class AmbientKeyboardBacklightControllerTests { setupSensorWithInitialLux(500F) // Current state: Step 1 [value = 100, increaseThreshold = 1000, decreaseThreshold = -1] - repeat(HYSTERESIS_THRESHOLD) { - sendAmbientLuxValue(1500F) - } + repeat(HYSTERESIS_THRESHOLD) { sendAmbientLuxValue(1500F) } testLooper.dispatchAll() assertEquals( "Should receive brightness change callback for increasing lux change", 200, - lastBrightnessCallback + lastBrightnessCallback, ) } @@ -207,39 +201,31 @@ class AmbientKeyboardBacklightControllerTests { setupSensorWithInitialLux(1500F) // Current state: Step 2 [value = 200, increaseThreshold = 2000, decreaseThreshold = 900] - repeat(HYSTERESIS_THRESHOLD) { - sendAmbientLuxValue(500F) - } + repeat(HYSTERESIS_THRESHOLD) { sendAmbientLuxValue(500F) } testLooper.dispatchAll() assertEquals( "Should receive brightness change callback for decreasing lux change", 100, - lastBrightnessCallback + lastBrightnessCallback, ) } @Test fun testRegisterAmbientListener_throwsExceptionOnRegisteringDuplicate() { - val ambientListener = - AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener { } + val ambientListener = AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener {} ambientController.registerAmbientBacklightListener(ambientListener) assertThrows(IllegalStateException::class.java) { - ambientController.registerAmbientBacklightListener( - ambientListener - ) + ambientController.registerAmbientBacklightListener(ambientListener) } } @Test fun testUnregisterAmbientListener_throwsExceptionOnUnregisteringNonExistent() { - val ambientListener = - AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener { } + val ambientListener = AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener {} assertThrows(IllegalStateException::class.java) { - ambientController.unregisterAmbientBacklightListener( - ambientListener - ) + ambientController.unregisterAmbientBacklightListener(ambientListener) } } @@ -248,25 +234,23 @@ class AmbientKeyboardBacklightControllerTests { assertEquals( "Should not have a sensor listener registered at init", 0, - listenerRegistrationCount + listenerRegistrationCount, ) assertFalse("Should not have a sensor listener registered at init", listenerRegistered) val ambientListener1 = - AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener { } + AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener {} ambientController.registerAmbientBacklightListener(ambientListener1) - assertEquals( - "Should register a new sensor listener", 1, listenerRegistrationCount - ) + assertEquals("Should register a new sensor listener", 1, listenerRegistrationCount) assertTrue("Should have sensor listener registered", listenerRegistered) val ambientListener2 = - AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener { } + AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener {} ambientController.registerAmbientBacklightListener(ambientListener2) assertEquals( "Should not register a new sensor listener when adding a second ambient listener", 1, - listenerRegistrationCount + listenerRegistrationCount, ) assertTrue("Should have sensor listener registered", listenerRegistered) @@ -276,7 +260,7 @@ class AmbientKeyboardBacklightControllerTests { ambientController.unregisterAmbientBacklightListener(ambientListener2) assertFalse( "Should not have sensor listener registered if there are no ambient listeners", - listenerRegistered + listenerRegistered, ) } @@ -291,7 +275,7 @@ class AmbientKeyboardBacklightControllerTests { assertEquals( "Should not re-register listener on display change if unique is same", count, - listenerRegistrationCount + listenerRegistrationCount, ) } @@ -307,7 +291,7 @@ class AmbientKeyboardBacklightControllerTests { assertEquals( "Should re-register listener on display change if unique id changed", count + 1, - listenerRegistrationCount + listenerRegistrationCount, ) } @@ -318,15 +302,13 @@ class AmbientKeyboardBacklightControllerTests { // Previous state: Step 1 [value = 100, increaseThreshold = 1000, decreaseThreshold = -1] // Current state: Step 2 [value = 200, increaseThreshold = 2000, decreaseThreshold = 900] lastBrightnessCallback = -1 - repeat(HYSTERESIS_THRESHOLD) { - sendAmbientLuxValue(999F) - } + repeat(HYSTERESIS_THRESHOLD) { sendAmbientLuxValue(999F) } testLooper.dispatchAll() assertEquals( "Should not receive any callback for brightness change", -1, - lastBrightnessCallback + lastBrightnessCallback, ) } @@ -337,15 +319,13 @@ class AmbientKeyboardBacklightControllerTests { // Previous state: Step 1 [value = 100, increaseThreshold = 1000, decreaseThreshold = -1] // Current state: Step 2 [value = 200, increaseThreshold = 2000, decreaseThreshold = 900] lastBrightnessCallback = -1 - repeat(HYSTERESIS_THRESHOLD - 1) { - sendAmbientLuxValue(2001F) - } + repeat(HYSTERESIS_THRESHOLD - 1) { sendAmbientLuxValue(2001F) } testLooper.dispatchAll() assertEquals( "Should not receive any callback for brightness change", -1, - lastBrightnessCallback + lastBrightnessCallback, ) } diff --git a/tests/Input/src/com/android/server/input/BatteryControllerTests.kt b/tests/Input/src/com/android/server/input/BatteryControllerTests.kt index 890c346ea015..bcb740652dde 100644 --- a/tests/Input/src/com/android/server/input/BatteryControllerTests.kt +++ b/tests/Input/src/com/android/server/input/BatteryControllerTests.kt @@ -92,7 +92,7 @@ private fun createInputDevice( private fun <T, U> memberMatcher( member: String, memberProvider: (T) -> U, - match: Matcher<U> + match: Matcher<U>, ): TypeSafeMatcher<T> = object : TypeSafeMatcher<T>() { @@ -115,12 +115,13 @@ private fun matchesState( isPresent: Boolean = true, status: Int? = null, capacity: Float? = null, - eventTime: Long? = null + eventTime: Long? = null, ): Matcher<IInputDeviceBatteryState> { - val batteryStateMatchers = mutableListOf<Matcher<IInputDeviceBatteryState>>( - memberMatcher("deviceId", { it.deviceId }, equalTo(deviceId)), - memberMatcher("isPresent", { it.isPresent }, equalTo(isPresent)) - ) + val batteryStateMatchers = + mutableListOf<Matcher<IInputDeviceBatteryState>>( + memberMatcher("deviceId", { it.deviceId }, equalTo(deviceId)), + memberMatcher("isPresent", { it.isPresent }, equalTo(isPresent)), + ) if (eventTime != null) { batteryStateMatchers.add(memberMatcher("updateTime", { it.updateTime }, equalTo(eventTime))) } @@ -143,14 +144,14 @@ private fun IInputDeviceBatteryListener.verifyNotified( isPresent: Boolean = true, status: Int? = null, capacity: Float? = null, - eventTime: Long? = null + eventTime: Long? = null, ) { verifyNotified(matchesState(deviceId, isPresent, status, capacity, eventTime), mode) } private fun IInputDeviceBatteryListener.verifyNotified( matcher: Matcher<IInputDeviceBatteryState>, - mode: VerificationMode = times(1) + mode: VerificationMode = times(1), ) { verify(this, mode).onBatteryStateChanged(MockitoHamcrest.argThat(matcher)) } @@ -165,8 +166,7 @@ private fun createMockListener(): IInputDeviceBatteryListener { /** * Tests for {@link InputDeviceBatteryController}. * - * Build/Install/Run: - * atest InputTests:InputDeviceBatteryControllerTests + * Build/Install/Run: atest InputTests:InputDeviceBatteryControllerTests */ @Presubmit class BatteryControllerTests { @@ -181,19 +181,13 @@ class BatteryControllerTests { const val TIMESTAMP = 123456789L } - @get:Rule - val rule = MockitoJUnit.rule()!! - @get:Rule - val context = TestableContext(ApplicationProvider.getApplicationContext()) - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val rule = MockitoJUnit.rule()!! + @get:Rule val context = TestableContext(ApplicationProvider.getApplicationContext()) + @get:Rule val inputManagerRule = MockInputManagerRule() - @Mock - private lateinit var native: NativeInputManagerService - @Mock - private lateinit var uEventManager: UEventManager - @Mock - private lateinit var bluetoothBatteryManager: BluetoothBatteryManager + @Mock private lateinit var native: NativeInputManagerService + @Mock private lateinit var uEventManager: UEventManager + @Mock private lateinit var bluetoothBatteryManager: BluetoothBatteryManager private lateinit var batteryController: BatteryController private lateinit var testLooper: TestLooper @@ -206,14 +200,18 @@ class BatteryControllerTests { testLooper = TestLooper() val inputManager = InputManager(context) context.addMockSystemService(InputManager::class.java, inputManager) - `when`(inputManagerRule.mock.inputDeviceIds).then { - deviceGenerationMap.keys.toIntArray() - } + `when`(inputManagerRule.mock.inputDeviceIds).then { deviceGenerationMap.keys.toIntArray() } addInputDevice(DEVICE_ID) addInputDevice(SECOND_DEVICE_ID) - batteryController = BatteryController(context, native, testLooper.looper, uEventManager, - bluetoothBatteryManager) + batteryController = + BatteryController( + context, + native, + testLooper.looper, + uEventManager, + bluetoothBatteryManager, + ) batteryController.systemRunning() val listenerCaptor = ArgumentCaptor.forClass(IInputDevicesChangedListener::class.java) verify(inputManagerRule.mock).registerInputDevicesChangedListener(listenerCaptor.capture()) @@ -222,12 +220,13 @@ class BatteryControllerTests { } private fun notifyDeviceChanged( - deviceId: Int, + deviceId: Int, hasBattery: Boolean = true, - supportsUsi: Boolean = false + supportsUsi: Boolean = false, ) { - val generation = deviceGenerationMap[deviceId]?.plus(1) - ?: throw IllegalArgumentException("Device $deviceId was never added!") + val generation = + deviceGenerationMap[deviceId]?.plus(1) + ?: throw IllegalArgumentException("Device $deviceId was never added!") deviceGenerationMap[deviceId] = generation `when`(inputManagerRule.mock.getInputDevice(deviceId)) @@ -239,7 +238,7 @@ class BatteryControllerTests { } private fun addInputDevice( - deviceId: Int, + deviceId: Int, hasBattery: Boolean = true, supportsUsi: Boolean = false, ) { @@ -248,8 +247,10 @@ class BatteryControllerTests { } private fun createBluetoothDevice(address: String): BluetoothDevice { - return context.getSystemService(BluetoothManager::class.java)!! - .adapter.getRemoteDevice(address) + return context + .getSystemService(BluetoothManager::class.java)!! + .adapter + .getRemoteDevice(address) } @Test @@ -279,8 +280,7 @@ class BatteryControllerTests { try { batteryController.registerBatteryListener(DEVICE_ID, listener2, PID) fail("Expected security exception when registering more than one listener per process") - } catch (ignored: SecurityException) { - } + } catch (ignored: SecurityException) {} } @Test @@ -323,15 +323,18 @@ class BatteryControllerTests { batteryController.registerBatteryListener(DEVICE_ID, listener, PID) // The device paths for UEvent notifications do not include the "/sys" prefix, so verify // that the added listener is configured to match the path without that prefix. - verify(uEventManager) - .addListener(uEventListener.capture(), eq("DEVPATH=/dev/test/device1")) + verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/test/device1")) listener.verifyNotified(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.78f) // If the battery state has changed when an UEvent is sent, the listeners are notified. `when`(native.getBatteryCapacity(DEVICE_ID)).thenReturn(80) uEventListener.value!!.onBatteryUEvent(TIMESTAMP) - listener.verifyNotified(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.80f, - eventTime = TIMESTAMP) + listener.verifyNotified( + DEVICE_ID, + status = STATUS_CHARGING, + capacity = 0.80f, + eventTime = TIMESTAMP, + ) // If the battery state has not changed when an UEvent is sent, the listeners are not // notified. @@ -341,8 +344,11 @@ class BatteryControllerTests { batteryController.unregisterBatteryListener(DEVICE_ID, listener, PID) verify(uEventManager).removeListener(uEventListener.capture()) - assertEquals("The same observer must be registered and unregistered", - uEventListener.allValues[0], uEventListener.allValues[1]) + assertEquals( + "The same observer must be registered and unregistered", + uEventListener.allValues[0], + uEventListener.allValues[1], + ) } @Test @@ -366,8 +372,12 @@ class BatteryControllerTests { // If the battery becomes present again, the listener is notified. notifyDeviceChanged(DEVICE_ID, hasBattery = true) testLooper.dispatchNext() - listener.verifyNotified(DEVICE_ID, mode = times(2), status = STATUS_CHARGING, - capacity = 0.78f) + listener.verifyNotified( + DEVICE_ID, + mode = times(2), + status = STATUS_CHARGING, + capacity = 0.78f, + ) // Ensure that a new UEventListener was added. verify(uEventManager, times(2)) .addListener(uEventListener.capture(), eq("DEVPATH=/test/device1")) @@ -437,8 +447,11 @@ class BatteryControllerTests { `when`(native.getBatteryStatus(DEVICE_ID)).thenReturn(STATUS_CHARGING) `when`(native.getBatteryCapacity(DEVICE_ID)).thenReturn(78) val batteryState = batteryController.getBatteryState(DEVICE_ID) - assertThat("battery state matches", batteryState, - matchesState(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.78f)) + assertThat( + "battery state matches", + batteryState, + matchesState(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.78f), + ) } @Test @@ -453,8 +466,11 @@ class BatteryControllerTests { // change in the battery state, the listener is also notified. `when`(native.getBatteryCapacity(DEVICE_ID)).thenReturn(80) val batteryState = batteryController.getBatteryState(DEVICE_ID) - assertThat("battery matches state", batteryState, - matchesState(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.80f)) + assertThat( + "battery matches state", + batteryState, + matchesState(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.80f), + ) listener.verifyNotified(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.80f) } @@ -466,8 +482,7 @@ class BatteryControllerTests { // Even though there is no listener added for this device, it is being monitored. val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java) - verify(uEventManager) - .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) + verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) // Add and remove a listener for the device. val listener = createMockListener() @@ -507,8 +522,7 @@ class BatteryControllerTests { addInputDevice(USI_DEVICE_ID, supportsUsi = true) testLooper.dispatchNext() val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java) - verify(uEventManager) - .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) + verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) // A USI device's battery state is not valid until the first UEvent notification. // Add a listener, and ensure it is notified that the battery state is not present. @@ -517,34 +531,49 @@ class BatteryControllerTests { listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID)) // Ensure that querying for battery state also returns the same invalid result. - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - isInvalidBatteryState(USI_DEVICE_ID)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + isInvalidBatteryState(USI_DEVICE_ID), + ) // There is a UEvent signaling a battery change. The battery state is now valid. uEventListener.value!!.onBatteryUEvent(TIMESTAMP) listener.verifyNotified(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f), + ) // There is another UEvent notification. The battery state is now updated. `when`(native.getBatteryCapacity(USI_DEVICE_ID)).thenReturn(64) uEventListener.value!!.onBatteryUEvent(TIMESTAMP + 1) listener.verifyNotified(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f), + ) // The battery state is still valid after a millisecond. testLooper.moveTimeForward(1) testLooper.dispatchAll() - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f), + ) // The battery is no longer present after the timeout expires. testLooper.moveTimeForward(USI_BATTERY_VALIDITY_DURATION_MILLIS - 1) testLooper.dispatchNext() listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID), times(2)) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - isInvalidBatteryState(USI_DEVICE_ID)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + isInvalidBatteryState(USI_DEVICE_ID), + ) } @Test @@ -556,16 +585,18 @@ class BatteryControllerTests { addInputDevice(USI_DEVICE_ID, supportsUsi = true) testLooper.dispatchNext() val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java) - verify(uEventManager) - .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) + verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) // There is a UEvent signaling a battery change. The battery state is now valid. uEventListener.value!!.onBatteryUEvent(TIMESTAMP) val listener = createMockListener() batteryController.registerBatteryListener(USI_DEVICE_ID, listener, PID) listener.verifyNotified(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f), + ) // Stylus presence is detected before the validity timeout expires. testLooper.moveTimeForward(100) @@ -575,15 +606,21 @@ class BatteryControllerTests { // Ensure that timeout was extended, and the battery state is now valid for longer. testLooper.moveTimeForward(USI_BATTERY_VALIDITY_DURATION_MILLIS - 100) testLooper.dispatchAll() - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f), + ) // Ensure the validity period expires after the expected amount of time. testLooper.moveTimeForward(100) testLooper.dispatchNext() listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID)) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - isInvalidBatteryState(USI_DEVICE_ID)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + isInvalidBatteryState(USI_DEVICE_ID), + ) } @Test @@ -595,22 +632,27 @@ class BatteryControllerTests { addInputDevice(USI_DEVICE_ID, supportsUsi = true) testLooper.dispatchNext() val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java) - verify(uEventManager) - .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) + verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) // The USI battery state is initially invalid. val listener = createMockListener() batteryController.registerBatteryListener(USI_DEVICE_ID, listener, PID) listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID)) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - isInvalidBatteryState(USI_DEVICE_ID)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + isInvalidBatteryState(USI_DEVICE_ID), + ) // A stylus presence is detected. This validates the battery state. batteryController.notifyStylusGestureStarted(USI_DEVICE_ID, TIMESTAMP) listener.verifyNotified(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f), + ) } @Test @@ -623,27 +665,35 @@ class BatteryControllerTests { addInputDevice(USI_DEVICE_ID, supportsUsi = true) testLooper.dispatchNext() val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java) - verify(uEventManager) - .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) + verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device")) // The USI battery state is initially invalid. val listener = createMockListener() batteryController.registerBatteryListener(USI_DEVICE_ID, listener, PID) listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID)) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - isInvalidBatteryState(USI_DEVICE_ID)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + isInvalidBatteryState(USI_DEVICE_ID), + ) // Since the capacity reported is 0, stylus presence does not validate the battery state. batteryController.notifyStylusGestureStarted(USI_DEVICE_ID, TIMESTAMP) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - isInvalidBatteryState(USI_DEVICE_ID)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + isInvalidBatteryState(USI_DEVICE_ID), + ) // However, if a UEvent reports a battery capacity of 0, the battery state is now valid. uEventListener.value!!.onBatteryUEvent(TIMESTAMP) listener.verifyNotified(USI_DEVICE_ID, status = STATUS_UNKNOWN, capacity = 0f) - assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID), - matchesState(USI_DEVICE_ID, status = STATUS_UNKNOWN, capacity = 0f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(USI_DEVICE_ID), + matchesState(USI_DEVICE_ID, status = STATUS_UNKNOWN, capacity = 0f), + ) } @Test @@ -722,15 +772,21 @@ class BatteryControllerTests { verify(bluetoothBatteryManager).addBatteryListener(bluetoothListener.capture()) verify(uEventManager).addListener(uEventListener.capture(), any()) listener.verifyNotified(BT_DEVICE_ID, capacity = 0.21f) - assertThat("battery state matches", batteryController.getBatteryState(BT_DEVICE_ID), - matchesState(BT_DEVICE_ID, capacity = 0.21f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(BT_DEVICE_ID), + matchesState(BT_DEVICE_ID, capacity = 0.21f), + ) // If only the native battery state changes the listener is not notified. `when`(native.getBatteryCapacity(BT_DEVICE_ID)).thenReturn(97) uEventListener.value!!.onBatteryUEvent(TIMESTAMP) listener.verifyNotified(BT_DEVICE_ID, mode = times(1), capacity = 0.21f) - assertThat("battery state matches", batteryController.getBatteryState(BT_DEVICE_ID), - matchesState(BT_DEVICE_ID, capacity = 0.21f)) + assertThat( + "battery state matches", + batteryController.getBatteryState(BT_DEVICE_ID), + matchesState(BT_DEVICE_ID, capacity = 0.21f), + ) } @Test @@ -751,8 +807,11 @@ class BatteryControllerTests { listener.verifyNotified(BT_DEVICE_ID, capacity = 0.21f) // Fall back to the native state when BT is off. - bluetoothListener.value!!.onBluetoothBatteryChanged(TIMESTAMP, "AA:BB:CC:DD:EE:FF", - BluetoothDevice.BATTERY_LEVEL_BLUETOOTH_OFF) + bluetoothListener.value!!.onBluetoothBatteryChanged( + TIMESTAMP, + "AA:BB:CC:DD:EE:FF", + BluetoothDevice.BATTERY_LEVEL_BLUETOOTH_OFF, + ) listener.verifyNotified(BT_DEVICE_ID, capacity = 0.98f) bluetoothListener.value!!.onBluetoothBatteryChanged(TIMESTAMP, "AA:BB:CC:DD:EE:FF", 22) @@ -760,8 +819,11 @@ class BatteryControllerTests { listener.verifyNotified(BT_DEVICE_ID, capacity = 0.22f) // Fall back to the native state when BT battery is unknown. - bluetoothListener.value!!.onBluetoothBatteryChanged(TIMESTAMP, "AA:BB:CC:DD:EE:FF", - BluetoothDevice.BATTERY_LEVEL_UNKNOWN) + bluetoothListener.value!!.onBluetoothBatteryChanged( + TIMESTAMP, + "AA:BB:CC:DD:EE:FF", + BluetoothDevice.BATTERY_LEVEL_UNKNOWN, + ) listener.verifyNotified(BT_DEVICE_ID, mode = times(2), capacity = 0.98f) } @@ -782,10 +844,10 @@ class BatteryControllerTests { batteryController.registerBatteryListener(DEVICE_ID, listener, PID) verify(bluetoothBatteryManager, never()).addMetadataListener(any(), any()) - val metadataListener1 = ArgumentCaptor.forClass( - BluetoothAdapter.OnMetadataChangedListener::class.java) - val metadataListener2 = ArgumentCaptor.forClass( - BluetoothAdapter.OnMetadataChangedListener::class.java) + val metadataListener1 = + ArgumentCaptor.forClass(BluetoothAdapter.OnMetadataChangedListener::class.java) + val metadataListener2 = + ArgumentCaptor.forClass(BluetoothAdapter.OnMetadataChangedListener::class.java) // The metadata listener is added when the first BT input device is monitored. batteryController.registerBatteryListener(BT_DEVICE_ID, listener, PID) @@ -814,12 +876,16 @@ class BatteryControllerTests { fun testNotifiesBluetoothMetadataBatteryChanges() { `when`(inputManagerRule.mock.getInputDeviceBluetoothAddress(BT_DEVICE_ID)) .thenReturn("AA:BB:CC:DD:EE:FF") - `when`(bluetoothBatteryManager.getMetadata("AA:BB:CC:DD:EE:FF", - BluetoothDevice.METADATA_MAIN_BATTERY)) + `when`( + bluetoothBatteryManager.getMetadata( + "AA:BB:CC:DD:EE:FF", + BluetoothDevice.METADATA_MAIN_BATTERY, + ) + ) .thenReturn("21".toByteArray()) addInputDevice(BT_DEVICE_ID) - val metadataListener = ArgumentCaptor.forClass( - BluetoothAdapter.OnMetadataChangedListener::class.java) + val metadataListener = + ArgumentCaptor.forClass(BluetoothAdapter.OnMetadataChangedListener::class.java) val listener = createMockListener() val bluetoothDevice = createBluetoothDevice("AA:BB:CC:DD:EE:FF") batteryController.registerBatteryListener(BT_DEVICE_ID, listener, PID) @@ -829,25 +895,44 @@ class BatteryControllerTests { // When the state has not changed, the listener is not notified again. metadataListener.value!!.onMetadataChanged( - bluetoothDevice, BluetoothDevice.METADATA_MAIN_BATTERY, "21".toByteArray()) + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_BATTERY, + "21".toByteArray(), + ) listener.verifyNotified(BT_DEVICE_ID, mode = times(1), capacity = 0.21f) metadataListener.value!!.onMetadataChanged( - bluetoothDevice, BluetoothDevice.METADATA_MAIN_BATTERY, "25".toByteArray()) + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_BATTERY, + "25".toByteArray(), + ) listener.verifyNotified(BT_DEVICE_ID, capacity = 0.25f, status = STATUS_UNKNOWN) metadataListener.value!!.onMetadataChanged( - bluetoothDevice, BluetoothDevice.METADATA_MAIN_CHARGING, "true".toByteArray()) + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_CHARGING, + "true".toByteArray(), + ) listener.verifyNotified(BT_DEVICE_ID, capacity = 0.25f, status = STATUS_CHARGING) metadataListener.value!!.onMetadataChanged( - bluetoothDevice, BluetoothDevice.METADATA_MAIN_CHARGING, "false".toByteArray()) + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_CHARGING, + "false".toByteArray(), + ) listener.verifyNotified(BT_DEVICE_ID, capacity = 0.25f, status = STATUS_DISCHARGING) metadataListener.value!!.onMetadataChanged( - bluetoothDevice, BluetoothDevice.METADATA_MAIN_CHARGING, null) - listener.verifyNotified(BT_DEVICE_ID, mode = times(2), capacity = 0.25f, - status = STATUS_UNKNOWN) + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_CHARGING, + null, + ) + listener.verifyNotified( + BT_DEVICE_ID, + mode = times(2), + capacity = 0.25f, + status = STATUS_UNKNOWN, + ) } @Test @@ -855,13 +940,17 @@ class BatteryControllerTests { `when`(inputManagerRule.mock.getInputDeviceBluetoothAddress(BT_DEVICE_ID)) .thenReturn("AA:BB:CC:DD:EE:FF") `when`(bluetoothBatteryManager.getBatteryLevel(eq("AA:BB:CC:DD:EE:FF"))).thenReturn(21) - `when`(bluetoothBatteryManager.getMetadata("AA:BB:CC:DD:EE:FF", - BluetoothDevice.METADATA_MAIN_BATTERY)) + `when`( + bluetoothBatteryManager.getMetadata( + "AA:BB:CC:DD:EE:FF", + BluetoothDevice.METADATA_MAIN_BATTERY, + ) + ) .thenReturn("22".toByteArray()) addInputDevice(BT_DEVICE_ID) val bluetoothListener = ArgumentCaptor.forClass(BluetoothBatteryListener::class.java) - val metadataListener = ArgumentCaptor.forClass( - BluetoothAdapter.OnMetadataChangedListener::class.java) + val metadataListener = + ArgumentCaptor.forClass(BluetoothAdapter.OnMetadataChangedListener::class.java) val listener = createMockListener() val bluetoothDevice = createBluetoothDevice("AA:BB:CC:DD:EE:FF") batteryController.registerBatteryListener(BT_DEVICE_ID, listener, PID) @@ -877,13 +966,19 @@ class BatteryControllerTests { listener.verifyNotified(BT_DEVICE_ID, mode = never(), capacity = 0.23f) metadataListener.value!!.onMetadataChanged( - bluetoothDevice, BluetoothDevice.METADATA_MAIN_BATTERY, "24".toByteArray()) + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_BATTERY, + "24".toByteArray(), + ) listener.verifyNotified(BT_DEVICE_ID, capacity = 0.24f) // When the battery level from the metadata is no longer valid, we fall back to using the // Bluetooth battery level. metadataListener.value!!.onMetadataChanged( - bluetoothDevice, BluetoothDevice.METADATA_MAIN_BATTERY, null) + bluetoothDevice, + BluetoothDevice.METADATA_MAIN_BATTERY, + null, + ) listener.verifyNotified(BT_DEVICE_ID, capacity = 0.23f) } } diff --git a/tests/Input/src/com/android/server/input/InputDataStoreTests.kt b/tests/Input/src/com/android/server/input/InputDataStoreTests.kt index 78c828bafd8f..812bd608ed20 100644 --- a/tests/Input/src/com/android/server/input/InputDataStoreTests.kt +++ b/tests/Input/src/com/android/server/input/InputDataStoreTests.kt @@ -41,8 +41,7 @@ import org.mockito.Mockito /** * Tests for {@link InputDataStore}. * - * Build/Install/Run: - * atest InputTests:InputDataStoreTests + * Build/Install/Run: atest InputTests:InputDataStoreTests */ @Presubmit class InputDataStoreTests { @@ -63,25 +62,32 @@ class InputDataStoreTests { private fun setupInputDataStore() { tempFile = File.createTempFile("input_gestures", ".xml") - inputDataStore = InputDataStore(object : InputDataStore.FileInjector("input_gestures") { - private val atomicFile: AtomicFile = AtomicFile(tempFile) + inputDataStore = + InputDataStore( + object : InputDataStore.FileInjector("input_gestures") { + private val atomicFile: AtomicFile = AtomicFile(tempFile) - override fun openRead(userId: Int): InputStream? { - return atomicFile.openRead() - } + override fun openRead(userId: Int): InputStream? { + return atomicFile.openRead() + } - override fun startWrite(userId: Int): FileOutputStream? { - return atomicFile.startWrite() - } + override fun startWrite(userId: Int): FileOutputStream? { + return atomicFile.startWrite() + } - override fun finishWrite(userId: Int, fos: FileOutputStream?, success: Boolean) { - if (success) { - atomicFile.finishWrite(fos) - } else { - atomicFile.failWrite(fos) + override fun finishWrite( + userId: Int, + fos: FileOutputStream?, + success: Boolean, + ) { + if (success) { + atomicFile.finishWrite(fos) + } else { + atomicFile.failWrite(fos) + } + } } - } - }) + ) } private fun getPrintableXml(inputGestures: List<InputGestureData>): String { @@ -92,164 +98,157 @@ class InputDataStoreTests { @Test fun saveToDiskKeyGesturesOnly() { - val inputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_H, - KeyEvent.META_META_ON + val inputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_1, - KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger( + KeyEvent.KEYCODE_1, + KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_2, - KeyEvent.META_META_ON + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) - .build() - ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) + .build(), + ) inputDataStore.saveInputGestures(USER_ID, inputGestures) assertEquals( inputGestures, inputDataStore.loadInputGestures(USER_ID), - getPrintableXml(inputGestures) + getPrintableXml(inputGestures), ) } @Test fun saveToDiskTouchpadGestures() { - val inputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createTouchpadTrigger( - InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + val inputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createTouchpadTrigger( + InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() - ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build() + ) inputDataStore.saveInputGestures(USER_ID, inputGestures) assertEquals( inputGestures, inputDataStore.loadInputGestures(USER_ID), - getPrintableXml(inputGestures) + getPrintableXml(inputGestures), ) } @Test fun saveToDiskAppLaunchGestures() { - val inputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createTouchpadTrigger( - InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + val inputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createTouchpadTrigger( + InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION) - .setAppLaunchData(AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_2, - KeyEvent.META_META_ON + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION) + .setAppLaunchData( + AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION) - .setAppLaunchData(AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_1, - KeyEvent.META_META_ON + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION) - .setAppLaunchData( - AppLaunchData.createLaunchDataForComponent( - "com.test", - "com.test.BookmarkTest" + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION) + .setAppLaunchData( + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS) ) - ) - .build() - ) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_1, KeyEvent.META_META_ON) + ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION) + .setAppLaunchData( + AppLaunchData.createLaunchDataForComponent( + "com.test", + "com.test.BookmarkTest", + ) + ) + .build(), + ) inputDataStore.saveInputGestures(USER_ID, inputGestures) assertEquals( inputGestures, inputDataStore.loadInputGestures(USER_ID), - getPrintableXml(inputGestures) + getPrintableXml(inputGestures), ) } @Test fun saveToDiskCombinedGestures() { - val inputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_1, - KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON + val inputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger( + KeyEvent.KEYCODE_1, + KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_2, - KeyEvent.META_META_ON + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createTouchpadTrigger( - InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createTouchpadTrigger( + InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_9, - KeyEvent.META_META_ON + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_9, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION) - .setAppLaunchData(AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)) - .build(), - ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION) + .setAppLaunchData( + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS) + ) + .build(), + ) inputDataStore.saveInputGestures(USER_ID, inputGestures) assertEquals( inputGestures, inputDataStore.loadInputGestures(USER_ID), - getPrintableXml(inputGestures) + getPrintableXml(inputGestures), ) } @Test fun validXmlParse() { - val xmlData = """ + val xmlData = + """ <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <root> <input_gesture_list> @@ -263,45 +262,42 @@ class InputDataStoreTests { <touchpad_trigger touchpad_gesture_type="1" /> </input_gesture> </input_gesture_list> - </root>""".trimIndent() - val validInputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_1, - KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON + </root>""" + .trimIndent() + val validInputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger( + KeyEvent.KEYCODE_1, + KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_2, - KeyEvent.META_META_ON + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createTouchpadTrigger( - InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createTouchpadTrigger( + InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() - ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build(), + ) val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8)) - assertEquals( - validInputGestures, - inputDataStore.readInputGesturesXml(inputStream, true) - ) + assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true)) } @Test fun missingTriggerData() { - val xmlData = """ + val xmlData = + """ <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <root> <input_gesture_list> @@ -314,36 +310,33 @@ class InputDataStoreTests { <touchpad_trigger touchpad_gesture_type="1" /> </input_gesture> </input_gesture_list> - </root>""".trimIndent() - val validInputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_2, - KeyEvent.META_META_ON + </root>""" + .trimIndent() + val validInputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createTouchpadTrigger( - InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createTouchpadTrigger( + InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() - ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build(), + ) val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8)) - assertEquals( - validInputGestures, - inputDataStore.readInputGesturesXml(inputStream, true) - ) + assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true)) } @Test fun invalidKeycode() { - val xmlData = """ + val xmlData = + """ <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <root> <input_gesture_list> @@ -357,36 +350,36 @@ class InputDataStoreTests { <touchpad_trigger touchpad_gesture_type="1" /> </input_gesture> </input_gesture_list> - </root>""".trimIndent() - val validInputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_1, - KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON + </root>""" + .trimIndent() + val validInputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger( + KeyEvent.KEYCODE_1, + KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createTouchpadTrigger( - InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createTouchpadTrigger( + InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() - ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build(), + ) val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8)) - assertEquals( - validInputGestures, - inputDataStore.readInputGesturesXml(inputStream, true) - ) + assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true)) } @Test fun invalidTriggerName() { - val xmlData = """ + val xmlData = + """ <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <root> <input_gesture_list> @@ -400,37 +393,34 @@ class InputDataStoreTests { <invalid_trigger_name touchpad_gesture_type="1" /> </input_gesture> </input_gesture_list> - </root>""".trimIndent() - val validInputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_1, - KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON + </root>""" + .trimIndent() + val validInputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger( + KeyEvent.KEYCODE_1, + KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_2, - KeyEvent.META_META_ON + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) - .build(), - ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) + .build(), + ) val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8)) - assertEquals( - validInputGestures, - inputDataStore.readInputGesturesXml(inputStream, true) - ) + assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true)) } @Test fun invalidTouchpadGestureType() { - val xmlData = """ + val xmlData = + """ <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <root> <input_gesture_list> @@ -444,61 +434,55 @@ class InputDataStoreTests { <touchpad_trigger touchpad_gesture_type="9999" /> </input_gesture> </input_gesture_list> - </root>""".trimIndent() - val validInputGestures = listOf( - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_1, - KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON + </root>""" + .trimIndent() + val validInputGestures = + listOf( + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger( + KeyEvent.KEYCODE_1, + KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build(), - InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_2, - KeyEvent.META_META_ON + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build(), + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) - .build(), - ) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS) + .build(), + ) val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8)) - assertEquals( - validInputGestures, - inputDataStore.readInputGesturesXml(inputStream, true) - ) + assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true)) } @Test fun emptyInputGestureList() { - val xmlData = """ + val xmlData = + """ <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <root> <input_gesture_list> </input_gesture_list> - </root>""".trimIndent() + </root>""" + .trimIndent() val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8)) - assertEquals( - listOf(), - inputDataStore.readInputGesturesXml(inputStream, true) - ) + assertEquals(listOf(), inputDataStore.readInputGesturesXml(inputStream, true)) } @Test fun invalidTag() { - val xmlData = """ + val xmlData = + """ <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <root> <invalid_tag_name> </invalid_tag_name> - </root>""".trimIndent() + </root>""" + .trimIndent() val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8)) - assertEquals( - listOf(), - inputDataStore.readInputGesturesXml(inputStream, true) - ) + assertEquals(listOf(), inputDataStore.readInputGesturesXml(inputStream, true)) } -}
\ No newline at end of file +} diff --git a/tests/Input/src/com/android/server/input/InputGestureManagerTests.kt b/tests/Input/src/com/android/server/input/InputGestureManagerTests.kt index e281a3fb1287..5b4a39b49146 100644 --- a/tests/Input/src/com/android/server/input/InputGestureManagerTests.kt +++ b/tests/Input/src/com/android/server/input/InputGestureManagerTests.kt @@ -29,8 +29,7 @@ import org.junit.Test /** * Tests for custom keyboard glyph map configuration. * - * Build/Install/Run: - * atest InputTests:CustomInputGestureManagerTests + * Build/Install/Run: atest InputTests:CustomInputGestureManagerTests */ @Presubmit class InputGestureManagerTests { @@ -48,163 +47,144 @@ class InputGestureManagerTests { @Test fun addRemoveCustomGesture() { - val customGesture = InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_H, - KeyEvent.META_META_ON + val customGesture = + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build() val result = inputGestureManager.addCustomInputGesture(USER_ID, customGesture) assertEquals(InputManager.CUSTOM_INPUT_GESTURE_RESULT_SUCCESS, result) assertEquals( listOf(customGesture), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) inputGestureManager.removeCustomInputGesture(USER_ID, customGesture) assertEquals( listOf<InputGestureData>(), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) } @Test fun removeNonExistentGesture() { - val customGesture = InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_H, - KeyEvent.META_META_ON + val customGesture = + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build() val result = inputGestureManager.removeCustomInputGesture(USER_ID, customGesture) assertEquals(InputManager.CUSTOM_INPUT_GESTURE_RESULT_ERROR_DOES_NOT_EXIST, result) assertEquals( listOf<InputGestureData>(), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) } @Test fun addAlreadyExistentGesture() { - val customGesture = InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_H, - KeyEvent.META_META_ON + val customGesture = + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build() inputGestureManager.addCustomInputGesture(USER_ID, customGesture) - val customGesture2 = InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_H, - KeyEvent.META_META_ON + val customGesture2 = + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build() + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build() val result = inputGestureManager.addCustomInputGesture(USER_ID, customGesture2) assertEquals(InputManager.CUSTOM_INPUT_GESTURE_RESULT_ERROR_ALREADY_EXISTS, result) assertEquals( listOf(customGesture), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) } @Test fun addRemoveAllExistentGestures() { - val customGesture = InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_H, - KeyEvent.META_META_ON + val customGesture = + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build() inputGestureManager.addCustomInputGesture(USER_ID, customGesture) - val customGesture2 = InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_DEL, - KeyEvent.META_META_ON + val customGesture2 = + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_DEL, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build() + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build() inputGestureManager.addCustomInputGesture(USER_ID, customGesture2) assertEquals( listOf(customGesture, customGesture2), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) - inputGestureManager.removeAllCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.removeAllCustomInputGestures(USER_ID, /* filter= */ null) assertEquals( listOf<InputGestureData>(), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) } @Test fun filteringBasedOnTouchpadOrKeyGestures() { - val customKeyGesture = InputGestureData.Builder() - .setTrigger( - InputGestureData.createKeyTrigger( - KeyEvent.KEYCODE_H, - KeyEvent.META_META_ON + val customKeyGesture = + InputGestureData.Builder() + .setTrigger( + InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .build() + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .build() inputGestureManager.addCustomInputGesture(USER_ID, customKeyGesture) - val customTouchpadGesture = InputGestureData.Builder() - .setTrigger( - InputGestureData.createTouchpadTrigger( - InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + val customTouchpadGesture = + InputGestureData.Builder() + .setTrigger( + InputGestureData.createTouchpadTrigger( + InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP + ) ) - ) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) - .build() + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK) + .build() inputGestureManager.addCustomInputGesture(USER_ID, customTouchpadGesture) assertEquals( listOf(customTouchpadGesture, customKeyGesture), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) assertEquals( listOf(customKeyGesture), - inputGestureManager.getCustomInputGestures(USER_ID, InputGestureData.Filter.KEY) + inputGestureManager.getCustomInputGestures(USER_ID, InputGestureData.Filter.KEY), ) assertEquals( listOf(customTouchpadGesture), - inputGestureManager.getCustomInputGestures( - USER_ID, - InputGestureData.Filter.TOUCHPAD - ) + inputGestureManager.getCustomInputGestures(USER_ID, InputGestureData.Filter.TOUCHPAD), ) inputGestureManager.removeAllCustomInputGestures(USER_ID, InputGestureData.Filter.KEY) assertEquals( listOf(customTouchpadGesture), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) - inputGestureManager.removeAllCustomInputGestures( - USER_ID, - InputGestureData.Filter.TOUCHPAD - ) + inputGestureManager.removeAllCustomInputGestures(USER_ID, InputGestureData.Filter.TOUCHPAD) assertEquals( listOf<InputGestureData>(), - inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null) + inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null), ) } -}
\ No newline at end of file +} diff --git a/tests/Input/src/com/android/server/input/InputManagerServiceTests.kt b/tests/Input/src/com/android/server/input/InputManagerServiceTests.kt index 71c7a6b1119d..4737d19acde1 100644 --- a/tests/Input/src/com/android/server/input/InputManagerServiceTests.kt +++ b/tests/Input/src/com/android/server/input/InputManagerServiceTests.kt @@ -16,7 +16,6 @@ package com.android.server.input - import android.Manifest import android.content.Context import android.content.ContextWrapper @@ -39,14 +38,14 @@ import android.platform.test.annotations.EnableFlags import android.platform.test.annotations.Presubmit import android.platform.test.flag.junit.SetFlagsRule import android.provider.Settings -import android.view.View.OnKeyListener +import android.test.mock.MockContentResolver import android.view.InputDevice import android.view.KeyCharacterMap import android.view.KeyEvent import android.view.SurfaceHolder import android.view.SurfaceView +import android.view.View.OnKeyListener import android.view.WindowManager -import android.test.mock.MockContentResolver import androidx.test.platform.app.InstrumentationRegistry import com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity import com.android.dx.mockito.inline.extended.ExtendedMockito @@ -75,28 +74,33 @@ import org.mockito.Mockito.never import org.mockito.Mockito.spy import org.mockito.Mockito.times import org.mockito.Mockito.verify -import org.mockito.Mockito.verifyNoMoreInteractions import org.mockito.Mockito.verifyNoInteractions +import org.mockito.Mockito.verifyNoMoreInteractions import org.mockito.Mockito.`when` import org.mockito.stubbing.OngoingStubbing /** * Tests for {@link InputManagerService}. * - * Build/Install/Run: - * atest InputTests:InputManagerServiceTests + * Build/Install/Run: atest InputTests:InputManagerServiceTests */ @Presubmit class InputManagerServiceTests { companion object { - val ACTION_KEY_EVENTS = listOf( - KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_META_LEFT), - KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_META_RIGHT), - KeyEvent( /* downTime= */0, /* eventTime= */0, /* action= */0, /* code= */0, - /* repeat= */0, KeyEvent.META_META_ON + val ACTION_KEY_EVENTS = + listOf( + KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_META_LEFT), + KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_META_RIGHT), + KeyEvent( + /* downTime= */ 0, + /* eventTime= */ 0, + /* action= */ 0, + /* code= */ 0, + /* repeat= */ 0, + KeyEvent.META_META_ON, + ), ) - ) } @get:Rule @@ -108,32 +112,24 @@ class InputManagerServiceTests { .mockStatic(InputSettings::class.java) .build()!! - @get:Rule - val setFlagsRule = SetFlagsRule() + @get:Rule val setFlagsRule = SetFlagsRule() - @get:Rule - val fakeSettingsProviderRule = FakeSettingsProvider.rule()!! + @get:Rule val fakeSettingsProviderRule = FakeSettingsProvider.rule()!! - @Mock - private lateinit var native: NativeInputManagerService + @Mock private lateinit var native: NativeInputManagerService - @Mock - private lateinit var wmCallbacks: InputManagerService.WindowManagerCallbacks + @Mock private lateinit var wmCallbacks: InputManagerService.WindowManagerCallbacks - @Mock - private lateinit var windowManagerInternal: WindowManagerInternal + @Mock private lateinit var windowManagerInternal: WindowManagerInternal - @Mock - private lateinit var packageManagerInternal: PackageManagerInternal + @Mock private lateinit var packageManagerInternal: PackageManagerInternal - @Mock - private lateinit var uEventManager: UEventManager + @Mock private lateinit var uEventManager: UEventManager @Mock private lateinit var kbdController: InputManagerService.KeyboardBacklightControllerInterface - @Mock - private lateinit var kcm: KeyCharacterMap + @Mock private lateinit var kcm: KeyCharacterMap private lateinit var service: InputManagerService private lateinit var localService: InputManagerInternal @@ -147,44 +143,50 @@ class InputManagerServiceTests { fun setup() { context = spy(ContextWrapper(InstrumentationRegistry.getInstrumentation().getContext())) fakePermissionEnforcer = FakePermissionEnforcer() - doReturn(Context.PERMISSION_ENFORCER_SERVICE).`when`(context).getSystemServiceName( - eq(PermissionEnforcer::class.java) - ) - doReturn(fakePermissionEnforcer).`when`(context).getSystemService( - eq(Context.PERMISSION_ENFORCER_SERVICE) - ) + doReturn(Context.PERMISSION_ENFORCER_SERVICE) + .`when`(context) + .getSystemServiceName(eq(PermissionEnforcer::class.java)) + doReturn(fakePermissionEnforcer) + .`when`(context) + .getSystemService(eq(Context.PERMISSION_ENFORCER_SERVICE)) contentResolver = MockContentResolver(context) contentResolver.addProvider(Settings.AUTHORITY, FakeSettingsProvider()) whenever(context.contentResolver).thenReturn(contentResolver) testLooper = TestLooper() service = - InputManagerService(object : InputManagerService.Injector( - context, testLooper.looper, testLooper.looper, uEventManager) { - override fun getNativeService( - service: InputManagerService? - ): NativeInputManagerService { - return native - } - - override fun registerLocalService(service: InputManagerInternal?) { - localService = service!! - } - - override fun getKeyboardBacklightController( - nativeService: NativeInputManagerService? - ): InputManagerService.KeyboardBacklightControllerInterface { - return kbdController - } - }, fakePermissionEnforcer) + InputManagerService( + object : + InputManagerService.Injector( + context, + testLooper.looper, + testLooper.looper, + uEventManager, + ) { + override fun getNativeService( + service: InputManagerService? + ): NativeInputManagerService { + return native + } + + override fun registerLocalService(service: InputManagerInternal?) { + localService = service!! + } + + override fun getKeyboardBacklightController( + nativeService: NativeInputManagerService? + ): InputManagerService.KeyboardBacklightControllerInterface { + return kbdController + } + }, + fakePermissionEnforcer, + ) inputManagerGlobalSession = InputManagerGlobal.createTestSession(service) val inputManager = InputManager(context) whenever(context.getSystemService(InputManager::class.java)).thenReturn(inputManager) whenever(context.getSystemService(Context.INPUT_SERVICE)).thenReturn(inputManager) whenever(context.checkCallingOrSelfPermission(Manifest.permission.MANAGE_KEY_GESTURES)) - .thenReturn( - PackageManager.PERMISSION_GRANTED - ) + .thenReturn(PackageManager.PERMISSION_GRANTED) ExtendedMockito.doReturn(windowManagerInternal).`when` { LocalServices.getService(eq(WindowManagerInternal::class.java)) @@ -192,9 +194,7 @@ class InputManagerServiceTests { ExtendedMockito.doReturn(packageManagerInternal).`when` { LocalServices.getService(eq(PackageManagerInternal::class.java)) } - ExtendedMockito.doReturn(kcm).`when` { - KeyCharacterMap.load(anyInt()) - } + ExtendedMockito.doReturn(kcm).`when` { KeyCharacterMap.load(anyInt()) } assertTrue("Local service must be registered", this::localService.isInitialized) service.setWindowManagerCallbacks(wmCallbacks) @@ -219,9 +219,7 @@ class InputManagerServiceTests { fun testInputSettingsUpdatedOnSystemRunning() { verifyNoInteractions(native) - runWithShellPermissionIdentity { - service.systemRunning() - } + runWithShellPermissionIdentity { service.systemRunning() } verify(native).setPointerSpeed(anyInt()) verify(native).setTouchpadPointerSpeed(anyInt()) @@ -238,8 +236,7 @@ class InputManagerServiceTests { verify(native).setStylusPointerIconEnabled(anyBoolean()) // Called thrice at boot, since there are individual callbacks to update the // key repeat timeout, the key repeat delay and whether key repeat enabled. - verify(native, times(3)).setKeyRepeatConfiguration(anyInt(), anyInt(), - anyBoolean()) + verify(native, times(3)).setKeyRepeatConfiguration(anyInt(), anyInt(), anyBoolean()) } @Test @@ -259,7 +256,9 @@ class InputManagerServiceTests { localService.setTypeAssociation(inputPort, type) - assertThat(service.getDeviceTypeAssociations()).asList().containsExactly(inputPort, type) + assertThat(service.getDeviceTypeAssociations()) + .asList() + .containsExactly(inputPort, type) .inOrder() } @@ -290,8 +289,8 @@ class InputManagerServiceTests { fun testActionKeyEventsForwardedToFocusedWindow_whenCorrectlyRequested() { service.systemRunning() overrideSendActionKeyEventsToFocusedWindow( - /* hasPermission = */true, - /* hasPrivateFlag = */true + /* hasPermission = */ true, + /* hasPrivateFlag = */ true, ) whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(-1) @@ -304,8 +303,8 @@ class InputManagerServiceTests { fun testActionKeyEventsNotForwardedToFocusedWindow_whenNoPermissions() { service.systemRunning() overrideSendActionKeyEventsToFocusedWindow( - /* hasPermission = */false, - /* hasPrivateFlag = */true + /* hasPermission = */ false, + /* hasPrivateFlag = */ true, ) whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(-1) @@ -318,8 +317,8 @@ class InputManagerServiceTests { fun testActionKeyEventsNotForwardedToFocusedWindow_whenNoPrivateFlag() { service.systemRunning() overrideSendActionKeyEventsToFocusedWindow( - /* hasPermission = */true, - /* hasPrivateFlag = */false + /* hasPermission = */ true, + /* hasPrivateFlag = */ false, ) whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(-1) @@ -362,13 +361,20 @@ class InputManagerServiceTests { fun testKeyEventsForwardedToFocusedWindow_whenWmAllows() { service.systemRunning() overrideSendActionKeyEventsToFocusedWindow( - /* hasPermission = */false, - /* hasPrivateFlag = */false + /* hasPermission = */ false, + /* hasPrivateFlag = */ false, ) whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(0) - val event = KeyEvent( /* downTime= */0, /* eventTime= */0, KeyEvent.ACTION_DOWN, - KeyEvent.KEYCODE_SPACE, /* repeat= */0, KeyEvent.META_CTRL_ON) + val event = + KeyEvent( + /* downTime= */ 0, + /* eventTime= */ 0, + KeyEvent.ACTION_DOWN, + KeyEvent.KEYCODE_SPACE, + /* repeat= */ 0, + KeyEvent.META_CTRL_ON, + ) assertEquals(0, service.interceptKeyBeforeDispatching(null, event, 0)) } @@ -399,13 +405,20 @@ class InputManagerServiceTests { fun testKeyEventsNotForwardedToFocusedWindow_whenWmConsumes() { service.systemRunning() overrideSendActionKeyEventsToFocusedWindow( - /* hasPermission = */false, - /* hasPrivateFlag = */false + /* hasPermission = */ false, + /* hasPrivateFlag = */ false, ) whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(-1) - val event = KeyEvent( /* downTime= */0, /* eventTime= */0, KeyEvent.ACTION_DOWN, - KeyEvent.KEYCODE_SPACE, /* repeat= */0, KeyEvent.META_CTRL_ON) + val event = + KeyEvent( + /* downTime= */ 0, + /* eventTime= */ 0, + KeyEvent.ACTION_DOWN, + KeyEvent.KEYCODE_SPACE, + /* repeat= */ 0, + KeyEvent.META_CTRL_ON, + ) assertEquals(-1, service.interceptKeyBeforeDispatching(null, event, 0)) } @@ -420,19 +433,20 @@ class InputManagerServiceTests { } private fun createVirtualDisplays(count: Int): AutoClosingVirtualDisplays { - val displayManager: DisplayManager = context.getSystemService( - DisplayManager::class.java - ) as DisplayManager + val displayManager: DisplayManager = + context.getSystemService(DisplayManager::class.java) as DisplayManager val virtualDisplays = mutableListOf<VirtualDisplay>() for (i in 0 until count) { - virtualDisplays.add(displayManager.createVirtualDisplay( + virtualDisplays.add( + displayManager.createVirtualDisplay( /* displayName= */ "testVirtualDisplay$i", /* width= */ 100, /* height= */ 100, /* densityDpi= */ 100, /* surface= */ null, - /* flags= */ 0 - )) + /* flags= */ 0, + ) + ) } return AutoClosingVirtualDisplays(virtualDisplays) } @@ -441,26 +455,26 @@ class InputManagerServiceTests { private fun createKeycodeAEvent(inputDevice: InputDevice, action: Int): KeyEvent { val eventTime = SystemClock.uptimeMillis() return KeyEvent( - /* downTime= */ eventTime, - /* eventTime= */ eventTime, - /* action= */ action, - /* code= */ KeyEvent.KEYCODE_A, - /* repeat= */ 0, - /* metaState= */ 0, - /* deviceId= */ inputDevice.id, - /* scanCode= */ 0, - /* flags= */ KeyEvent.FLAG_FROM_SYSTEM, - /* source= */ InputDevice.SOURCE_KEYBOARD + /* downTime= */ eventTime, + /* eventTime= */ eventTime, + /* action= */ action, + /* code= */ KeyEvent.KEYCODE_A, + /* repeat= */ 0, + /* metaState= */ 0, + /* deviceId= */ inputDevice.id, + /* scanCode= */ 0, + /* flags= */ KeyEvent.FLAG_FROM_SYSTEM, + /* source= */ InputDevice.SOURCE_KEYBOARD, ) } private fun createInputDevice(): InputDevice { return InputDevice.Builder() - .setId(123) - .setName("abc") - .setDescriptor("def") - .setSources(InputDevice.SOURCE_KEYBOARD) - .build() + .setId(123) + .setName("abc") + .setDescriptor("def") + .setSources(InputDevice.SOURCE_KEYBOARD) + .build() } @Test @@ -485,8 +499,8 @@ class InputManagerServiceTests { // Associate input device with display service.addUniqueIdAssociationByDescriptor( - inputDevice.descriptor, - virtualDisplays[0].display.displayId.toString() + inputDevice.descriptor, + virtualDisplays[0].display.displayId.toString(), ) // Simulate 2 different KeyEvents @@ -513,8 +527,8 @@ class InputManagerServiceTests { // Associate with Display 2 service.addUniqueIdAssociationByDescriptor( - inputDevice.descriptor, - virtualDisplays[1].display.displayId.toString() + inputDevice.descriptor, + virtualDisplays[1].display.displayId.toString(), ) // Simulate a KeyEvent @@ -548,8 +562,8 @@ class InputManagerServiceTests { // Associate input device with display service.addUniqueIdAssociationByPort( - inputDevice.name, - virtualDisplays[0].display.displayId.toString() + inputDevice.name, + virtualDisplays[0].display.displayId.toString(), ) // Simulate 2 different KeyEvents @@ -576,8 +590,8 @@ class InputManagerServiceTests { // Associate with Display 2 service.addUniqueIdAssociationByPort( - inputDevice.name, - virtualDisplays[1].display.displayId.toString() + inputDevice.name, + virtualDisplays[1].display.displayId.toString(), ) // Simulate a KeyEvent @@ -619,7 +633,7 @@ class InputManagerServiceTests { ExtendedMockito.verify { InputSettings.setAccessibilityBounceKeysThreshold( any(), - eq(InputSettings.DEFAULT_BOUNCE_KEYS_THRESHOLD_MILLIS) + eq(InputSettings.DEFAULT_BOUNCE_KEYS_THRESHOLD_MILLIS), ) } } @@ -635,9 +649,7 @@ class InputManagerServiceTests { .setAction(KeyGestureEvent.ACTION_GESTURE_COMPLETE) .build() service.handleKeyGestureEvent(toggleMouseKeysEvent) - ExtendedMockito.verify { - InputSettings.setAccessibilityMouseKeysEnabled(any(), eq(true)) - } + ExtendedMockito.verify { InputSettings.setAccessibilityMouseKeysEnabled(any(), eq(true)) } } @Test @@ -648,9 +660,7 @@ class InputManagerServiceTests { .setAction(KeyGestureEvent.ACTION_GESTURE_COMPLETE) .build() service.handleKeyGestureEvent(toggleStickyKeysEvent) - ExtendedMockito.verify { - InputSettings.setAccessibilityStickyKeysEnabled(any(), eq(true)) - } + ExtendedMockito.verify { InputSettings.setAccessibilityStickyKeysEnabled(any(), eq(true)) } } @Test @@ -664,7 +674,7 @@ class InputManagerServiceTests { ExtendedMockito.verify { InputSettings.setAccessibilitySlowKeysThreshold( any(), - eq(InputSettings.DEFAULT_SLOW_KEYS_THRESHOLD_MILLIS) + eq(InputSettings.DEFAULT_SLOW_KEYS_THRESHOLD_MILLIS), ) } } @@ -683,37 +693,39 @@ class InputManagerServiceTests { fun overrideSendActionKeyEventsToFocusedWindow( hasPermission: Boolean, - hasPrivateFlag: Boolean + hasPrivateFlag: Boolean, ) { ExtendedMockito.doReturn( - if (hasPermission) { - PermissionChecker.PERMISSION_GRANTED - } else { - PermissionChecker.PERMISSION_HARD_DENIED - } - ).`when` { - PermissionChecker.checkPermissionForDataDelivery( - any(), - eq(Manifest.permission.OVERRIDE_SYSTEM_KEY_BEHAVIOR_IN_FOCUSED_WINDOW), - anyInt(), - anyInt(), - any(), - any(), - any() + if (hasPermission) { + PermissionChecker.PERMISSION_GRANTED + } else { + PermissionChecker.PERMISSION_HARD_DENIED + } ) - } + .`when` { + PermissionChecker.checkPermissionForDataDelivery( + any(), + eq(Manifest.permission.OVERRIDE_SYSTEM_KEY_BEHAVIOR_IN_FOCUSED_WINDOW), + anyInt(), + anyInt(), + any(), + any(), + any(), + ) + } - val info = KeyInterceptionInfo( - /* type = */0, - if (hasPrivateFlag) { - WindowManager.LayoutParams.PRIVATE_FLAG_ALLOW_ACTION_KEY_EVENTS - } else { - 0 - }, - "title", - /* uid = */0, - /* inputFeatureFlags = */ 0 - ) + val info = + KeyInterceptionInfo( + /* type = */ 0, + if (hasPrivateFlag) { + WindowManager.LayoutParams.PRIVATE_FLAG_ALLOW_ACTION_KEY_EVENTS + } else { + 0 + }, + "title", + /* uid = */ 0, + /* inputFeatureFlags = */ 0, + ) whenever(windowManagerInternal.getKeyInterceptionInfoFromToken(any())).thenReturn(info) } } diff --git a/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt b/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt index 163dda84a71c..c64578e4638f 100644 --- a/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt +++ b/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt @@ -77,8 +77,7 @@ import org.mockito.kotlin.times /** * Tests for {@link KeyGestureController}. * - * Build/Install/Run: - * atest InputTests:KeyGestureControllerTests + * Build/Install/Run: atest InputTests:KeyGestureControllerTests */ @Presubmit @RunWith(JUnitParamsRunner::class) @@ -86,23 +85,29 @@ class KeyGestureControllerTests { companion object { const val DEVICE_ID = 1 - val HOME_GESTURE_COMPLETE_EVENT = KeyGestureEvent.Builder() - .setDeviceId(DEVICE_ID) - .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H)) - .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON) - .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) - .setAction(KeyGestureEvent.ACTION_GESTURE_COMPLETE) - .build() - val MODIFIER = mapOf( - KeyEvent.KEYCODE_CTRL_LEFT to (KeyEvent.META_CTRL_LEFT_ON or KeyEvent.META_CTRL_ON), - KeyEvent.KEYCODE_CTRL_RIGHT to (KeyEvent.META_CTRL_RIGHT_ON or KeyEvent.META_CTRL_ON), - KeyEvent.KEYCODE_ALT_LEFT to (KeyEvent.META_ALT_LEFT_ON or KeyEvent.META_ALT_ON), - KeyEvent.KEYCODE_ALT_RIGHT to (KeyEvent.META_ALT_RIGHT_ON or KeyEvent.META_ALT_ON), - KeyEvent.KEYCODE_SHIFT_LEFT to (KeyEvent.META_SHIFT_LEFT_ON or KeyEvent.META_SHIFT_ON), - KeyEvent.KEYCODE_SHIFT_RIGHT to (KeyEvent.META_SHIFT_RIGHT_ON or KeyEvent.META_SHIFT_ON), - KeyEvent.KEYCODE_META_LEFT to (KeyEvent.META_META_LEFT_ON or KeyEvent.META_META_ON), - KeyEvent.KEYCODE_META_RIGHT to (KeyEvent.META_META_RIGHT_ON or KeyEvent.META_META_ON), - ) + val HOME_GESTURE_COMPLETE_EVENT = + KeyGestureEvent.Builder() + .setDeviceId(DEVICE_ID) + .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H)) + .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON) + .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME) + .setAction(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + .build() + val MODIFIER = + mapOf( + KeyEvent.KEYCODE_CTRL_LEFT to (KeyEvent.META_CTRL_LEFT_ON or KeyEvent.META_CTRL_ON), + KeyEvent.KEYCODE_CTRL_RIGHT to + (KeyEvent.META_CTRL_RIGHT_ON or KeyEvent.META_CTRL_ON), + KeyEvent.KEYCODE_ALT_LEFT to (KeyEvent.META_ALT_LEFT_ON or KeyEvent.META_ALT_ON), + KeyEvent.KEYCODE_ALT_RIGHT to (KeyEvent.META_ALT_RIGHT_ON or KeyEvent.META_ALT_ON), + KeyEvent.KEYCODE_SHIFT_LEFT to + (KeyEvent.META_SHIFT_LEFT_ON or KeyEvent.META_SHIFT_ON), + KeyEvent.KEYCODE_SHIFT_RIGHT to + (KeyEvent.META_SHIFT_RIGHT_ON or KeyEvent.META_SHIFT_ON), + KeyEvent.KEYCODE_META_LEFT to (KeyEvent.META_META_LEFT_ON or KeyEvent.META_META_ON), + KeyEvent.KEYCODE_META_RIGHT to + (KeyEvent.META_META_RIGHT_ON or KeyEvent.META_META_ON), + ) const val SEARCH_KEY_BEHAVIOR_DEFAULT_SEARCH = 0 const val SEARCH_KEY_BEHAVIOR_TARGET_ACTIVITY = 1 const val SETTINGS_KEY_BEHAVIOR_SETTINGS_ACTIVITY = 0 @@ -116,15 +121,14 @@ class KeyGestureControllerTests { @JvmField @Rule - val extendedMockitoRule = ExtendedMockitoRule.Builder(this) - .mockStatic(FrameworkStatsLog::class.java) - .mockStatic(SystemProperties::class.java) - .mockStatic(KeyCharacterMap::class.java) - .build()!! + val extendedMockitoRule = + ExtendedMockitoRule.Builder(this) + .mockStatic(FrameworkStatsLog::class.java) + .mockStatic(SystemProperties::class.java) + .mockStatic(KeyCharacterMap::class.java) + .build()!! - @JvmField - @Rule - val rule = SetFlagsRule() + @JvmField @Rule val rule = SetFlagsRule() @Mock private lateinit var iInputManager: IInputManager @Mock private lateinit var packageManager: PackageManager @@ -151,29 +155,35 @@ class KeyGestureControllerTests { currentPid = Process.myPid() tempFile = File.createTempFile("input_gestures", ".xml") inputDataStore = - InputDataStore(object : InputDataStore.FileInjector("input_gestures.xml") { - private val atomicFile: AtomicFile = AtomicFile(tempFile) + InputDataStore( + object : InputDataStore.FileInjector("input_gestures.xml") { + private val atomicFile: AtomicFile = AtomicFile(tempFile) - override fun openRead(userId: Int): InputStream? { - return atomicFile.openRead() - } + override fun openRead(userId: Int): InputStream? { + return atomicFile.openRead() + } - override fun startWrite(userId: Int): FileOutputStream? { - return atomicFile.startWrite() - } + override fun startWrite(userId: Int): FileOutputStream? { + return atomicFile.startWrite() + } - override fun finishWrite(userId: Int, fos: FileOutputStream?, success: Boolean) { - if (success) { - atomicFile.finishWrite(fos) - } else { - atomicFile.failWrite(fos) + override fun finishWrite( + userId: Int, + fos: FileOutputStream?, + success: Boolean, + ) { + if (success) { + atomicFile.finishWrite(fos) + } else { + atomicFile.failWrite(fos) + } } - } - override fun getAtomicFileForUserId(userId: Int): AtomicFile { - return atomicFile + override fun getAtomicFileForUserId(userId: Int): AtomicFile { + return atomicFile + } } - }) + ) startNewInputGlobalTestSession() } @@ -230,11 +240,12 @@ class KeyGestureControllerTests { object : KeyGestureController.Injector() { override fun getAccessibilityShortcutController( context: Context?, - handler: Handler? + handler: Handler?, ): AccessibilityShortcutController { return accessibilityShortcutController } - }) + }, + ) Mockito.`when`(iInputManager.registerKeyGestureHandler(Mockito.any(), Mockito.any())) .thenAnswer { val args = it.arguments @@ -242,14 +253,18 @@ class KeyGestureControllerTests { keyGestureController.registerKeyGestureHandler( args[0] as IntArray, args[1] as IKeyGestureHandler, - SYSTEM_PID + SYSTEM_PID, ) } - } + } keyGestureController.setWindowManagerCallbacks(wmCallbacks) Mockito.`when`(wmCallbacks.isKeyguardLocked(Mockito.anyInt())).thenReturn(false) - Mockito.`when`(accessibilityShortcutController - .isAccessibilityShortcutAvailable(Mockito.anyBoolean())).thenReturn(true) + Mockito.`when`( + accessibilityShortcutController.isAccessibilityShortcutAvailable( + Mockito.anyBoolean() + ) + ) + .thenReturn(true) Mockito.`when`(iInputManager.appLaunchBookmarks) .thenReturn(keyGestureController.appLaunchBookmarks) keyGestureController.systemRunning() @@ -258,9 +273,10 @@ class KeyGestureControllerTests { private fun notifyHomeGestureCompleted() { keyGestureController.notifyKeyGestureCompleted( - DEVICE_ID, intArrayOf(KeyEvent.KEYCODE_H), + DEVICE_ID, + intArrayOf(KeyEvent.KEYCODE_H), KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON, - KeyGestureEvent.KEY_GESTURE_TYPE_HOME + KeyGestureEvent.KEY_GESTURE_TYPE_HOME, ) } @@ -273,15 +289,11 @@ class KeyGestureControllerTests { keyGestureController.registerKeyGestureEventListener(listener, 0) notifyHomeGestureCompleted() testLooper.dispatchAll() - assertEquals( - "Listener should get callbacks on key gesture event completed", - 1, - events.size - ) + assertEquals("Listener should get callbacks on key gesture event completed", 1, events.size) assertEquals( "Listener should get callback for key gesture complete event", HOME_GESTURE_COMPLETE_EVENT, - events[0] + events[0], ) // Unregister listener @@ -289,11 +301,7 @@ class KeyGestureControllerTests { keyGestureController.unregisterKeyGestureEventListener(listener, 0) notifyHomeGestureCompleted() testLooper.dispatchAll() - assertEquals( - "Listener should not get callback after being unregistered", - 0, - events.size - ) + assertEquals("Listener should not get callback after being unregistered", 0, events.size) } class TestData( @@ -317,7 +325,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_ASSISTANT, intArrayOf(KeyEvent.KEYCODE_A), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + H -> Go Home", @@ -325,7 +333,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_HOME, intArrayOf(KeyEvent.KEYCODE_H), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + ENTER -> Go Home", @@ -333,7 +341,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_HOME, intArrayOf(KeyEvent.KEYCODE_ENTER), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + I -> Launch System Settings", @@ -341,7 +349,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SYSTEM_SETTINGS, intArrayOf(KeyEvent.KEYCODE_I), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + L -> Lock", @@ -349,7 +357,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LOCK_SCREEN, intArrayOf(KeyEvent.KEYCODE_L), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + N -> Toggle Notification", @@ -357,18 +365,15 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL, intArrayOf(KeyEvent.KEYCODE_N), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + S -> Take Screenshot", - intArrayOf( - KeyEvent.KEYCODE_META_LEFT, - KeyEvent.KEYCODE_S - ), + intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_S), KeyGestureEvent.KEY_GESTURE_TYPE_TAKE_SCREENSHOT, intArrayOf(KeyEvent.KEYCODE_S), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + ESC -> Back", @@ -376,7 +381,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_BACK, intArrayOf(KeyEvent.KEYCODE_ESCAPE), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + DPAD_LEFT -> Back", @@ -384,55 +389,55 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_BACK, intArrayOf(KeyEvent.KEYCODE_DPAD_LEFT), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + CTRL + DPAD_UP -> Multi Window Navigation", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_CTRL_LEFT, - KeyEvent.KEYCODE_DPAD_UP + KeyEvent.KEYCODE_DPAD_UP, ), KeyGestureEvent.KEY_GESTURE_TYPE_MULTI_WINDOW_NAVIGATION, intArrayOf(KeyEvent.KEYCODE_DPAD_UP), KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + CTRL + DPAD_DOWN -> Desktop Mode", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_CTRL_LEFT, - KeyEvent.KEYCODE_DPAD_DOWN + KeyEvent.KEYCODE_DPAD_DOWN, ), KeyGestureEvent.KEY_GESTURE_TYPE_DESKTOP_MODE, intArrayOf(KeyEvent.KEYCODE_DPAD_DOWN), KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + CTRL + DPAD_LEFT -> Splitscreen Navigation Left", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_CTRL_LEFT, - KeyEvent.KEYCODE_DPAD_LEFT + KeyEvent.KEYCODE_DPAD_LEFT, ), KeyGestureEvent.KEY_GESTURE_TYPE_SPLIT_SCREEN_NAVIGATION_LEFT, intArrayOf(KeyEvent.KEYCODE_DPAD_LEFT), KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + CTRL + DPAD_RIGHT -> Splitscreen Navigation Right", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_CTRL_LEFT, - KeyEvent.KEYCODE_DPAD_RIGHT + KeyEvent.KEYCODE_DPAD_RIGHT, ), KeyGestureEvent.KEY_GESTURE_TYPE_SPLIT_SCREEN_NAVIGATION_RIGHT, intArrayOf(KeyEvent.KEYCODE_DPAD_RIGHT), KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + / -> Open Shortcut Helper", @@ -440,7 +445,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_OPEN_SHORTCUT_HELPER, intArrayOf(KeyEvent.KEYCODE_SLASH), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + ALT -> Toggle Caps Lock", @@ -448,7 +453,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_CAPS_LOCK, intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "ALT + META -> Toggle Caps Lock", @@ -456,7 +461,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_CAPS_LOCK, intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + TAB -> Open Overview", @@ -464,7 +469,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_RECENT_APPS, intArrayOf(KeyEvent.KEYCODE_TAB), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "ALT + TAB -> Toggle Recent Apps Switcher", @@ -474,8 +479,8 @@ class KeyGestureControllerTests { KeyEvent.META_ALT_ON, intArrayOf( KeyGestureEvent.ACTION_GESTURE_START, - KeyGestureEvent.ACTION_GESTURE_COMPLETE - ) + KeyGestureEvent.ACTION_GESTURE_COMPLETE, + ), ), TestData( "CTRL + SPACE -> Switch Language Forward", @@ -483,31 +488,31 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LANGUAGE_SWITCH, intArrayOf(KeyEvent.KEYCODE_SPACE), KeyEvent.META_CTRL_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "CTRL + SHIFT + SPACE -> Switch Language Backward", intArrayOf( KeyEvent.KEYCODE_CTRL_LEFT, KeyEvent.KEYCODE_SHIFT_LEFT, - KeyEvent.KEYCODE_SPACE + KeyEvent.KEYCODE_SPACE, ), KeyGestureEvent.KEY_GESTURE_TYPE_LANGUAGE_SWITCH, intArrayOf(KeyEvent.KEYCODE_SPACE), KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "CTRL + ALT + Z -> Accessibility Shortcut", intArrayOf( KeyEvent.KEYCODE_CTRL_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_Z + KeyEvent.KEYCODE_Z, ), KeyGestureEvent.KEY_GESTURE_TYPE_ACCESSIBILITY_SHORTCUT, intArrayOf(KeyEvent.KEYCODE_Z), KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + B -> Launch Default Browser", @@ -516,7 +521,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_B), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER) + AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER), ), TestData( "META + C -> Launch Default Contacts", @@ -525,7 +530,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_P), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS), ), TestData( "META + E -> Launch Default Email", @@ -534,7 +539,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_E), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL), ), TestData( "META + K -> Launch Default Calendar", @@ -543,7 +548,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_C), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR), ), TestData( "META + M -> Launch Default Maps", @@ -552,7 +557,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_M), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS), ), TestData( "META + U -> Launch Default Calculator", @@ -561,159 +566,147 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_U), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR), ), TestData( "META + CTRL + DEL -> Trigger Bug Report", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_CTRL_LEFT, - KeyEvent.KEYCODE_DEL + KeyEvent.KEYCODE_DEL, ), KeyGestureEvent.KEY_GESTURE_TYPE_TRIGGER_BUG_REPORT, intArrayOf(KeyEvent.KEYCODE_DEL), KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "Meta + Alt + 3 -> Toggle Bounce Keys", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_3 + KeyEvent.KEYCODE_3, ), KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_BOUNCE_KEYS, intArrayOf(KeyEvent.KEYCODE_3), KeyEvent.META_META_ON or KeyEvent.META_ALT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "Meta + Alt + 4 -> Toggle Mouse Keys", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_4 + KeyEvent.KEYCODE_4, ), KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_MOUSE_KEYS, intArrayOf(KeyEvent.KEYCODE_4), KeyEvent.META_META_ON or KeyEvent.META_ALT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "Meta + Alt + 5 -> Toggle Sticky Keys", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_5 + KeyEvent.KEYCODE_5, ), KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_STICKY_KEYS, intArrayOf(KeyEvent.KEYCODE_5), KeyEvent.META_META_ON or KeyEvent.META_ALT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "Meta + Alt + 6 -> Toggle Slow Keys", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_6 + KeyEvent.KEYCODE_6, ), KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_SLOW_KEYS, intArrayOf(KeyEvent.KEYCODE_6), KeyEvent.META_META_ON or KeyEvent.META_ALT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + CTRL + D -> Move a task to next display", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_CTRL_LEFT, - KeyEvent.KEYCODE_D + KeyEvent.KEYCODE_D, ), KeyGestureEvent.KEY_GESTURE_TYPE_MOVE_TO_NEXT_DISPLAY, intArrayOf(KeyEvent.KEYCODE_D), KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + [ -> Resizes a task to fit the left half of the screen", - intArrayOf( - KeyEvent.KEYCODE_META_LEFT, - KeyEvent.KEYCODE_LEFT_BRACKET - ), + intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_LEFT_BRACKET), KeyGestureEvent.KEY_GESTURE_TYPE_SNAP_LEFT_FREEFORM_WINDOW, intArrayOf(KeyEvent.KEYCODE_LEFT_BRACKET), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + ] -> Resizes a task to fit the right half of the screen", - intArrayOf( - KeyEvent.KEYCODE_META_LEFT, - KeyEvent.KEYCODE_RIGHT_BRACKET - ), + intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_RIGHT_BRACKET), KeyGestureEvent.KEY_GESTURE_TYPE_SNAP_RIGHT_FREEFORM_WINDOW, intArrayOf(KeyEvent.KEYCODE_RIGHT_BRACKET), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + '=' -> Toggles maximization of a task to maximized and restore its bounds", - intArrayOf( - KeyEvent.KEYCODE_META_LEFT, - KeyEvent.KEYCODE_EQUALS - ), + intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_EQUALS), KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_MAXIMIZE_FREEFORM_WINDOW, intArrayOf(KeyEvent.KEYCODE_EQUALS), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + '-' -> Minimizes a freeform task", - intArrayOf( - KeyEvent.KEYCODE_META_LEFT, - KeyEvent.KEYCODE_MINUS - ), + intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_MINUS), KeyGestureEvent.KEY_GESTURE_TYPE_MINIMIZE_FREEFORM_WINDOW, intArrayOf(KeyEvent.KEYCODE_MINUS), KeyEvent.META_META_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + ALT + M -> Toggle Magnification", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_M + KeyEvent.KEYCODE_M, ), KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_MAGNIFICATION, intArrayOf(KeyEvent.KEYCODE_M), KeyEvent.META_META_ON or KeyEvent.META_ALT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + ALT + S -> Activate Select to Speak", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_S + KeyEvent.KEYCODE_S, ), KeyGestureEvent.KEY_GESTURE_TYPE_ACTIVATE_SELECT_TO_SPEAK, intArrayOf(KeyEvent.KEYCODE_S), KeyEvent.META_META_ON or KeyEvent.META_ALT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + ALT + 'V' -> Toggle Voice Access", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_V + KeyEvent.KEYCODE_V, ), KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_VOICE_ACCESS, intArrayOf(KeyEvent.KEYCODE_V), KeyEvent.META_META_ON or KeyEvent.META_ALT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), ) } @@ -727,7 +720,7 @@ class KeyGestureControllerTests { com.android.hardware.input.Flags.FLAG_ENABLE_TALKBACK_AND_MAGNIFIER_KEY_GESTURES, com.android.hardware.input.Flags.FLAG_ENABLE_VOICE_ACCESS_KEY_GESTURES, com.android.window.flags.Flags.FLAG_ENABLE_MOVE_TO_NEXT_DISPLAY_SHORTCUT, - com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS + com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS, ) fun testKeyGestures(test: TestData) { setupKeyGestureController() @@ -743,26 +736,27 @@ class KeyGestureControllerTests { com.android.hardware.input.Flags.FLAG_ENABLE_TALKBACK_AND_MAGNIFIER_KEY_GESTURES, com.android.hardware.input.Flags.FLAG_ENABLE_VOICE_ACCESS_KEY_GESTURES, com.android.window.flags.Flags.FLAG_ENABLE_MOVE_TO_NEXT_DISPLAY_SHORTCUT, - com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS + com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS, ) fun testCustomKeyGesturesNotAllowedForSystemGestures(test: TestData) { setupKeyGestureController() - val builder = InputGestureData.Builder() - .setKeyGestureType(test.expectedKeyGestureType) - .setTrigger( - InputGestureData.createKeyTrigger( - test.expectedKeys[0], - test.expectedModifierState + val builder = + InputGestureData.Builder() + .setKeyGestureType(test.expectedKeyGestureType) + .setTrigger( + InputGestureData.createKeyTrigger( + test.expectedKeys[0], + test.expectedModifierState, + ) ) - ) if (test.expectedAppLaunchData != null) { builder.setAppLaunchData(test.expectedAppLaunchData) } assertEquals( test.toString(), InputManager.CUSTOM_INPUT_GESTURE_RESULT_ERROR_RESERVED_GESTURE, - keyGestureController.addCustomInputGesture(0, builder.build().aidlData) + keyGestureController.addCustomInputGesture(0, builder.build().aidlData), ) } @@ -776,7 +770,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_B), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER) + AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER), ), TestData( "META + P -> Launch Default Contacts", @@ -785,7 +779,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_P), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS), ), TestData( "META + E -> Launch Default Email", @@ -794,7 +788,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_E), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL), ), TestData( "META + C -> Launch Default Calendar", @@ -803,7 +797,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_C), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR), ), TestData( "META + M -> Launch Default Maps", @@ -812,7 +806,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_M), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS), ), TestData( "META + U -> Launch Default Calculator", @@ -821,47 +815,47 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_U), KeyEvent.META_META_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR), ), TestData( "META + SHIFT + B -> Launch Default Browser", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_SHIFT_LEFT, - KeyEvent.KEYCODE_B + KeyEvent.KEYCODE_B, ), KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION, intArrayOf(KeyEvent.KEYCODE_B), KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER) + AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER), ), TestData( "META + SHIFT + P -> Launch Default Contacts", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_SHIFT_LEFT, - KeyEvent.KEYCODE_P + KeyEvent.KEYCODE_P, ), KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION, intArrayOf(KeyEvent.KEYCODE_P), KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS), ), TestData( "META + SHIFT + J -> Launch Target Activity", intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_SHIFT_LEFT, - KeyEvent.KEYCODE_J + KeyEvent.KEYCODE_J, ), KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION, intArrayOf(KeyEvent.KEYCODE_J), KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest") - ) + AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest"), + ), ) } @@ -890,7 +884,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_RECENT_APPS, intArrayOf(KeyEvent.KEYCODE_RECENT_APPS), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "APP_SWITCH -> App Switch", @@ -900,8 +894,8 @@ class KeyGestureControllerTests { 0, intArrayOf( KeyGestureEvent.ACTION_GESTURE_START, - KeyGestureEvent.ACTION_GESTURE_COMPLETE - ) + KeyGestureEvent.ACTION_GESTURE_COMPLETE, + ), ), TestData( "BRIGHTNESS_UP -> Brightness Up", @@ -909,7 +903,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_BRIGHTNESS_UP, intArrayOf(KeyEvent.KEYCODE_BRIGHTNESS_UP), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "BRIGHTNESS_DOWN -> Brightness Down", @@ -917,7 +911,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_BRIGHTNESS_DOWN, intArrayOf(KeyEvent.KEYCODE_BRIGHTNESS_DOWN), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "KEYBOARD_BACKLIGHT_UP -> Keyboard Backlight Up", @@ -925,7 +919,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_KEYBOARD_BACKLIGHT_UP, intArrayOf(KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_UP), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "KEYBOARD_BACKLIGHT_DOWN -> Keyboard Backlight Down", @@ -933,7 +927,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_KEYBOARD_BACKLIGHT_DOWN, intArrayOf(KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_DOWN), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "KEYBOARD_BACKLIGHT_TOGGLE -> Keyboard Backlight Toggle", @@ -941,7 +935,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_KEYBOARD_BACKLIGHT_TOGGLE, intArrayOf(KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_TOGGLE), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "ALL_APPS -> Open App Drawer", @@ -949,7 +943,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS, intArrayOf(KeyEvent.KEYCODE_ALL_APPS), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "NOTIFICATION -> Toggle Notification Panel", @@ -957,7 +951,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL, intArrayOf(KeyEvent.KEYCODE_NOTIFICATION), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "LANGUAGE_SWITCH -> Switch Language Forward", @@ -965,7 +959,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LANGUAGE_SWITCH, intArrayOf(KeyEvent.KEYCODE_LANGUAGE_SWITCH), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "SHIFT + LANGUAGE_SWITCH -> Switch Language Backward", @@ -973,7 +967,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LANGUAGE_SWITCH, intArrayOf(KeyEvent.KEYCODE_LANGUAGE_SWITCH), KeyEvent.META_SHIFT_ON, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "SCREENSHOT -> Take Screenshot", @@ -981,7 +975,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_TAKE_SCREENSHOT, intArrayOf(KeyEvent.KEYCODE_SCREENSHOT), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META -> Open Apps Drawer", @@ -989,7 +983,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_ACCESSIBILITY_ALL_APPS, intArrayOf(KeyEvent.KEYCODE_META_LEFT), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "SYSRQ -> Take screenshot", @@ -997,7 +991,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_TAKE_SCREENSHOT, intArrayOf(KeyEvent.KEYCODE_SYSRQ), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "ESC -> Close All Dialogs", @@ -1005,7 +999,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_CLOSE_ALL_DIALOGS, intArrayOf(KeyEvent.KEYCODE_ESCAPE), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "EXPLORER -> Launch Default Browser", @@ -1014,7 +1008,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_EXPLORER), 0, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER) + AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER), ), TestData( "ENVELOPE -> Launch Default Email", @@ -1023,7 +1017,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_ENVELOPE), 0, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL), ), TestData( "CONTACTS -> Launch Default Contacts", @@ -1032,7 +1026,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_CONTACTS), 0, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS), ), TestData( "CALENDAR -> Launch Default Calendar", @@ -1041,7 +1035,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_CALENDAR), 0, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR), ), TestData( "MUSIC -> Launch Default Music", @@ -1050,7 +1044,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_MUSIC), 0, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MUSIC) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MUSIC), ), TestData( "CALCULATOR -> Launch Default Calculator", @@ -1059,7 +1053,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_CALCULATOR), 0, intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), - AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR) + AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR), ), TestData( "LOCK -> Lock Screen", @@ -1067,7 +1061,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LOCK_SCREEN, intArrayOf(KeyEvent.KEYCODE_LOCK), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "FULLSCREEN -> Turns a task into fullscreen", @@ -1075,7 +1069,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_MULTI_WINDOW_NAVIGATION, intArrayOf(KeyEvent.KEYCODE_FULLSCREEN), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), ) } @@ -1091,31 +1085,32 @@ class KeyGestureControllerTests { @Test fun testKeycodesFullyConsumed_irrespectiveOfHandlers() { setupKeyGestureController() - val testKeys = intArrayOf( - KeyEvent.KEYCODE_RECENT_APPS, - KeyEvent.KEYCODE_APP_SWITCH, - KeyEvent.KEYCODE_BRIGHTNESS_UP, - KeyEvent.KEYCODE_BRIGHTNESS_DOWN, - KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_DOWN, - KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_UP, - KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_TOGGLE, - KeyEvent.KEYCODE_ALL_APPS, - KeyEvent.KEYCODE_NOTIFICATION, - KeyEvent.KEYCODE_SETTINGS, - KeyEvent.KEYCODE_LANGUAGE_SWITCH, - KeyEvent.KEYCODE_SCREENSHOT, - KeyEvent.KEYCODE_META_LEFT, - KeyEvent.KEYCODE_META_RIGHT, - KeyEvent.KEYCODE_ASSIST, - KeyEvent.KEYCODE_VOICE_ASSIST, - KeyEvent.KEYCODE_STYLUS_BUTTON_PRIMARY, - KeyEvent.KEYCODE_STYLUS_BUTTON_SECONDARY, - KeyEvent.KEYCODE_STYLUS_BUTTON_TERTIARY, - KeyEvent.KEYCODE_STYLUS_BUTTON_TAIL, - KeyEvent.KEYCODE_DO_NOT_DISTURB, - KeyEvent.KEYCODE_LOCK, - KeyEvent.KEYCODE_FULLSCREEN - ) + val testKeys = + intArrayOf( + KeyEvent.KEYCODE_RECENT_APPS, + KeyEvent.KEYCODE_APP_SWITCH, + KeyEvent.KEYCODE_BRIGHTNESS_UP, + KeyEvent.KEYCODE_BRIGHTNESS_DOWN, + KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_DOWN, + KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_UP, + KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_TOGGLE, + KeyEvent.KEYCODE_ALL_APPS, + KeyEvent.KEYCODE_NOTIFICATION, + KeyEvent.KEYCODE_SETTINGS, + KeyEvent.KEYCODE_LANGUAGE_SWITCH, + KeyEvent.KEYCODE_SCREENSHOT, + KeyEvent.KEYCODE_META_LEFT, + KeyEvent.KEYCODE_META_RIGHT, + KeyEvent.KEYCODE_ASSIST, + KeyEvent.KEYCODE_VOICE_ASSIST, + KeyEvent.KEYCODE_STYLUS_BUTTON_PRIMARY, + KeyEvent.KEYCODE_STYLUS_BUTTON_SECONDARY, + KeyEvent.KEYCODE_STYLUS_BUTTON_TERTIARY, + KeyEvent.KEYCODE_STYLUS_BUTTON_TAIL, + KeyEvent.KEYCODE_DO_NOT_DISTURB, + KeyEvent.KEYCODE_LOCK, + KeyEvent.KEYCODE_FULLSCREEN, + ) for (key in testKeys) { sendKeys(intArrayOf(key), assertNotSentToApps = true) @@ -1130,7 +1125,7 @@ class KeyGestureControllerTests { testKeyGestureNotProduced( "SEARCH -> Default Search", intArrayOf(KeyEvent.KEYCODE_SEARCH), - intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SEARCH) + intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SEARCH), ) } @@ -1146,7 +1141,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SEARCH, intArrayOf(KeyEvent.KEYCODE_SEARCH), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ) ) } @@ -1161,8 +1156,8 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_SETTINGS), intArrayOf( KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SEARCH, - KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL - ) + KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL, + ), ) } @@ -1178,7 +1173,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SYSTEM_SETTINGS, intArrayOf(KeyEvent.KEYCODE_SETTINGS), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ) ) } @@ -1195,7 +1190,7 @@ class KeyGestureControllerTests { KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL, intArrayOf(KeyEvent.KEYCODE_SETTINGS), 0, - intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ) ) } @@ -1208,15 +1203,11 @@ class KeyGestureControllerTests { keyGestureController.registerKeyGestureEventListener(listener, 0) sendKeys(intArrayOf(KeyEvent.KEYCODE_CAPS_LOCK)) testLooper.dispatchAll() - assertEquals( - "Listener should get callbacks on key gesture event completed", - 1, - events.size - ) + assertEquals("Listener should get callbacks on key gesture event completed", 1, events.size) assertEquals( "Listener should get callback for Toggle Caps Lock key gesture complete event", KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_CAPS_LOCK, - events[0].keyGestureType + events[0].keyGestureType, ) } @@ -1231,8 +1222,8 @@ class KeyGestureControllerTests { 0, intArrayOf( KeyGestureEvent.ACTION_GESTURE_START, - KeyGestureEvent.ACTION_GESTURE_COMPLETE - ) + KeyGestureEvent.ACTION_GESTURE_COMPLETE, + ), ), TestData( "POWER + STEM_PRIMARY -> Screenshot Chord", @@ -1242,8 +1233,8 @@ class KeyGestureControllerTests { 0, intArrayOf( KeyGestureEvent.ACTION_GESTURE_START, - KeyGestureEvent.ACTION_GESTURE_COMPLETE - ) + KeyGestureEvent.ACTION_GESTURE_COMPLETE, + ), ), TestData( "BACK + DPAD_CENTER -> TV Trigger Bug Report", @@ -1253,8 +1244,8 @@ class KeyGestureControllerTests { 0, intArrayOf( KeyGestureEvent.ACTION_GESTURE_START, - KeyGestureEvent.ACTION_GESTURE_COMPLETE - ) + KeyGestureEvent.ACTION_GESTURE_COMPLETE, + ), ), ) } @@ -1263,7 +1254,7 @@ class KeyGestureControllerTests { @Parameters(method = "systemGesturesTestArguments_forKeyCombinations") @EnableFlags( com.android.hardware.input.Flags.FLAG_USE_KEY_GESTURE_EVENT_HANDLER, - com.android.hardware.input.Flags.FLAG_USE_KEY_GESTURE_EVENT_HANDLER_MULTI_KEY_GESTURES + com.android.hardware.input.Flags.FLAG_USE_KEY_GESTURE_EVENT_HANDLER_MULTI_KEY_GESTURES, ) fun testKeyCombinationGestures(test: TestData) { setupKeyGestureController() @@ -1278,29 +1269,25 @@ class KeyGestureControllerTests { intArrayOf( KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT, - KeyEvent.KEYCODE_Q + KeyEvent.KEYCODE_Q, ), KeyGestureEvent.KEY_GESTURE_TYPE_HOME, intArrayOf(KeyEvent.KEYCODE_Q), KeyEvent.META_META_ON or KeyEvent.META_ALT_ON, - intArrayOf( - KeyGestureEvent.ACTION_GESTURE_COMPLETE - ) + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), ), TestData( "META + ALT + Q -> Launch app", intArrayOf( KeyEvent.KEYCODE_CTRL_LEFT, KeyEvent.KEYCODE_SHIFT_LEFT, - KeyEvent.KEYCODE_Q + KeyEvent.KEYCODE_Q, ), KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION, intArrayOf(KeyEvent.KEYCODE_Q), KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON, - intArrayOf( - KeyGestureEvent.ACTION_GESTURE_COMPLETE - ), - AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest") + intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE), + AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest"), ), ) } @@ -1309,31 +1296,27 @@ class KeyGestureControllerTests { @Parameters(method = "customInputGesturesTestArguments") fun testCustomKeyGestures(test: TestData) { setupKeyGestureController() - val trigger = InputGestureData.createKeyTrigger( - test.expectedKeys[0], - test.expectedModifierState - ) - val builder = InputGestureData.Builder() - .setKeyGestureType(test.expectedKeyGestureType) - .setTrigger(trigger) + val trigger = + InputGestureData.createKeyTrigger(test.expectedKeys[0], test.expectedModifierState) + val builder = + InputGestureData.Builder() + .setKeyGestureType(test.expectedKeyGestureType) + .setTrigger(trigger) if (test.expectedAppLaunchData != null) { builder.setAppLaunchData(test.expectedAppLaunchData) } val inputGestureData = builder.build() - assertNull( - test.toString(), - keyGestureController.getInputGesture(0, trigger.aidlTrigger) - ) + assertNull(test.toString(), keyGestureController.getInputGesture(0, trigger.aidlTrigger)) assertEquals( test.toString(), InputManager.CUSTOM_INPUT_GESTURE_RESULT_SUCCESS, - keyGestureController.addCustomInputGesture(0, builder.build().aidlData) + keyGestureController.addCustomInputGesture(0, builder.build().aidlData), ) assertEquals( test.toString(), inputGestureData.aidlData, - keyGestureController.getInputGesture(0, trigger.aidlTrigger) + keyGestureController.getInputGesture(0, trigger.aidlTrigger), ) testKeyGestureInternal(test) } @@ -1343,14 +1326,15 @@ class KeyGestureControllerTests { fun testCustomKeyGesturesSavedAndLoadedByController(test: TestData) { val userId = 10 setupKeyGestureController() - val builder = InputGestureData.Builder() - .setKeyGestureType(test.expectedKeyGestureType) - .setTrigger( - InputGestureData.createKeyTrigger( - test.expectedKeys[0], - test.expectedModifierState + val builder = + InputGestureData.Builder() + .setKeyGestureType(test.expectedKeyGestureType) + .setTrigger( + InputGestureData.createKeyTrigger( + test.expectedKeys[0], + test.expectedModifierState, + ) ) - ) if (test.expectedAppLaunchData != null) { builder.setAppLaunchData(test.expectedAppLaunchData) } @@ -1371,11 +1355,12 @@ class KeyGestureControllerTests { assertEquals( "Test: $test doesn't produce correct number of saved input gestures", 1, - savedInputGestures.size + savedInputGestures.size, ) assertEquals( - "Test: $test doesn't produce correct input gesture data", inputGestureData, - InputGestureData(savedInputGestures[0]) + "Test: $test doesn't produce correct input gesture data", + inputGestureData, + InputGestureData(savedInputGestures[0]), ) } @@ -1384,14 +1369,15 @@ class KeyGestureControllerTests { fun testCustomKeyGestureRestoredFromBackup(test: TestData) { val userId = 10 setupKeyGestureController() - val builder = InputGestureData.Builder() - .setKeyGestureType(test.expectedKeyGestureType) - .setTrigger( - InputGestureData.createKeyTrigger( - test.expectedKeys[0], - test.expectedModifierState + val builder = + InputGestureData.Builder() + .setKeyGestureType(test.expectedKeyGestureType) + .setTrigger( + InputGestureData.createKeyTrigger( + test.expectedKeys[0], + test.expectedModifierState, + ) ) - ) if (test.expectedAppLaunchData != null) { builder.setAppLaunchData(test.expectedAppLaunchData) } @@ -1415,7 +1401,7 @@ class KeyGestureControllerTests { assertEquals( "Test: $test doesn't produce correct number of saved input gestures", 0, - savedInputGestures.size + savedInputGestures.size, ) // After the restore, there should be the original gesture re-registered. @@ -1424,11 +1410,12 @@ class KeyGestureControllerTests { assertEquals( "Test: $test doesn't produce correct number of saved input gestures", 1, - savedInputGestures.size + savedInputGestures.size, ) assertEquals( - "Test: $test doesn't produce correct input gesture data", inputGestureData, - InputGestureData(savedInputGestures[0]) + "Test: $test doesn't produce correct input gesture data", + inputGestureData, + InputGestureData(savedInputGestures[0]), ) } @@ -1449,14 +1436,14 @@ class KeyGestureControllerTests { "3 Finger Tap -> Go Home", InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP, KeyGestureEvent.KEY_GESTURE_TYPE_HOME, - KeyGestureEvent.ACTION_GESTURE_COMPLETE + KeyGestureEvent.ACTION_GESTURE_COMPLETE, ), TouchpadTestData( "3 Finger Tap -> Launch app", InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP, KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION, KeyGestureEvent.ACTION_GESTURE_COMPLETE, - AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest") + AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest"), ), ) } @@ -1465,9 +1452,10 @@ class KeyGestureControllerTests { @Parameters(method = "customTouchpadGesturesTestArguments") fun testCustomTouchpadGesture(test: TouchpadTestData) { setupKeyGestureController() - val builder = InputGestureData.Builder() - .setKeyGestureType(test.expectedKeyGestureType) - .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType)) + val builder = + InputGestureData.Builder() + .setKeyGestureType(test.expectedKeyGestureType) + .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType)) if (test.expectedAppLaunchData != null) { builder.setAppLaunchData(test.expectedAppLaunchData) } @@ -1476,13 +1464,11 @@ class KeyGestureControllerTests { keyGestureController.addCustomInputGesture(0, inputGestureData.aidlData) val handledEvents = mutableListOf<KeyGestureEvent>() - val handler = KeyGestureHandler { event, _ -> - handledEvents.add(KeyGestureEvent(event)) - } + val handler = KeyGestureHandler { event, _ -> handledEvents.add(KeyGestureEvent(event)) } keyGestureController.registerKeyGestureHandler( intArrayOf(test.expectedKeyGestureType), handler, - TEST_PID + TEST_PID, ) handledEvents.clear() @@ -1491,23 +1477,23 @@ class KeyGestureControllerTests { assertEquals( "Test: $test doesn't produce correct number of key gesture events", 1, - handledEvents.size + handledEvents.size, ) val event = handledEvents[0] assertEquals( "Test: $test doesn't produce correct key gesture type", test.expectedKeyGestureType, - event.keyGestureType + event.keyGestureType, ) assertEquals( "Test: $test doesn't produce correct key gesture action", test.expectedAction, - event.action + event.action, ) assertEquals( "Test: $test doesn't produce correct app launch data", test.expectedAppLaunchData, - event.appLaunchData + event.appLaunchData, ) keyGestureController.unregisterKeyGestureHandler(handler, TEST_PID) @@ -1518,9 +1504,10 @@ class KeyGestureControllerTests { fun testCustomTouchpadGesturesSavedAndLoadedByController(test: TouchpadTestData) { val userId = 10 setupKeyGestureController() - val builder = InputGestureData.Builder() - .setKeyGestureType(test.expectedKeyGestureType) - .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType)) + val builder = + InputGestureData.Builder() + .setKeyGestureType(test.expectedKeyGestureType) + .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType)) if (test.expectedAppLaunchData != null) { builder.setAppLaunchData(test.expectedAppLaunchData) } @@ -1540,23 +1527,24 @@ class KeyGestureControllerTests { assertEquals( "Test: $test doesn't produce correct number of saved input gestures", 1, - savedInputGestures.size + savedInputGestures.size, ) assertEquals( - "Test: $test doesn't produce correct input gesture data", inputGestureData, - InputGestureData(savedInputGestures[0]) + "Test: $test doesn't produce correct input gesture data", + inputGestureData, + InputGestureData(savedInputGestures[0]), ) } - @Test @Parameters(method = "customTouchpadGesturesTestArguments") fun testCustomTouchpadGesturesRestoredFromBackup(test: TouchpadTestData) { val userId = 10 setupKeyGestureController() - val builder = InputGestureData.Builder() - .setKeyGestureType(test.expectedKeyGestureType) - .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType)) + val builder = + InputGestureData.Builder() + .setKeyGestureType(test.expectedKeyGestureType) + .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType)) if (test.expectedAppLaunchData != null) { builder.setAppLaunchData(test.expectedAppLaunchData) } @@ -1579,7 +1567,7 @@ class KeyGestureControllerTests { assertEquals( "Test: $test doesn't produce correct number of saved input gestures", 0, - savedInputGestures.size + savedInputGestures.size, ) // After the restore, there should be the original gesture re-registered. @@ -1588,11 +1576,12 @@ class KeyGestureControllerTests { assertEquals( "Test: $test doesn't produce correct number of saved input gestures", 1, - savedInputGestures.size + savedInputGestures.size, ) assertEquals( - "Test: $test doesn't produce correct input gesture data", inputGestureData, - InputGestureData(savedInputGestures[0]) + "Test: $test doesn't produce correct input gesture data", + inputGestureData, + InputGestureData(savedInputGestures[0]), ) } @@ -1604,7 +1593,7 @@ class KeyGestureControllerTests { intArrayOf(KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN), // Assuming this value is always greater than the accessibility shortcut timeout, which // currently defaults to 3000ms - timeDelayMs = 10000 + timeDelayMs = 10000, ) Mockito.verify(accessibilityShortcutController, times(1)).performAccessibilityShortcut() } @@ -1613,10 +1602,7 @@ class KeyGestureControllerTests { fun testAccessibilityTvShortcutChordPressed() { setupKeyGestureController() - sendKeys( - intArrayOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_DOWN), - timeDelayMs = 10000 - ) + sendKeys(intArrayOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_DOWN), timeDelayMs = 10000) Mockito.verify(accessibilityShortcutController, times(1)).performAccessibilityShortcut() } @@ -1626,7 +1612,7 @@ class KeyGestureControllerTests { sendKeys( intArrayOf(KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN), - timeDelayMs = 0 + timeDelayMs = 0, ) Mockito.verify(accessibilityShortcutController, never()).performAccessibilityShortcut() } @@ -1635,10 +1621,7 @@ class KeyGestureControllerTests { fun testAccessibilityTvShortcutChordPressedForLessThanTimeout() { setupKeyGestureController() - sendKeys( - intArrayOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_DOWN), - timeDelayMs = 0 - ) + sendKeys(intArrayOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_DOWN), timeDelayMs = 0) Mockito.verify(accessibilityShortcutController, never()).performAccessibilityShortcut() } @@ -1651,14 +1634,14 @@ class KeyGestureControllerTests { keyGestureController.registerKeyGestureHandler( intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), handler1, - RANDOM_PID1 + RANDOM_PID1, ) assertThrows(IllegalStateException::class.java) { keyGestureController.registerKeyGestureHandler( intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK), handler2, - RANDOM_PID1 + RANDOM_PID1, ) } } @@ -1672,14 +1655,14 @@ class KeyGestureControllerTests { keyGestureController.registerKeyGestureHandler( intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), handler1, - RANDOM_PID1 + RANDOM_PID1, ) assertThrows(IllegalArgumentException::class.java) { keyGestureController.registerKeyGestureHandler( intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), handler2, - RANDOM_PID2 + RANDOM_PID2, ) } } @@ -1691,11 +1674,7 @@ class KeyGestureControllerTests { val handler = KeyGestureHandler { _, _ -> } assertThrows(IllegalArgumentException::class.java) { - keyGestureController.registerKeyGestureHandler( - intArrayOf(), - handler, - RANDOM_PID1 - ) + keyGestureController.registerKeyGestureHandler(intArrayOf(), handler, RANDOM_PID1) } } @@ -1708,15 +1687,12 @@ class KeyGestureControllerTests { keyGestureController.registerKeyGestureHandler( intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_RECENT_APPS), handler1, - TEST_PID + TEST_PID, ) sendKeys(intArrayOf(KeyEvent.KEYCODE_RECENT_APPS)) assertEquals(1, callbackCount) - keyGestureController.unregisterKeyGestureHandler( - handler1, - TEST_PID - ) + keyGestureController.unregisterKeyGestureHandler(handler1, TEST_PID) // Callback should not be sent after unregister sendKeys(intArrayOf(KeyEvent.KEYCODE_RECENT_APPS)) @@ -1725,13 +1701,11 @@ class KeyGestureControllerTests { private fun testKeyGestureInternal(test: TestData) { val handledEvents = mutableListOf<KeyGestureEvent>() - val handler = KeyGestureHandler { event, _ -> - handledEvents.add(KeyGestureEvent(event)) - } + val handler = KeyGestureHandler { event, _ -> handledEvents.add(KeyGestureEvent(event)) } keyGestureController.registerKeyGestureHandler( intArrayOf(test.expectedKeyGestureType), handler, - TEST_PID + TEST_PID, ) handledEvents.clear() @@ -1740,34 +1714,34 @@ class KeyGestureControllerTests { assertEquals( "Test: $test doesn't produce correct number of key gesture events", test.expectedActions.size, - handledEvents.size + handledEvents.size, ) for (i in handledEvents.indices) { val event = handledEvents[i] assertArrayEquals( "Test: $test doesn't produce correct key gesture keycodes", test.expectedKeys, - event.keycodes + event.keycodes, ) assertEquals( "Test: $test doesn't produce correct key gesture modifier state", test.expectedModifierState, - event.modifierState + event.modifierState, ) assertEquals( "Test: $test doesn't produce correct key gesture type", test.expectedKeyGestureType, - event.keyGestureType + event.keyGestureType, ) assertEquals( "Test: $test doesn't produce correct key gesture action", test.expectedActions[i], - event.action + event.action, ) assertEquals( "Test: $test doesn't produce correct app launch data", test.expectedAppLaunchData, - event.appLaunchData + event.appLaunchData, ) } @@ -1777,12 +1751,10 @@ class KeyGestureControllerTests { private fun testKeyGestureNotProduced( testName: String, testKeys: IntArray, - possibleGestures: IntArray + possibleGestures: IntArray, ) { var handledEvents = mutableListOf<KeyGestureEvent>() - val handler = KeyGestureHandler { event, _ -> - handledEvents.add(KeyGestureEvent(event)) - } + val handler = KeyGestureHandler { event, _ -> handledEvents.add(KeyGestureEvent(event)) } keyGestureController.registerKeyGestureHandler(possibleGestures, handler, TEST_PID) handledEvents.clear() @@ -1793,16 +1765,24 @@ class KeyGestureControllerTests { private fun sendKeys( testKeys: IntArray, assertNotSentToApps: Boolean = false, - timeDelayMs: Long = 0 + timeDelayMs: Long = 0, ) { var metaState = 0 val now = SystemClock.uptimeMillis() for (key in testKeys) { - val downEvent = KeyEvent( - now, now, KeyEvent.ACTION_DOWN, key, 0 /*repeat*/, metaState, - DEVICE_ID, 0 /*scancode*/, 0 /*flags*/, - InputDevice.SOURCE_KEYBOARD - ) + val downEvent = + KeyEvent( + now, + now, + KeyEvent.ACTION_DOWN, + key, + 0 /*repeat*/, + metaState, + DEVICE_ID, + 0 /*scancode*/, + 0 /*flags*/, + InputDevice.SOURCE_KEYBOARD, + ) interceptKey(downEvent, assertNotSentToApps) metaState = metaState or MODIFIER.getOrDefault(key, 0) @@ -1816,11 +1796,19 @@ class KeyGestureControllerTests { } for (key in testKeys.reversed()) { - val upEvent = KeyEvent( - now, now, KeyEvent.ACTION_UP, key, 0 /*repeat*/, metaState, - DEVICE_ID, 0 /*scancode*/, 0 /*flags*/, - InputDevice.SOURCE_KEYBOARD - ) + val upEvent = + KeyEvent( + now, + now, + KeyEvent.ACTION_UP, + key, + 0 /*repeat*/, + metaState, + DEVICE_ID, + 0 /*scancode*/, + 0 /*flags*/, + InputDevice.SOURCE_KEYBOARD, + ) interceptKey(upEvent, assertNotSentToApps) metaState = metaState and MODIFIER.getOrDefault(key, 0).inv() @@ -1833,13 +1821,9 @@ class KeyGestureControllerTests { keyGestureController.interceptKeyBeforeQueueing(event, FLAG_INTERACTIVE) testLooper.dispatchAll() - val consumed = - keyGestureController.interceptKeyBeforeDispatching(null, event, 0) == -1L + val consumed = keyGestureController.interceptKeyBeforeDispatching(null, event, 0) == -1L if (assertNotSentToApps) { - assertTrue( - "interceptKeyBeforeDispatching should consume all events $event", - consumed - ) + assertTrue("interceptKeyBeforeDispatching should consume all events $event", consumed) } if (!consumed) { keyGestureController.interceptUnhandledKey(event, null) diff --git a/tests/Input/src/com/android/server/input/KeyRemapperTests.kt b/tests/Input/src/com/android/server/input/KeyRemapperTests.kt index 4f4c97bef4c0..1fa985647513 100644 --- a/tests/Input/src/com/android/server/input/KeyRemapperTests.kt +++ b/tests/Input/src/com/android/server/input/KeyRemapperTests.kt @@ -51,31 +51,32 @@ private fun createKeyboard(deviceId: Int): InputDevice = /** * Tests for {@link KeyRemapper}. * - * Build/Install/Run: - * atest InputTests:KeyRemapperTests + * Build/Install/Run: atest InputTests:KeyRemapperTests */ @Presubmit class KeyRemapperTests { companion object { const val DEVICE_ID = 1 - val REMAPPABLE_KEYS = intArrayOf( - KeyEvent.KEYCODE_CTRL_LEFT, KeyEvent.KEYCODE_CTRL_RIGHT, - KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_META_RIGHT, - KeyEvent.KEYCODE_ALT_LEFT, KeyEvent.KEYCODE_ALT_RIGHT, - KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_SHIFT_RIGHT, - KeyEvent.KEYCODE_CAPS_LOCK - ) + val REMAPPABLE_KEYS = + intArrayOf( + KeyEvent.KEYCODE_CTRL_LEFT, + KeyEvent.KEYCODE_CTRL_RIGHT, + KeyEvent.KEYCODE_META_LEFT, + KeyEvent.KEYCODE_META_RIGHT, + KeyEvent.KEYCODE_ALT_LEFT, + KeyEvent.KEYCODE_ALT_RIGHT, + KeyEvent.KEYCODE_SHIFT_LEFT, + KeyEvent.KEYCODE_SHIFT_RIGHT, + KeyEvent.KEYCODE_CAPS_LOCK, + ) } - @get:Rule - val rule = MockitoJUnit.rule()!! + @get:Rule val rule = MockitoJUnit.rule()!! - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val inputManagerRule = MockInputManagerRule() - @Mock - private lateinit var native: NativeInputManagerService + @Mock private lateinit var native: NativeInputManagerService private lateinit var mKeyRemapper: KeyRemapper private lateinit var context: Context private lateinit var dataStore: PersistentDataStore @@ -84,24 +85,22 @@ class KeyRemapperTests { @Before fun setup() { context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext())) - dataStore = PersistentDataStore(object : PersistentDataStore.Injector() { - override fun openRead(): InputStream? { - throw FileNotFoundException() - } - - override fun startWrite(): FileOutputStream? { - throw IOException() - } - - override fun finishWrite(fos: FileOutputStream?, success: Boolean) {} - }) + dataStore = + PersistentDataStore( + object : PersistentDataStore.Injector() { + override fun openRead(): InputStream? { + throw FileNotFoundException() + } + + override fun startWrite(): FileOutputStream? { + throw IOException() + } + + override fun finishWrite(fos: FileOutputStream?, success: Boolean) {} + } + ) testLooper = TestLooper() - mKeyRemapper = KeyRemapper( - context, - native, - dataStore, - testLooper.looper - ) + mKeyRemapper = KeyRemapper(context, native, dataStore, testLooper.looper) val inputManager = InputManager(context) Mockito.`when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))) .thenReturn(inputManager) @@ -131,7 +130,7 @@ class KeyRemapperTests { assertEquals( "Remapping should include mapping from $fromKeyCode to $toKeyCode", toKeyCode, - remapping.getOrDefault(fromKeyCode, -1) + remapping.getOrDefault(fromKeyCode, -1), ) } @@ -141,7 +140,7 @@ class KeyRemapperTests { assertEquals( "Remapping size should be 0 after clearAllModifierKeyRemappings", 0, - mKeyRemapper.keyRemapping.size + mKeyRemapper.keyRemapping.size, ) } } @@ -159,7 +158,7 @@ class KeyRemapperTests { assertEquals( "Remapping should not be done if modifier key remapping is disabled", 0, - remapping.size + remapping.size, ) } } @@ -168,7 +167,8 @@ class KeyRemapperTests { init { Settings.Global.putString( context.contentResolver, - "settings_new_keyboard_modifier_key", enabled.toString() + "settings_new_keyboard_modifier_key", + enabled.toString(), ) } @@ -176,8 +176,8 @@ class KeyRemapperTests { Settings.Global.putString( context.contentResolver, "settings_new_keyboard_modifier_key", - "" + "", ) } } -}
\ No newline at end of file +} diff --git a/tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt b/tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt index 644d5a0679de..cf09b54753b0 100644 --- a/tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt +++ b/tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt @@ -29,8 +29,8 @@ import android.os.SystemProperties import android.os.UEventObserver import android.os.test.TestLooper import android.platform.test.annotations.Presubmit -import android.view.InputDevice import android.util.TypedValue +import android.view.InputDevice import androidx.test.annotation.UiThreadTest import androidx.test.core.app.ApplicationProvider import com.android.dx.mockito.inline.extended.ExtendedMockito @@ -65,12 +65,7 @@ private fun createKeyboard(deviceId: Int): InputDevice = .setExternal(true) .build() -private fun createLight(lightId: Int, lightType: Int): Light = - createLight( - lightId, - lightType, - null - ) +private fun createLight(lightId: Int, lightType: Int): Light = createLight(lightId, lightType, null) private fun createLight(lightId: Int, lightType: Int, suggestedBrightnessLevels: IntArray?): Light = Light( @@ -79,13 +74,13 @@ private fun createLight(lightId: Int, lightType: Int, suggestedBrightnessLevels: 1, lightType, Light.LIGHT_CAPABILITY_BRIGHTNESS, - suggestedBrightnessLevels + suggestedBrightnessLevels, ) + /** * Tests for {@link KeyboardBacklightController}. * - * Build/Install/Run: - * atest InputTests:KeyboardBacklightControllerTests + * Build/Install/Run: atest InputTests:KeyboardBacklightControllerTests */ @Presubmit class KeyboardBacklightControllerTests { @@ -100,15 +95,11 @@ class KeyboardBacklightControllerTests { @get:Rule val extendedMockitoRule = ExtendedMockitoRule.Builder(this).mockStatic(SystemProperties::class.java).build()!! - @get:Rule - val inputManagerRule = MockInputManagerRule() - - @Mock - private lateinit var native: NativeInputManagerService - @Mock - private lateinit var uEventManager: UEventManager - @Mock - private lateinit var resources: Resources + @get:Rule val inputManagerRule = MockInputManagerRule() + + @Mock private lateinit var native: NativeInputManagerService + @Mock private lateinit var uEventManager: UEventManager + @Mock private lateinit var resources: Resources private lateinit var keyboardBacklightController: KeyboardBacklightController private lateinit var context: Context private lateinit var testLooper: TestLooper @@ -135,9 +126,7 @@ class KeyboardBacklightControllerTests { lightColorMap.getOrDefault(args[1] as Int, 0) } lightColorMap.clear() - `when`(native.sysfsNodeChanged(any())).then { - sysfsNodeChanges++ - } + `when`(native.sysfsNodeChanged(any())).then { sysfsNodeChanges++ } } private fun setupConfig() { @@ -153,22 +142,29 @@ class KeyboardBacklightControllerTests { `when`(resources.getInteger(R.integer.config_keyboardBacklightTimeoutMs)) .thenReturn(USER_INACTIVITY_THRESHOLD_MILLIS) `when`( - resources.getValue( - eq(R.dimen.config_autoKeyboardBrightnessSmoothingConstant), - any(TypedValue::class.java), - anyBoolean() + resources.getValue( + eq(R.dimen.config_autoKeyboardBrightnessSmoothingConstant), + any(TypedValue::class.java), + anyBoolean(), + ) ) - ).then { - val args = it.arguments - val outValue = args[1] as TypedValue - outValue.data = java.lang.Float.floatToRawIntBits(1.0f) - Unit - } + .then { + val args = it.arguments + val outValue = args[1] as TypedValue + outValue.data = java.lang.Float.floatToRawIntBits(1.0f) + Unit + } } private fun setupController() { - keyboardBacklightController = KeyboardBacklightController(context, native, - testLooper.looper, FakeAnimatorFactory(), uEventManager) + keyboardBacklightController = + KeyboardBacklightController( + context, + native, + testLooper.looper, + FakeAnimatorFactory(), + uEventManager, + ) } @Test @@ -180,8 +176,11 @@ class KeyboardBacklightControllerTests { `when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight)) keyboardBacklightController.onInputDeviceAdded(DEVICE_ID) - assertIncrementDecrementForLevels(keyboardWithBacklight, keyboardBacklight, - DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL) + assertIncrementDecrementForLevels( + keyboardWithBacklight, + keyboardBacklight, + DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL, + ) } @Test @@ -204,12 +203,8 @@ class KeyboardBacklightControllerTests { val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT) val keyboardInputLight = createLight(SECOND_LIGHT_ID, Light.LIGHT_TYPE_INPUT) `when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight) - `when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn( - listOf( - keyboardBacklight, - keyboardInputLight - ) - ) + `when`(inputManagerRule.mock.getLights(DEVICE_ID)) + .thenReturn(listOf(keyboardBacklight, keyboardInputLight)) keyboardBacklightController.onInputDeviceAdded(DEVICE_ID) incrementKeyboardBacklight(DEVICE_ID) @@ -239,22 +234,22 @@ class KeyboardBacklightControllerTests { assertEquals( "Backlight state device Id should be $DEVICE_ID", DEVICE_ID, - lastBacklightState!!.deviceId + lastBacklightState!!.deviceId, ) assertEquals( "Backlight state brightnessLevel should be 1", 1, - lastBacklightState!!.brightnessLevel + lastBacklightState!!.brightnessLevel, ) assertEquals( "Backlight state maxBrightnessLevel should be $maxLevel", maxLevel, - lastBacklightState!!.maxBrightnessLevel + lastBacklightState!!.maxBrightnessLevel, ) assertEquals( "Backlight state isTriggeredByKeyPress should be true", true, - lastBacklightState!!.isTriggeredByKeyPress + lastBacklightState!!.isTriggeredByKeyPress, ) // Unregister listener @@ -278,7 +273,7 @@ class KeyboardBacklightControllerTests { assertNotEquals( "Keyboard backlight level should be incremented to a non-zero value", 0, - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) testLooper.moveTimeForward((USER_INACTIVITY_THRESHOLD_MILLIS + 1000).toLong()) @@ -286,7 +281,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Keyboard backlight level should be turned off after inactivity", 0, - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) } @@ -304,21 +299,21 @@ class KeyboardBacklightControllerTests { assertNotEquals( "Keyboard backlight level should be incremented to a non-zero value", 0, - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) keyboardBacklightController.handleInteractiveStateChange(false /* isDisplayOn */) assertEquals( "Keyboard backlight level should be turned off after display is turned off", 0, - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) keyboardBacklightController.handleInteractiveStateChange(true /* isDisplayOn */) assertEquals( "Keyboard backlight level should be turned on after display is turned on", currentValue, - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) } @@ -326,58 +321,70 @@ class KeyboardBacklightControllerTests { fun testKeyboardBacklightSysfsNodeAdded_AfterInputDeviceAdded() { setupController() var counter = sysfsNodeChanges - keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent( - "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::no_backlight\u0000" - )) + keyboardBacklightController.onKeyboardBacklightUEvent( + UEventObserver.UEvent( + "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::no_backlight\u0000" + ) + ) assertEquals( "Should not reload sysfs node if UEvent path doesn't contain kbd_backlight", counter, - sysfsNodeChanges + sysfsNodeChanges, ) - keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent( - "ACTION=add\u0000SUBSYSTEM=power\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000" - )) + keyboardBacklightController.onKeyboardBacklightUEvent( + UEventObserver.UEvent( + "ACTION=add\u0000SUBSYSTEM=power\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000" + ) + ) assertEquals( "Should not reload sysfs node if UEvent doesn't belong to subsystem LED", counter, - sysfsNodeChanges + sysfsNodeChanges, ) - keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent( - "ACTION=remove\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000" - )) + keyboardBacklightController.onKeyboardBacklightUEvent( + UEventObserver.UEvent( + "ACTION=remove\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000" + ) + ) assertEquals( "Should not reload sysfs node if UEvent doesn't have ACTION(add)", counter, - sysfsNodeChanges + sysfsNodeChanges, ) - keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent( - "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/pqr/abc::kbd_backlight\u0000" - )) + keyboardBacklightController.onKeyboardBacklightUEvent( + UEventObserver.UEvent( + "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/pqr/abc::kbd_backlight\u0000" + ) + ) assertEquals( "Should not reload sysfs node if UEvent path doesn't belong to leds/ directory", counter, - sysfsNodeChanges + sysfsNodeChanges, ) - keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent( - "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000" - )) + keyboardBacklightController.onKeyboardBacklightUEvent( + UEventObserver.UEvent( + "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000" + ) + ) assertEquals( "Should reload sysfs node if a valid Keyboard backlight LED UEvent occurs", ++counter, - sysfsNodeChanges + sysfsNodeChanges, ) - keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent( - "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc:kbd_backlight:red\u0000" - )) + keyboardBacklightController.onKeyboardBacklightUEvent( + UEventObserver.UEvent( + "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc:kbd_backlight:red\u0000" + ) + ) assertEquals( "Should reload sysfs node if a valid Keyboard backlight LED UEvent occurs", ++counter, - sysfsNodeChanges + sysfsNodeChanges, ) } @@ -398,12 +405,12 @@ class KeyboardBacklightControllerTests { assertEquals( "Should start animation from level 0", DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[0], - lastAnimationValues[0] + lastAnimationValues[0], ) assertEquals( "Should start animation to level 1", DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[1], - lastAnimationValues[1] + lastAnimationValues[1], ) } @@ -412,8 +419,8 @@ class KeyboardBacklightControllerTests { setupController() val keyboardWithBacklight = createKeyboard(DEVICE_ID) val suggestedLevels = intArrayOf(0, 22, 63, 135, 196, 255) - val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, - suggestedLevels) + val keyboardBacklight = + createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, suggestedLevels) `when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight) `when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight)) keyboardBacklightController.onInputDeviceAdded(DEVICE_ID) @@ -426,14 +433,17 @@ class KeyboardBacklightControllerTests { setupController() val keyboardWithBacklight = createKeyboard(DEVICE_ID) val suggestedLevels = IntArray(MAX_BRIGHTNESS_CHANGE_STEPS + 1) { 10 * (it + 1) } - val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, - suggestedLevels) + val keyboardBacklight = + createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, suggestedLevels) `when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight) `when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight)) keyboardBacklightController.onInputDeviceAdded(DEVICE_ID) - assertIncrementDecrementForLevels(keyboardWithBacklight, keyboardBacklight, - DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL) + assertIncrementDecrementForLevels( + keyboardWithBacklight, + keyboardBacklight, + DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL, + ) } @Test @@ -441,15 +451,18 @@ class KeyboardBacklightControllerTests { setupController() val keyboardWithBacklight = createKeyboard(DEVICE_ID) val suggestedLevels = intArrayOf(22, 63, 135, 196) - val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, - suggestedLevels) + val keyboardBacklight = + createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, suggestedLevels) `when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight) `when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight)) keyboardBacklightController.onInputDeviceAdded(DEVICE_ID) // Framework will add the lowest and maximum levels if not provided via config - assertIncrementDecrementForLevels(keyboardWithBacklight, keyboardBacklight, - intArrayOf(0, 22, 63, 135, 196, 255)) + assertIncrementDecrementForLevels( + keyboardWithBacklight, + keyboardBacklight, + intArrayOf(0, 22, 63, 135, 196, 255), + ) } @Test @@ -457,15 +470,18 @@ class KeyboardBacklightControllerTests { setupController() val keyboardWithBacklight = createKeyboard(DEVICE_ID) val suggestedLevels = intArrayOf(22, 63, 135, 400, 196, 1000) - val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, - suggestedLevels) + val keyboardBacklight = + createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, suggestedLevels) `when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight) `when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight)) keyboardBacklightController.onInputDeviceAdded(DEVICE_ID) // Framework will drop out of bound levels in the config - assertIncrementDecrementForLevels(keyboardWithBacklight, keyboardBacklight, - intArrayOf(0, 22, 63, 135, 196, 255)) + assertIncrementDecrementForLevels( + keyboardWithBacklight, + keyboardBacklight, + intArrayOf(0, 22, 63, 135, 196, 255), + ) } @Test @@ -480,7 +496,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value should be changed to ambient provided value", Color.argb(1, 0, 0, 0), - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) incrementKeyboardBacklight(DEVICE_ID) @@ -488,7 +504,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value for level after increment post Ambient change is mismatched", Color.argb(DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[1], 0, 0, 0), - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) } @@ -504,7 +520,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value should be changed to ambient provided value", Color.argb(254, 0, 0, 0), - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) decrementKeyboardBacklight(DEVICE_ID) @@ -513,7 +529,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value for level after decrement post Ambient change is mismatched", Color.argb(DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[numLevels - 2], 0, 0, 0), - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) } @@ -529,21 +545,21 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value should be changed to the first level", Color.argb(DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[1], 0, 0, 0), - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) sendAmbientBacklightValue(100) assertNotEquals( "Light value should not change based on ambient changes after manual changes", Color.argb(100, 0, 0, 0), - lightColorMap[LIGHT_ID] + lightColorMap[LIGHT_ID], ) } private fun assertIncrementDecrementForLevels( device: InputDevice, light: Light, - expectedLevels: IntArray + expectedLevels: IntArray, ) { val deviceId = device.id val lightId = light.id @@ -552,7 +568,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value for level $level mismatched", Color.argb(expectedLevels[level], 0, 0, 0), - lightColorMap[lightId] + lightColorMap[lightId], ) } @@ -561,7 +577,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value for max level mismatched", Color.argb(MAX_BRIGHTNESS, 0, 0, 0), - lightColorMap[lightId] + lightColorMap[lightId], ) for (level in expectedLevels.size - 2 downTo 0) { @@ -569,7 +585,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value for level $level mismatched", Color.argb(expectedLevels[level], 0, 0, 0), - lightColorMap[lightId] + lightColorMap[lightId], ) } @@ -578,7 +594,7 @@ class KeyboardBacklightControllerTests { assertEquals( "Light value for min level mismatched", Color.argb(0, 0, 0, 0), - lightColorMap[lightId] + lightColorMap[lightId], ) } @@ -586,14 +602,15 @@ class KeyboardBacklightControllerTests { override fun onBrightnessChanged( deviceId: Int, state: IKeyboardBacklightState, - isTriggeredByKeyPress: Boolean + isTriggeredByKeyPress: Boolean, ) { - lastBacklightState = KeyboardBacklightState( - deviceId, - state.brightnessLevel, - state.maxBrightnessLevel, - isTriggeredByKeyPress - ) + lastBacklightState = + KeyboardBacklightState( + deviceId, + state.brightnessLevel, + state.maxBrightnessLevel, + isTriggeredByKeyPress, + ) } } @@ -619,7 +636,7 @@ class KeyboardBacklightControllerTests { val deviceId: Int, val brightnessLevel: Int, val maxBrightnessLevel: Int, - val isTriggeredByKeyPress: Boolean + val isTriggeredByKeyPress: Boolean, ) private inner class FakeAnimatorFactory : KeyboardBacklightController.AnimatorFactory { diff --git a/tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt b/tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt index 5da0beb9cc8a..7c3a6a60d3b6 100644 --- a/tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt +++ b/tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt @@ -49,8 +49,7 @@ import org.mockito.junit.MockitoJUnit /** * Tests for custom keyboard glyph map configuration. * - * Build/Install/Run: - * atest InputTests:KeyboardGlyphManagerTests + * Build/Install/Run: atest InputTests:KeyboardGlyphManagerTests */ @Presubmit class KeyboardGlyphManagerTests { @@ -66,15 +65,11 @@ class KeyboardGlyphManagerTests { const val RECEIVER_NAME = "DummyReceiver" } - @get:Rule - val setFlagsRule = SetFlagsRule() - @get:Rule - val mockitoRule = MockitoJUnit.rule()!! - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val setFlagsRule = SetFlagsRule() + @get:Rule val mockitoRule = MockitoJUnit.rule()!! + @get:Rule val inputManagerRule = MockInputManagerRule() - @Mock - private lateinit var packageManager: PackageManager + @Mock private lateinit var packageManager: PackageManager private lateinit var keyboardGlyphManager: KeyboardGlyphManager private lateinit var context: Context @@ -99,7 +94,8 @@ class KeyboardGlyphManagerTests { .thenReturn(inputManager) keyboardDevice = createKeyboard(DEVICE_ID, VENDOR_ID, PRODUCT_ID, 0, "", "") - Mockito.`when`(inputManagerRule.mock.inputDeviceIds).thenReturn(intArrayOf(DEVICE_ID, DEVICE_ID2)) + Mockito.`when`(inputManagerRule.mock.inputDeviceIds) + .thenReturn(intArrayOf(DEVICE_ID, DEVICE_ID2)) Mockito.`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardDevice) val keyboardDevice2 = createKeyboard(DEVICE_ID2, VENDOR_ID2, PRODUCT_ID2, 0, "", "") @@ -110,19 +106,22 @@ class KeyboardGlyphManagerTests { Mockito.`when`(context.packageManager).thenReturn(packageManager) val info = createMockReceiver() - Mockito.`when`(packageManager.queryBroadcastReceiversAsUser(Mockito.any(), Mockito.anyInt(), - Mockito.anyInt())).thenReturn(listOf(info)) + Mockito.`when`( + packageManager.queryBroadcastReceiversAsUser( + Mockito.any(), + Mockito.anyInt(), + Mockito.anyInt(), + ) + ) + .thenReturn(listOf(info)) Mockito.`when`(packageManager.getReceiverInfo(Mockito.any(), Mockito.anyInt())) .thenReturn(info.activityInfo) val resources = context.resources Mockito.`when`( - packageManager.getResourcesForApplication( - Mockito.any( - ApplicationInfo::class.java - ) + packageManager.getResourcesForApplication(Mockito.any(ApplicationInfo::class.java)) ) - ).thenReturn(resources) + .thenReturn(resources) } private fun createMockReceiver(): ResolveInfo { @@ -134,7 +133,7 @@ class KeyboardGlyphManagerTests { info.activityInfo.metaData = Bundle() info.activityInfo.metaData.putInt( InputManager.META_DATA_KEYBOARD_GLYPH_MAPS, - R.xml.keyboard_glyph_maps + R.xml.keyboard_glyph_maps, ) info.serviceInfo = ServiceInfo() info.serviceInfo.packageName = PACKAGE_NAME @@ -147,15 +146,15 @@ class KeyboardGlyphManagerTests { fun testGlyphMapsLoaded() { assertNotNull( "Glyph map for test keyboard(deviceId=$DEVICE_ID) must exist", - keyboardGlyphManager.getKeyGlyphMap(DEVICE_ID) + keyboardGlyphManager.getKeyGlyphMap(DEVICE_ID), ) assertNotNull( "Glyph map for test keyboard(deviceId=$DEVICE_ID2) must exist", - keyboardGlyphManager.getKeyGlyphMap(DEVICE_ID2) + keyboardGlyphManager.getKeyGlyphMap(DEVICE_ID2), ) assertNull( "Glyph map for non-existing keyboard must be null", - keyboardGlyphManager.getKeyGlyphMap(-2) + keyboardGlyphManager.getKeyGlyphMap(-2), ) } @@ -178,16 +177,15 @@ class KeyboardGlyphManagerTests { assertEquals(2, hardwareShortcuts.size) assertEquals( KeyEvent.KEYCODE_BACK, - hardwareShortcuts[KeyCombination(KeyEvent.META_FUNCTION_ON, KeyEvent.KEYCODE_1)] + hardwareShortcuts[KeyCombination(KeyEvent.META_FUNCTION_ON, KeyEvent.KEYCODE_1)], ) assertEquals( KeyEvent.KEYCODE_HOME, hardwareShortcuts[ KeyCombination( KeyEvent.META_FUNCTION_ON or KeyEvent.META_META_ON, - KeyEvent.KEYCODE_2 - ) - ] + KeyEvent.KEYCODE_2, + )], ) } } diff --git a/tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt b/tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt index 4440a839caef..c83036ce05ba 100644 --- a/tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt +++ b/tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt @@ -65,7 +65,7 @@ fun createKeyboard( productId: Int, deviceBus: Int, languageTag: String, - layoutType: String + layoutType: String, ): InputDevice = InputDevice.Builder() .setId(deviceId) @@ -84,8 +84,7 @@ fun createKeyboard( /** * Tests for {@link Default UI} and {@link New UI}. * - * Build/Install/Run: - * atest InputTests:KeyboardLayoutManagerTests + * Build/Install/Run: atest InputTests:KeyboardLayoutManagerTests */ @Presubmit class KeyboardLayoutManagerTests { @@ -118,19 +117,15 @@ class KeyboardLayoutManagerTests { @JvmField @Rule - val extendedMockitoRule = ExtendedMockitoRule.Builder(this) - .mockStatic(FrameworkStatsLog::class.java).build()!! + val extendedMockitoRule = + ExtendedMockitoRule.Builder(this).mockStatic(FrameworkStatsLog::class.java).build()!! - @get:Rule - val inputManagerRule = MockInputManagerRule() + @get:Rule val inputManagerRule = MockInputManagerRule() - @Mock - private lateinit var native: NativeInputManagerService + @Mock private lateinit var native: NativeInputManagerService - @Mock - private lateinit var packageManager: PackageManager - @Mock - private lateinit var notificationManager: NotificationManager + @Mock private lateinit var packageManager: PackageManager + @Mock private lateinit var notificationManager: NotificationManager private lateinit var keyboardLayoutManager: KeyboardLayoutManager private lateinit var imeInfo: InputMethodInfo @@ -149,23 +144,25 @@ class KeyboardLayoutManagerTests { @Before fun setup() { context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext())) - dataStore = PersistentDataStore(object : PersistentDataStore.Injector() { - override fun openRead(): InputStream? { - throw FileNotFoundException() - } - - override fun startWrite(): FileOutputStream? { - throw IOException() - } - - override fun finishWrite(fos: FileOutputStream?, success: Boolean) {} - }) + dataStore = + PersistentDataStore( + object : PersistentDataStore.Injector() { + override fun openRead(): InputStream? { + throw FileNotFoundException() + } + + override fun startWrite(): FileOutputStream? { + throw IOException() + } + + override fun finishWrite(fos: FileOutputStream?, success: Boolean) {} + } + ) testLooper = TestLooper() - keyboardLayoutManager = Mockito.spy( - KeyboardLayoutManager(context, native, dataStore, testLooper.looper) - ) + keyboardLayoutManager = + Mockito.spy(KeyboardLayoutManager(context, native, dataStore, testLooper.looper)) Mockito.`when`(context.getSystemService(Mockito.eq(Context.NOTIFICATION_SERVICE))) - .thenReturn(notificationManager) + .thenReturn(notificationManager) setupInputDevices() setupBroadcastReceiver() setupIme() @@ -176,47 +173,72 @@ class KeyboardLayoutManagerTests { Mockito.`when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))) .thenReturn(inputManager) - keyboardDevice = createKeyboard(DEVICE_ID, DEFAULT_VENDOR_ID, DEFAULT_PRODUCT_ID, - DEFAULT_DEVICE_BUS, "", "") - vendorSpecificKeyboardDevice = createKeyboard(VENDOR_SPECIFIC_DEVICE_ID, 1, 1, - 1, "", "") - englishDvorakKeyboardDevice = createKeyboard(ENGLISH_DVORAK_DEVICE_ID, DEFAULT_VENDOR_ID, - DEFAULT_PRODUCT_ID, DEFAULT_DEVICE_BUS, "en", "dvorak") - englishQwertyKeyboardDevice = createKeyboard(ENGLISH_QWERTY_DEVICE_ID, DEFAULT_VENDOR_ID, - DEFAULT_PRODUCT_ID, DEFAULT_DEVICE_BUS, "en", "qwerty") - Mockito.`when`(inputManagerRule.mock.inputDeviceIds) - .thenReturn(intArrayOf( + keyboardDevice = + createKeyboard( DEVICE_ID, - VENDOR_SPECIFIC_DEVICE_ID, + DEFAULT_VENDOR_ID, + DEFAULT_PRODUCT_ID, + DEFAULT_DEVICE_BUS, + "", + "", + ) + vendorSpecificKeyboardDevice = createKeyboard(VENDOR_SPECIFIC_DEVICE_ID, 1, 1, 1, "", "") + englishDvorakKeyboardDevice = + createKeyboard( ENGLISH_DVORAK_DEVICE_ID, - ENGLISH_QWERTY_DEVICE_ID - )) + DEFAULT_VENDOR_ID, + DEFAULT_PRODUCT_ID, + DEFAULT_DEVICE_BUS, + "en", + "dvorak", + ) + englishQwertyKeyboardDevice = + createKeyboard( + ENGLISH_QWERTY_DEVICE_ID, + DEFAULT_VENDOR_ID, + DEFAULT_PRODUCT_ID, + DEFAULT_DEVICE_BUS, + "en", + "qwerty", + ) + Mockito.`when`(inputManagerRule.mock.inputDeviceIds) + .thenReturn( + intArrayOf( + DEVICE_ID, + VENDOR_SPECIFIC_DEVICE_ID, + ENGLISH_DVORAK_DEVICE_ID, + ENGLISH_QWERTY_DEVICE_ID, + ) + ) Mockito.`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardDevice) Mockito.`when`(inputManagerRule.mock.getInputDevice(VENDOR_SPECIFIC_DEVICE_ID)) .thenReturn(vendorSpecificKeyboardDevice) Mockito.`when`(inputManagerRule.mock.getInputDevice(ENGLISH_DVORAK_DEVICE_ID)) .thenReturn(englishDvorakKeyboardDevice) Mockito.`when`(inputManagerRule.mock.getInputDevice(ENGLISH_QWERTY_DEVICE_ID)) - .thenReturn(englishQwertyKeyboardDevice) + .thenReturn(englishQwertyKeyboardDevice) } private fun setupBroadcastReceiver() { Mockito.`when`(context.packageManager).thenReturn(packageManager) val info = createMockReceiver() - Mockito.`when`(packageManager.queryBroadcastReceiversAsUser(Mockito.any(), Mockito.anyInt(), - Mockito.anyInt())).thenReturn(listOf(info)) + Mockito.`when`( + packageManager.queryBroadcastReceiversAsUser( + Mockito.any(), + Mockito.anyInt(), + Mockito.anyInt(), + ) + ) + .thenReturn(listOf(info)) Mockito.`when`(packageManager.getReceiverInfo(Mockito.any(), Mockito.anyInt())) .thenReturn(info.activityInfo) val resources = context.resources Mockito.`when`( - packageManager.getResourcesForApplication( - Mockito.any( - ApplicationInfo::class.java - ) + packageManager.getResourcesForApplication(Mockito.any(ApplicationInfo::class.java)) ) - ).thenReturn(resources) + .thenReturn(resources) } private fun setupIme() { @@ -229,22 +251,21 @@ class KeyboardLayoutManagerTests { assertNotEquals( "Keyboard layout API should not return empty array", 0, - keyboardLayouts.size + keyboardLayouts.size, ) assertTrue( "Keyboard layout API should provide English(US) layout", - hasLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR) + hasLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR), ) } @Test fun testGetKeyboardLayout() { - val keyboardLayout = - keyboardLayoutManager.getKeyboardLayout(ENGLISH_US_LAYOUT_DESCRIPTOR) - assertEquals("getKeyboardLayout API should return correct Layout from " + - "available layouts", + val keyboardLayout = keyboardLayoutManager.getKeyboardLayout(ENGLISH_US_LAYOUT_DESCRIPTOR) + assertEquals( + "getKeyboardLayout API should return correct Layout from " + "available layouts", ENGLISH_US_LAYOUT_DESCRIPTOR, - keyboardLayout!!.descriptor + keyboardLayout!!.descriptor, ) } @@ -253,32 +274,44 @@ class KeyboardLayoutManagerTests { val imeSubtype = createImeSubtype() keyboardLayoutManager.setKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype, - ENGLISH_UK_LAYOUT_DESCRIPTOR + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, + ENGLISH_UK_LAYOUT_DESCRIPTOR, ) var result = keyboardLayoutManager.getKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, ) assertEquals( "getKeyboardLayoutForInputDevice API should return the set layout", ENGLISH_UK_LAYOUT_DESCRIPTOR, - result.layoutDescriptor + result.layoutDescriptor, ) // This should replace previously set layout keyboardLayoutManager.setKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype, - ENGLISH_US_LAYOUT_DESCRIPTOR + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, + ENGLISH_US_LAYOUT_DESCRIPTOR, ) result = keyboardLayoutManager.getKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, ) assertEquals( "getKeyboardLayoutForInputDevice API should return the last set layout", ENGLISH_US_LAYOUT_DESCRIPTOR, - result.layoutDescriptor + result.layoutDescriptor, ) } @@ -288,32 +321,42 @@ class KeyboardLayoutManagerTests { keyboardLayoutManager.setKeyboardLayoutOverrideForInputDevice( keyboardDevice.identifier, - ENGLISH_UK_LAYOUT_DESCRIPTOR + ENGLISH_UK_LAYOUT_DESCRIPTOR, ) var result = keyboardLayoutManager.getKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, ) assertEquals(LAYOUT_SELECTION_CRITERIA_DEVICE, result.selectionCriteria) assertEquals( "getKeyboardLayoutForInputDevice API should return the set layout", ENGLISH_UK_LAYOUT_DESCRIPTOR, - result.layoutDescriptor + result.layoutDescriptor, ) // This should replace the overriding layout set above keyboardLayoutManager.setKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype, - ENGLISH_US_LAYOUT_DESCRIPTOR - ) - result = keyboardLayoutManager.getKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, + ENGLISH_US_LAYOUT_DESCRIPTOR, ) + result = + keyboardLayoutManager.getKeyboardLayoutForInputDevice( + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, + ) assertEquals(LAYOUT_SELECTION_CRITERIA_USER, result.selectionCriteria) assertEquals( "getKeyboardLayoutForInputDevice API should return the user set layout", ENGLISH_US_LAYOUT_DESCRIPTOR, - result.layoutDescriptor + result.layoutDescriptor, ) } @@ -322,54 +365,67 @@ class KeyboardLayoutManagerTests { // Check Layouts for "hi-Latn". It should return all 'Latn' keyboard layouts var keyboardLayouts = keyboardLayoutManager.getKeyboardLayoutListForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, - createImeSubtypeForLanguageTag("hi-Latn") + keyboardDevice.identifier, + USER_ID, + imeInfo, + createImeSubtypeForLanguageTag("hi-Latn"), ) assertNotEquals( "getKeyboardLayoutListForInputDevice API should return the list of " + - "supported layouts with matching script code", + "supported layouts with matching script code", 0, - keyboardLayouts.size + keyboardLayouts.size, ) - assertTrue("getKeyboardLayoutListForInputDevice API should return a list " + + assertTrue( + "getKeyboardLayoutListForInputDevice API should return a list " + "containing English(US) layout for hi-Latn", - containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR) + containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR), ) - assertTrue("getKeyboardLayoutListForInputDevice API should return a list " + + assertTrue( + "getKeyboardLayoutListForInputDevice API should return a list " + "containing English(No script code) layout for hi-Latn", containsLayout( keyboardLayouts, - createLayoutDescriptor("keyboard_layout_english_without_script_code") - ) + createLayoutDescriptor("keyboard_layout_english_without_script_code"), + ), ) // Check Layouts for "hi" which by default uses 'Deva' script. keyboardLayouts = keyboardLayoutManager.getKeyboardLayoutListForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, - createImeSubtypeForLanguageTag("hi") + keyboardDevice.identifier, + USER_ID, + imeInfo, + createImeSubtypeForLanguageTag("hi"), ) - assertEquals("getKeyboardLayoutListForInputDevice API should return empty " + + assertEquals( + "getKeyboardLayoutListForInputDevice API should return empty " + "list if no supported layouts available", 0, - keyboardLayouts.size + keyboardLayouts.size, ) // If user manually selected some layout, always provide it in the layout list val imeSubtype = createImeSubtypeForLanguageTag("hi") keyboardLayoutManager.setKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype, - ENGLISH_US_LAYOUT_DESCRIPTOR + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, + ENGLISH_US_LAYOUT_DESCRIPTOR, ) keyboardLayouts = keyboardLayoutManager.getKeyboardLayoutListForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, - imeSubtype + keyboardDevice.identifier, + USER_ID, + imeInfo, + imeSubtype, ) - assertEquals("getKeyboardLayoutListForInputDevice API should return user " + + assertEquals( + "getKeyboardLayoutListForInputDevice API should return user " + "selected layout even if the script is incompatible with IME", - 1, - keyboardLayouts.size + 1, + keyboardLayouts.size, ) // Special case Japanese: UScript ignores provided script code for certain language tags @@ -377,63 +433,71 @@ class KeyboardLayoutManagerTests { // script from language tags and match those. keyboardLayouts = keyboardLayoutManager.getKeyboardLayoutListForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, - createImeSubtypeForLanguageTag("ja-Latn-JP") + keyboardDevice.identifier, + USER_ID, + imeInfo, + createImeSubtypeForLanguageTag("ja-Latn-JP"), ) assertNotEquals( "getKeyboardLayoutListForInputDevice API should return the list of " + - "supported layouts with matching script code for ja-Latn-JP", + "supported layouts with matching script code for ja-Latn-JP", 0, - keyboardLayouts.size + keyboardLayouts.size, ) - assertTrue("getKeyboardLayoutListForInputDevice API should return a list " + + assertTrue( + "getKeyboardLayoutListForInputDevice API should return a list " + "containing English(US) layout for ja-Latn-JP", - containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR) + containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR), ) - assertTrue("getKeyboardLayoutListForInputDevice API should return a list " + + assertTrue( + "getKeyboardLayoutListForInputDevice API should return a list " + "containing English(No script code) layout for ja-Latn-JP", containsLayout( keyboardLayouts, - createLayoutDescriptor("keyboard_layout_english_without_script_code") - ) + createLayoutDescriptor("keyboard_layout_english_without_script_code"), + ), ) // If script code not explicitly provided for Japanese should rely on Uscript to find // derived script code and hence no suitable layout will be found. keyboardLayouts = keyboardLayoutManager.getKeyboardLayoutListForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, - createImeSubtypeForLanguageTag("ja-JP") + keyboardDevice.identifier, + USER_ID, + imeInfo, + createImeSubtypeForLanguageTag("ja-JP"), ) assertEquals( "getKeyboardLayoutListForInputDevice API should return empty list of " + - "supported layouts with matching script code for ja-JP", + "supported layouts with matching script code for ja-JP", 0, - keyboardLayouts.size + keyboardLayouts.size, ) // If IME doesn't have a corresponding language tag, then should show all available // layouts no matter the script code. keyboardLayouts = keyboardLayoutManager.getKeyboardLayoutListForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, null + keyboardDevice.identifier, + USER_ID, + imeInfo, + null, ) assertNotEquals( "getKeyboardLayoutListForInputDevice API should return all layouts if" + "language tag or subtype not provided", 0, - keyboardLayouts.size + keyboardLayouts.size, ) - assertTrue("getKeyboardLayoutListForInputDevice API should contain Latin " + - "layouts if language tag or subtype not provided", - containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR) + assertTrue( + "getKeyboardLayoutListForInputDevice API should contain Latin " + + "layouts if language tag or subtype not provided", + containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR), ) - assertTrue("getKeyboardLayoutListForInputDevice API should contain Cyrillic " + - "layouts if language tag or subtype not provided", - containsLayout( - keyboardLayouts, - createLayoutDescriptor("keyboard_layout_russian") - ) + assertTrue( + "getKeyboardLayoutListForInputDevice API should contain Cyrillic " + + "layouts if language tag or subtype not provided", + containsLayout(keyboardLayouts, createLayoutDescriptor("keyboard_layout_russian")), ) } @@ -442,46 +506,50 @@ class KeyboardLayoutManagerTests { assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTag("en-US"), - ENGLISH_US_LAYOUT_DESCRIPTOR + ENGLISH_US_LAYOUT_DESCRIPTOR, ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTag("en-GB"), - ENGLISH_UK_LAYOUT_DESCRIPTOR + ENGLISH_UK_LAYOUT_DESCRIPTOR, ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTag("de"), - GERMAN_LAYOUT_DESCRIPTOR + GERMAN_LAYOUT_DESCRIPTOR, ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTag("fr-FR"), - createLayoutDescriptor("keyboard_layout_french") + createLayoutDescriptor("keyboard_layout_french"), ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTag("ru"), - createLayoutDescriptor("keyboard_layout_russian") + createLayoutDescriptor("keyboard_layout_russian"), ) assertEquals( "getDefaultKeyboardLayoutForInputDevice should return " + - "KeyboardLayoutSelectionResult.FAILED when no layout available", + "KeyboardLayoutSelectionResult.FAILED when no layout available", KeyboardLayoutSelectionResult.FAILED, keyboardLayoutManager.getKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, - createImeSubtypeForLanguageTag("it") - ) + keyboardDevice.identifier, + USER_ID, + imeInfo, + createImeSubtypeForLanguageTag("it"), + ), ) assertEquals( "getDefaultKeyboardLayoutForInputDevice should return " + - "KeyboardLayoutSelectionResult.FAILED when no layout for script code is" + - "available", + "KeyboardLayoutSelectionResult.FAILED when no layout for script code is" + + "available", KeyboardLayoutSelectionResult.FAILED, keyboardLayoutManager.getKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, - createImeSubtypeForLanguageTag("en-Deva") - ) + keyboardDevice.identifier, + USER_ID, + imeInfo, + createImeSubtypeForLanguageTag("en-Deva"), + ), ) } @@ -490,72 +558,75 @@ class KeyboardLayoutManagerTests { assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("en-US", "qwerty"), - ENGLISH_US_LAYOUT_DESCRIPTOR + ENGLISH_US_LAYOUT_DESCRIPTOR, ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("en-US", "dvorak"), - createLayoutDescriptor("keyboard_layout_english_us_dvorak") + createLayoutDescriptor("keyboard_layout_english_us_dvorak"), ) // Try to match layout type even if country doesn't match assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("en-GB", "dvorak"), - createLayoutDescriptor("keyboard_layout_english_us_dvorak") + createLayoutDescriptor("keyboard_layout_english_us_dvorak"), ) // Choose layout based on layout type priority, if layout type is not provided by IME // (Qwerty > Dvorak > Extended) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("en-US", ""), - ENGLISH_US_LAYOUT_DESCRIPTOR + ENGLISH_US_LAYOUT_DESCRIPTOR, ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("en-GB", "qwerty"), - ENGLISH_UK_LAYOUT_DESCRIPTOR + ENGLISH_UK_LAYOUT_DESCRIPTOR, ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("de", "qwertz"), - GERMAN_LAYOUT_DESCRIPTOR + GERMAN_LAYOUT_DESCRIPTOR, ) // Wrong layout type should match with language if provided layout type not available assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("de", "qwerty"), - GERMAN_LAYOUT_DESCRIPTOR + GERMAN_LAYOUT_DESCRIPTOR, ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("fr-FR", "azerty"), - createLayoutDescriptor("keyboard_layout_french") + createLayoutDescriptor("keyboard_layout_french"), ) assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("ru", "qwerty"), - createLayoutDescriptor("keyboard_layout_russian_qwerty") + createLayoutDescriptor("keyboard_layout_russian_qwerty"), ) // If layout type is empty then prioritize KCM with empty layout type assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("ru", ""), - createLayoutDescriptor("keyboard_layout_russian") + createLayoutDescriptor("keyboard_layout_russian"), ) - assertEquals("getDefaultKeyboardLayoutForInputDevice should return " + + assertEquals( + "getDefaultKeyboardLayoutForInputDevice should return " + "KeyboardLayoutSelectionResult.FAILED when no layout for script code is" + "available", KeyboardLayoutSelectionResult.FAILED, keyboardLayoutManager.getKeyboardLayoutForInputDevice( - keyboardDevice.identifier, USER_ID, imeInfo, - createImeSubtypeForLanguageTagAndLayoutType("en-Deva-US", "") - ) + keyboardDevice.identifier, + USER_ID, + imeInfo, + createImeSubtypeForLanguageTagAndLayoutType("en-Deva-US", ""), + ), ) // If prefer layout with empty country over mismatched country assertCorrectLayout( keyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("en-AU", "qwerty"), - ENGLISH_US_LAYOUT_DESCRIPTOR + ENGLISH_US_LAYOUT_DESCRIPTOR, ) } @@ -567,7 +638,7 @@ class KeyboardLayoutManagerTests { assertCorrectLayout( englishDvorakKeyboardDevice, frenchSubtype, - createLayoutDescriptor("keyboard_layout_english_us_dvorak") + createLayoutDescriptor("keyboard_layout_english_us_dvorak"), ) // Back to back changing HW keyboards with same product and vendor ID but different @@ -575,7 +646,7 @@ class KeyboardLayoutManagerTests { assertCorrectLayout( englishQwertyKeyboardDevice, frenchSubtype, - createLayoutDescriptor("keyboard_layout_english_us") + createLayoutDescriptor("keyboard_layout_english_us"), ) // Fallback to IME information if the HW provided layout script is incompatible with the @@ -583,62 +654,72 @@ class KeyboardLayoutManagerTests { assertCorrectLayout( englishDvorakKeyboardDevice, createImeSubtypeForLanguageTagAndLayoutType("ru", ""), - createLayoutDescriptor("keyboard_layout_russian") + createLayoutDescriptor("keyboard_layout_russian"), ) } @Test fun testConfigurationLogged_onInputDeviceAdded_VirtualKeyboardBasedSelection() { - val imeInfos = listOf( - KeyboardLayoutManager.ImeInfo(0, imeInfo, - createImeSubtypeForLanguageTagAndLayoutType("de-Latn", "qwertz"))) + val imeInfos = + listOf( + KeyboardLayoutManager.ImeInfo( + 0, + imeInfo, + createImeSubtypeForLanguageTagAndLayoutType("de-Latn", "qwertz"), + ) + ) Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping keyboardLayoutManager.onInputDeviceAdded(keyboardDevice.id) ExtendedMockito.verify { FrameworkStatsLog.write( - ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED), - ArgumentMatchers.anyBoolean(), - ArgumentMatchers.eq(keyboardDevice.vendorId), - ArgumentMatchers.eq(keyboardDevice.productId), - ArgumentMatchers.eq( - createByteArray( - KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG, - LAYOUT_TYPE_DEFAULT, - GERMAN_LAYOUT_NAME, - KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD, - "de-Latn", - LAYOUT_TYPE_QWERTZ - ), - ), - ArgumentMatchers.eq(keyboardDevice.deviceBus), + ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED), + ArgumentMatchers.anyBoolean(), + ArgumentMatchers.eq(keyboardDevice.vendorId), + ArgumentMatchers.eq(keyboardDevice.productId), + ArgumentMatchers.eq( + createByteArray( + KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG, + LAYOUT_TYPE_DEFAULT, + GERMAN_LAYOUT_NAME, + KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD, + "de-Latn", + LAYOUT_TYPE_QWERTZ, + ) + ), + ArgumentMatchers.eq(keyboardDevice.deviceBus), ) } } @Test fun testConfigurationLogged_onInputDeviceAdded_DeviceBasedSelection() { - val imeInfos = listOf( - KeyboardLayoutManager.ImeInfo(0, imeInfo, - createImeSubtypeForLanguageTagAndLayoutType("de-Latn", "qwertz"))) + val imeInfos = + listOf( + KeyboardLayoutManager.ImeInfo( + 0, + imeInfo, + createImeSubtypeForLanguageTagAndLayoutType("de-Latn", "qwertz"), + ) + ) Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping keyboardLayoutManager.onInputDeviceAdded(englishQwertyKeyboardDevice.id) ExtendedMockito.verify { FrameworkStatsLog.write( - ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED), - ArgumentMatchers.anyBoolean(), - ArgumentMatchers.eq(englishQwertyKeyboardDevice.vendorId), - ArgumentMatchers.eq(englishQwertyKeyboardDevice.productId), - ArgumentMatchers.eq( - createByteArray( - "en", - LAYOUT_TYPE_QWERTY, - ENGLISH_US_LAYOUT_NAME, - KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE, - "de-Latn", - LAYOUT_TYPE_QWERTZ - ) - ), - ArgumentMatchers.eq(keyboardDevice.deviceBus), + ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED), + ArgumentMatchers.anyBoolean(), + ArgumentMatchers.eq(englishQwertyKeyboardDevice.vendorId), + ArgumentMatchers.eq(englishQwertyKeyboardDevice.productId), + ArgumentMatchers.eq( + createByteArray( + "en", + LAYOUT_TYPE_QWERTY, + ENGLISH_US_LAYOUT_NAME, + KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE, + "de-Latn", + LAYOUT_TYPE_QWERTZ, + ) + ), + ArgumentMatchers.eq(keyboardDevice.deviceBus), ) } } @@ -650,21 +731,21 @@ class KeyboardLayoutManagerTests { keyboardLayoutManager.onInputDeviceAdded(keyboardDevice.id) ExtendedMockito.verify { FrameworkStatsLog.write( - ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED), - ArgumentMatchers.anyBoolean(), - ArgumentMatchers.eq(keyboardDevice.vendorId), - ArgumentMatchers.eq(keyboardDevice.productId), - ArgumentMatchers.eq( - createByteArray( - KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG, - LAYOUT_TYPE_DEFAULT, - "Default", - KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEFAULT, - KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG, - LAYOUT_TYPE_DEFAULT - ), - ), - ArgumentMatchers.eq(keyboardDevice.deviceBus), + ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED), + ArgumentMatchers.anyBoolean(), + ArgumentMatchers.eq(keyboardDevice.vendorId), + ArgumentMatchers.eq(keyboardDevice.productId), + ArgumentMatchers.eq( + createByteArray( + KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG, + LAYOUT_TYPE_DEFAULT, + "Default", + KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEFAULT, + KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG, + LAYOUT_TYPE_DEFAULT, + ) + ), + ArgumentMatchers.eq(keyboardDevice.deviceBus), ) } } @@ -674,82 +755,86 @@ class KeyboardLayoutManagerTests { val imeInfos = listOf(KeyboardLayoutManager.ImeInfo(0, imeInfo, createImeSubtype())) Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping keyboardLayoutManager.onInputDeviceChanged(keyboardDevice.id) - ExtendedMockito.verify({ - FrameworkStatsLog.write( + ExtendedMockito.verify( + { + FrameworkStatsLog.write( ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED), ArgumentMatchers.anyBoolean(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(ByteArray::class.java), ArgumentMatchers.anyInt(), - ) - }, Mockito.times(0)) + ) + }, + Mockito.times(0), + ) } @Test fun testNotificationShown_onInputDeviceChanged() { val imeInfos = listOf(KeyboardLayoutManager.ImeInfo(0, imeInfo, createImeSubtype())) Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping - Mockito.doReturn(false).`when`(keyboardLayoutManager).isVirtualDevice( - ArgumentMatchers.eq(keyboardDevice.id) - ) + Mockito.doReturn(false) + .`when`(keyboardLayoutManager) + .isVirtualDevice(ArgumentMatchers.eq(keyboardDevice.id)) keyboardLayoutManager.onInputDeviceChanged(keyboardDevice.id) - ExtendedMockito.verify( - notificationManager, - Mockito.times(1) - ).notifyAsUser( - ArgumentMatchers.isNull(), - ArgumentMatchers.anyInt(), - ArgumentMatchers.any(), - ArgumentMatchers.any() - ) + ExtendedMockito.verify(notificationManager, Mockito.times(1)) + .notifyAsUser( + ArgumentMatchers.isNull(), + ArgumentMatchers.anyInt(), + ArgumentMatchers.any(), + ArgumentMatchers.any(), + ) } @Test fun testNotificationNotShown_onInputDeviceChanged_forVirtualDevice() { val imeInfos = listOf(KeyboardLayoutManager.ImeInfo(0, imeInfo, createImeSubtype())) Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping - Mockito.doReturn(true).`when`(keyboardLayoutManager).isVirtualDevice( - ArgumentMatchers.eq(keyboardDevice.id) - ) + Mockito.doReturn(true) + .`when`(keyboardLayoutManager) + .isVirtualDevice(ArgumentMatchers.eq(keyboardDevice.id)) keyboardLayoutManager.onInputDeviceChanged(keyboardDevice.id) - ExtendedMockito.verify( - notificationManager, - Mockito.never() - ).notifyAsUser( - ArgumentMatchers.isNull(), - ArgumentMatchers.anyInt(), - ArgumentMatchers.any(), - ArgumentMatchers.any() - ) + ExtendedMockito.verify(notificationManager, Mockito.never()) + .notifyAsUser( + ArgumentMatchers.isNull(), + ArgumentMatchers.anyInt(), + ArgumentMatchers.any(), + ArgumentMatchers.any(), + ) } private fun assertCorrectLayout( device: InputDevice, imeSubtype: InputMethodSubtype, - expectedLayout: String + expectedLayout: String, ) { - val result = keyboardLayoutManager.getKeyboardLayoutForInputDevice( - device.identifier, USER_ID, imeInfo, imeSubtype - ) + val result = + keyboardLayoutManager.getKeyboardLayoutForInputDevice( + device.identifier, + USER_ID, + imeInfo, + imeSubtype, + ) assertEquals( "getDefaultKeyboardLayoutForInputDevice should return $expectedLayout", expectedLayout, - result.layoutDescriptor + result.layoutDescriptor, ) } private fun createImeSubtype(): InputMethodSubtype = - createImeSubtypeForLanguageTagAndLayoutType(null, null) + createImeSubtypeForLanguageTagAndLayoutType(null, null) private fun createImeSubtypeForLanguageTag(languageTag: String): InputMethodSubtype = - createImeSubtypeForLanguageTagAndLayoutType(languageTag, null) + createImeSubtypeForLanguageTagAndLayoutType(languageTag, null) private fun createImeSubtypeForLanguageTagAndLayoutType( - languageTag: String?, - layoutType: String? + languageTag: String?, + layoutType: String?, ): InputMethodSubtype { - val builder = InputMethodSubtype.InputMethodSubtypeBuilder() + val builder = + InputMethodSubtype.InputMethodSubtypeBuilder() .setSubtypeId(nextImeSubtypeId++) .setIsAuxiliary(false) .setSubtypeMode("keyboard") @@ -762,39 +847,39 @@ class KeyboardLayoutManagerTests { } private fun createByteArray( - expectedLanguageTag: String, - expectedLayoutType: Int, - expectedLayoutName: String, - expectedCriteria: Int, - expectedImeLanguageTag: String, - expectedImeLayoutType: Int + expectedLanguageTag: String, + expectedLayoutType: Int, + expectedLayoutName: String, + expectedCriteria: Int, + expectedImeLanguageTag: String, + expectedImeLayoutType: Int, ): ByteArray { val proto = ProtoOutputStream() - val keyboardLayoutConfigToken = proto.start( - KeyboardConfiguredProto.RepeatedKeyboardLayoutConfig.KEYBOARD_LAYOUT_CONFIG) + val keyboardLayoutConfigToken = + proto.start(KeyboardConfiguredProto.RepeatedKeyboardLayoutConfig.KEYBOARD_LAYOUT_CONFIG) proto.write( - KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LANGUAGE_TAG, - expectedLanguageTag + KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LANGUAGE_TAG, + expectedLanguageTag, ) proto.write( - KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LAYOUT_TYPE, - expectedLayoutType + KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LAYOUT_TYPE, + expectedLayoutType, ) proto.write( - KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LAYOUT_NAME, - expectedLayoutName + KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LAYOUT_NAME, + expectedLayoutName, ) proto.write( - KeyboardConfiguredProto.KeyboardLayoutConfig.LAYOUT_SELECTION_CRITERIA, - expectedCriteria + KeyboardConfiguredProto.KeyboardLayoutConfig.LAYOUT_SELECTION_CRITERIA, + expectedCriteria, ) proto.write( - KeyboardConfiguredProto.KeyboardLayoutConfig.IME_LANGUAGE_TAG, - expectedImeLanguageTag + KeyboardConfiguredProto.KeyboardLayoutConfig.IME_LANGUAGE_TAG, + expectedImeLanguageTag, ) proto.write( - KeyboardConfiguredProto.KeyboardLayoutConfig.IME_LAYOUT_TYPE, - expectedImeLayoutType + KeyboardConfiguredProto.KeyboardLayoutConfig.IME_LAYOUT_TYPE, + expectedImeLayoutType, ) proto.end(keyboardLayoutConfigToken) return proto.bytes @@ -830,7 +915,7 @@ class KeyboardLayoutManagerTests { info.activityInfo.metaData = Bundle() info.activityInfo.metaData.putInt( InputManager.META_DATA_KEYBOARD_LAYOUTS, - R.xml.keyboard_layouts + R.xml.keyboard_layouts, ) info.serviceInfo = ServiceInfo() info.serviceInfo.packageName = PACKAGE_NAME diff --git a/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt b/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt index 0615941eda09..5251f3d3f1d3 100644 --- a/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt +++ b/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt @@ -33,7 +33,7 @@ private fun createKeyboard( productId: Int, deviceBus: Int, languageTag: String?, - layoutType: String? + layoutType: String?, ): InputDevice = InputDevice.Builder() .setId(deviceId) @@ -52,16 +52,17 @@ private fun createKeyboard( private fun createImeSubtype( imeSubtypeId: Int, languageTag: ULocale?, - layoutType: String + layoutType: String, ): InputMethodSubtype = - InputMethodSubtype.InputMethodSubtypeBuilder().setSubtypeId(imeSubtypeId) - .setPhysicalKeyboardHint(languageTag, layoutType).build() + InputMethodSubtype.InputMethodSubtypeBuilder() + .setSubtypeId(imeSubtypeId) + .setPhysicalKeyboardHint(languageTag, layoutType) + .build() /** * Tests for {@link KeyboardMetricsCollector}. * - * Build/Install/Run: - * atest InputTests:KeyboardMetricsCollectorTests + * Build/Install/Run: atest InputTests:KeyboardMetricsCollectorTests */ @Presubmit class KeyboardMetricsCollectorTests { @@ -77,15 +78,16 @@ class KeyboardMetricsCollectorTests { fun testCreateKeyboardConfigurationEvent_throwsExceptionWithoutAnyLayoutConfiguration() { assertThrows(IllegalStateException::class.java) { KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder( - createKeyboard( - DEVICE_ID, - DEFAULT_VENDOR_ID, - DEFAULT_PRODUCT_ID, - DEFAULT_DEVICE_BUS, - null, - null + createKeyboard( + DEVICE_ID, + DEFAULT_VENDOR_ID, + DEFAULT_PRODUCT_ID, + DEFAULT_DEVICE_BUS, + null, + null, + ) ) - ).build() + .build() } } @@ -93,66 +95,78 @@ class KeyboardMetricsCollectorTests { fun testCreateKeyboardConfigurationEvent_throwsExceptionWithInvalidLayoutSelectionCriteria() { assertThrows(IllegalStateException::class.java) { KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder( - createKeyboard( - DEVICE_ID, - DEFAULT_VENDOR_ID, - DEFAULT_PRODUCT_ID, - DEFAULT_DEVICE_BUS, + createKeyboard( + DEVICE_ID, + DEFAULT_VENDOR_ID, + DEFAULT_PRODUCT_ID, + DEFAULT_DEVICE_BUS, + null, + null, + ) + ) + .addLayoutSelection( + createImeSubtype(1, ULocale.forLanguageTag("en-US"), "qwerty"), null, - null + 123, ) - ).addLayoutSelection(createImeSubtype(1, ULocale.forLanguageTag("en-US"), "qwerty"), - null, 123).build() + .build() } } @Test fun testCreateKeyboardConfigurationEvent_withMultipleConfigurations() { - val builder = KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder( - createKeyboard( - DEVICE_ID, - DEFAULT_VENDOR_ID, - DEFAULT_PRODUCT_ID, - DEFAULT_DEVICE_BUS, - "de-CH", - "qwertz" + val builder = + KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder( + createKeyboard( + DEVICE_ID, + DEFAULT_VENDOR_ID, + DEFAULT_PRODUCT_ID, + DEFAULT_DEVICE_BUS, + "de-CH", + "qwertz", + ) ) - ) - val event = builder.addLayoutSelection( - createImeSubtype(1, ULocale.forLanguageTag("en-US"), "qwerty"), - "English(US)(Qwerty)", - KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD - ).addLayoutSelection( - createImeSubtype(2, ULocale.forLanguageTag("en-US"), "azerty"), - null, // Default layout type - KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_USER - ).addLayoutSelection( - createImeSubtype(3, ULocale.forLanguageTag("en-US"), "qwerty"), - "German", - KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE - ).setIsFirstTimeConfiguration(true).build() + val event = + builder + .addLayoutSelection( + createImeSubtype(1, ULocale.forLanguageTag("en-US"), "qwerty"), + "English(US)(Qwerty)", + KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD, + ) + .addLayoutSelection( + createImeSubtype(2, ULocale.forLanguageTag("en-US"), "azerty"), + null, // Default layout type + KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_USER, + ) + .addLayoutSelection( + createImeSubtype(3, ULocale.forLanguageTag("en-US"), "qwerty"), + "German", + KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE, + ) + .setIsFirstTimeConfiguration(true) + .build() assertEquals( "KeyboardConfigurationEvent should pick vendor ID from provided InputDevice", DEFAULT_VENDOR_ID, - event.vendorId + event.vendorId, ) assertEquals( "KeyboardConfigurationEvent should pick product ID from provided InputDevice", DEFAULT_PRODUCT_ID, - event.productId + event.productId, ) assertEquals( - "KeyboardConfigurationEvent should pick device bus from provided InputDevice", - DEFAULT_DEVICE_BUS, - event.deviceBus + "KeyboardConfigurationEvent should pick device bus from provided InputDevice", + DEFAULT_DEVICE_BUS, + event.deviceBus, ) assertTrue(event.isFirstConfiguration) assertEquals( "KeyboardConfigurationEvent should contain 3 configurations provided", 3, - event.layoutConfigurations.size + event.layoutConfigurations.size, ) assertExpectedLayoutConfiguration( event.layoutConfigurations[0], @@ -185,21 +199,25 @@ class KeyboardMetricsCollectorTests { @Test fun testCreateKeyboardConfigurationEvent_withDefaultLanguageTag() { - val builder = KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder( - createKeyboard( - DEVICE_ID, - DEFAULT_VENDOR_ID, - DEFAULT_PRODUCT_ID, - DEFAULT_DEVICE_BUS, - "und", // Undefined language tag - "azerty" + val builder = + KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder( + createKeyboard( + DEVICE_ID, + DEFAULT_VENDOR_ID, + DEFAULT_PRODUCT_ID, + DEFAULT_DEVICE_BUS, + "und", // Undefined language tag + "azerty", + ) ) - ) - val event = builder.addLayoutSelection( - createImeSubtype(4, null, "qwerty"), // Default language tag - "German", - KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE - ).build() + val event = + builder + .addLayoutSelection( + createImeSubtype(4, null, "qwerty"), // Default language tag + "German", + KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE, + ) + .build() assertExpectedLayoutConfiguration( event.layoutConfigurations[0], @@ -219,7 +237,7 @@ class KeyboardMetricsCollectorTests { expectedSelectedLayout: String, expectedLayoutSelectionCriteria: Int, expectedImeLanguageTag: String, - expectedImeLayoutType: Int + expectedImeLayoutType: Int, ) { assertEquals(expectedKeyboardLanguageTag, configuration.keyboardLanguageTag) assertEquals(expectedKeyboardLayoutType, configuration.keyboardLayoutType) diff --git a/tests/Input/src/com/android/server/input/PointerIconCacheTest.kt b/tests/Input/src/com/android/server/input/PointerIconCacheTest.kt index 47e7ac720a08..d9ae7f339ed9 100644 --- a/tests/Input/src/com/android/server/input/PointerIconCacheTest.kt +++ b/tests/Input/src/com/android/server/input/PointerIconCacheTest.kt @@ -34,19 +34,14 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever -/** - * Tests for {@link PointerIconCache}. - */ +/** Tests for {@link PointerIconCache}. */ @Presubmit class PointerIconCacheTest { - @get:Rule - val rule = MockitoJUnit.rule()!! + @get:Rule val rule = MockitoJUnit.rule()!! - @Mock - private lateinit var native: NativeInputManagerService - @Mock - private lateinit var defaultDisplay: Display + @Mock private lateinit var native: NativeInputManagerService + @Mock private lateinit var defaultDisplay: Display private lateinit var context: Context private lateinit var testLooper: TestLooper @@ -56,9 +51,10 @@ class PointerIconCacheTest { fun setup() { whenever(defaultDisplay.displayId).thenReturn(Display.DEFAULT_DISPLAY) - context = object : ContextWrapper(InstrumentationRegistry.getInstrumentation().context) { - override fun getDisplay() = defaultDisplay - } + context = + object : ContextWrapper(InstrumentationRegistry.getInstrumentation().context) { + override fun getDisplay() = defaultDisplay + } testLooper = TestLooper() cache = PointerIconCache(context, native, Handler(testLooper.looper)) diff --git a/tests/Input/src/com/android/test/input/InputEventAssignerTest.kt b/tests/Input/src/com/android/test/input/InputEventAssignerTest.kt index 015e188fc98e..faa68bd484f6 100644 --- a/tests/Input/src/com/android/test/input/InputEventAssignerTest.kt +++ b/tests/Input/src/com/android/test/input/InputEventAssignerTest.kt @@ -17,10 +17,9 @@ package com.android.test.input import android.view.InputDevice.SOURCE_MOUSE -import android.view.InputDevice.SOURCE_TOUCHSCREEN import android.view.InputDevice.SOURCE_STYLUS import android.view.InputDevice.SOURCE_TOUCHPAD - +import android.view.InputDevice.SOURCE_TOUCHSCREEN import android.view.InputEventAssigner import android.view.KeyEvent import android.view.MotionEvent @@ -28,13 +27,13 @@ import org.junit.Assert.assertEquals import org.junit.Test sealed class StreamEvent + private data object Vsync : StreamEvent() + data class MotionEventData(val action: Int, val source: Int, val id: Int, val expectedId: Int) : StreamEvent() -/** - * Create a MotionEvent with the provided action, eventTime, and source - */ +/** Create a MotionEvent with the provided action, eventTime, and source */ fun createMotionEvent(action: Int, eventTime: Long, source: Int): MotionEvent { val downTime: Long = 10 val x = 1f @@ -47,8 +46,22 @@ fun createMotionEvent(action: Int, eventTime: Long, source: Int): MotionEvent { val deviceId = 1 val edgeFlags = 0 val displayId = 0 - return MotionEvent.obtain(downTime, eventTime, action, x, y, pressure, size, metaState, - xPrecision, yPrecision, deviceId, edgeFlags, source, displayId) + return MotionEvent.obtain( + downTime, + eventTime, + action, + x, + y, + pressure, + size, + metaState, + xPrecision, + yPrecision, + deviceId, + edgeFlags, + source, + displayId, + ) } private fun createKeyEvent(action: Int, eventTime: Long): KeyEvent { @@ -58,11 +71,10 @@ private fun createKeyEvent(action: Int, eventTime: Long): KeyEvent { } /** - * Check that the correct eventIds are assigned in a stream. The stream consists of motion - * events or vsync (processed frame) - * Each streamEvent should have unique ids when writing tests - * The test passes even if two events get assigned the same eventId, since the mapping is - * streamEventId -> motionEventId and streamEvents have unique ids + * Check that the correct eventIds are assigned in a stream. The stream consists of motion events or + * vsync (processed frame) Each streamEvent should have unique ids when writing tests The test + * passes even if two events get assigned the same eventId, since the mapping is streamEventId -> + * motionEventId and streamEvents have unique ids */ private fun checkEventStream(vararg streamEvents: StreamEvent) { val assigner = InputEventAssigner() @@ -90,9 +102,7 @@ class InputEventAssignerTest { private const val TAG = "InputEventAssignerTest" } - /** - * A single event should be assigned to the next available frame. - */ + /** A single event should be assigned to the next available frame. */ @Test fun testTouchMove() { checkEventStream( @@ -145,7 +155,7 @@ class InputEventAssignerTest { MotionEventData(MotionEvent.ACTION_DOWN, source, id = 1, expectedId = 1), MotionEventData(MotionEvent.ACTION_MOVE, source, id = 2, expectedId = 1), Vsync, - MotionEventData(MotionEvent.ACTION_MOVE, source, id = 4, expectedId = 4) + MotionEventData(MotionEvent.ACTION_MOVE, source, id = 4, expectedId = 4), ) } @@ -169,57 +179,47 @@ class InputEventAssignerTest { testDownAndMove(SOURCE_TOUCHPAD) } - /** - * After an up event, motion events should be assigned their own event id - */ + /** After an up event, motion events should be assigned their own event id */ @Test fun testMouseDownUpAndScroll() { checkEventStream( MotionEventData(MotionEvent.ACTION_DOWN, SOURCE_MOUSE, id = 1, expectedId = 1), MotionEventData(MotionEvent.ACTION_UP, SOURCE_MOUSE, id = 2, expectedId = 2), - MotionEventData(MotionEvent.ACTION_SCROLL, SOURCE_MOUSE, id = 3, expectedId = 3) + MotionEventData(MotionEvent.ACTION_SCROLL, SOURCE_MOUSE, id = 3, expectedId = 3), ) } - /** - * After an up event, motion events should be assigned their own event id - */ + /** After an up event, motion events should be assigned their own event id */ @Test fun testStylusDownUpAndHover() { checkEventStream( MotionEventData(MotionEvent.ACTION_DOWN, SOURCE_STYLUS, id = 1, expectedId = 1), MotionEventData(MotionEvent.ACTION_UP, SOURCE_STYLUS, id = 2, expectedId = 2), - MotionEventData(MotionEvent.ACTION_HOVER_ENTER, SOURCE_STYLUS, id = 3, expectedId = 3) + MotionEventData(MotionEvent.ACTION_HOVER_ENTER, SOURCE_STYLUS, id = 3, expectedId = 3), ) } - /** - * After a cancel event, motion events should be assigned their own event id - */ + /** After a cancel event, motion events should be assigned their own event id */ @Test fun testMouseDownCancelAndScroll() { checkEventStream( MotionEventData(MotionEvent.ACTION_DOWN, SOURCE_MOUSE, id = 1, expectedId = 1), MotionEventData(MotionEvent.ACTION_CANCEL, SOURCE_MOUSE, id = 2, expectedId = 2), - MotionEventData(MotionEvent.ACTION_SCROLL, SOURCE_MOUSE, id = 3, expectedId = 3) + MotionEventData(MotionEvent.ACTION_SCROLL, SOURCE_MOUSE, id = 3, expectedId = 3), ) } - /** - * After a cancel event, motion events should be assigned their own event id - */ + /** After a cancel event, motion events should be assigned their own event id */ @Test fun testStylusDownCancelAndHover() { checkEventStream( MotionEventData(MotionEvent.ACTION_DOWN, SOURCE_STYLUS, id = 1, expectedId = 1), MotionEventData(MotionEvent.ACTION_CANCEL, SOURCE_STYLUS, id = 2, expectedId = 2), - MotionEventData(MotionEvent.ACTION_HOVER_ENTER, SOURCE_STYLUS, id = 3, expectedId = 3) + MotionEventData(MotionEvent.ACTION_HOVER_ENTER, SOURCE_STYLUS, id = 3, expectedId = 3), ) } - /** - * KeyEvents are processed immediately, so the latest event should be returned. - */ + /** KeyEvents are processed immediately, so the latest event should be returned. */ @Test fun testKeyEvent() { val assigner = InputEventAssigner() diff --git a/tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt b/tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt index 075cf0cc5a45..acd5a7d3f9e2 100644 --- a/tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt +++ b/tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt @@ -22,8 +22,8 @@ import android.view.InputChannel import android.view.InputEvent import android.view.InputEventReceiver import android.view.KeyEvent -import org.junit.Assert.assertEquals import org.junit.After +import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test @@ -42,12 +42,17 @@ private fun assertKeyEvent(expected: KeyEvent, received: KeyEvent) { } private fun getTestKeyEvent(): KeyEvent { - return KeyEvent(1 /*downTime*/, 1 /*eventTime*/, KeyEvent.ACTION_DOWN, - KeyEvent.KEYCODE_A, 0 /*repeat*/) + return KeyEvent( + 1 /*downTime*/, + 1 /*eventTime*/, + KeyEvent.ACTION_DOWN, + KeyEvent.KEYCODE_A, + 0, /*repeat*/ + ) } private class CrashingInputEventReceiver(channel: InputChannel, looper: Looper) : - InputEventReceiver(channel, looper) { + InputEventReceiver(channel, looper) { override fun onInputEvent(event: InputEvent) { try { throw IllegalArgumentException("This receiver crashes when it receives input event") @@ -61,6 +66,7 @@ class InputEventSenderAndReceiverTest { companion object { private const val TAG = "InputEventSenderAndReceiverTest" } + private val mHandlerThread = HandlerThread("Process input events") private lateinit var mReceiver: SpyInputEventReceiver private lateinit var mSender: SpyInputEventSender @@ -98,8 +104,8 @@ class InputEventSenderAndReceiverTest { // The timeline case is slightly unusual because it goes from InputConsumer to InputPublisher. @Test fun testSendAndReceiveTimeline() { - val sent = SpyInputEventSender.Timeline( - inputEventId = 1, gpuCompletedTime = 2, presentTime = 3) + val sent = + SpyInputEventSender.Timeline(inputEventId = 1, gpuCompletedTime = 2, presentTime = 3) mReceiver.reportTimeline(sent.inputEventId, sent.gpuCompletedTime, sent.presentTime) val received = mSender.getTimeline() assertEquals(sent, received) @@ -110,8 +116,8 @@ class InputEventSenderAndReceiverTest { // event processing. @Test fun testSendAndReceiveInvalidTimeline() { - val sent = SpyInputEventSender.Timeline( - inputEventId = 1, gpuCompletedTime = 3, presentTime = 2) + val sent = + SpyInputEventSender.Timeline(inputEventId = 1, gpuCompletedTime = 3, presentTime = 2) mReceiver.reportTimeline(sent.inputEventId, sent.gpuCompletedTime, sent.presentTime) mSender.assertNoEvents() // Sender will no longer receive callbacks for this fd, even if receiver sends a valid @@ -123,9 +129,8 @@ class InputEventSenderAndReceiverTest { /** * If a receiver throws an exception during 'onInputEvent' execution, the 'finally' block still * completes, and therefore, finishInputEvent is called. Make sure that there's no crash in the - * native layer in these circumstances. - * In this test, we are reusing the 'mHandlerThread', but we are creating new sender and - * receiver. + * native layer in these circumstances. In this test, we are reusing the 'mHandlerThread', but + * we are creating new sender and receiver. */ @Test fun testCrashingReceiverDoesNotCrash() { diff --git a/tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt b/tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt index 860d9f680c4c..4ca08d839c54 100644 --- a/tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt +++ b/tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt @@ -18,12 +18,9 @@ package com.android.test.input import android.platform.test.annotations.EnableFlags import android.platform.test.flag.junit.SetFlagsRule - import android.view.KeyCharacterMap import android.view.KeyEvent - import com.android.hardware.input.Flags - import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Rule @@ -32,13 +29,10 @@ import org.junit.Test /** * Tests for {@link KeyCharacterMap}. * - * <p>Build/Install/Run: - * atest KeyCharacterMapTest - * + * <p>Build/Install/Run: atest KeyCharacterMapTest */ class KeyCharacterMapTest { - @get:Rule - val setFlagsRule = SetFlagsRule() + @get:Rule val setFlagsRule = SetFlagsRule() @Test @EnableFlags(Flags.FLAG_REMOVE_FALLBACK_MODIFIERS) @@ -47,28 +41,33 @@ class KeyCharacterMapTest { val keyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD) // One modifier fallback. - val oneModifierFallback = keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_SPACE, - KeyEvent.META_CTRL_ON) + val oneModifierFallback = + keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_SPACE, KeyEvent.META_CTRL_ON) assertEquals(KeyEvent.KEYCODE_LANGUAGE_SWITCH, oneModifierFallback.keyCode) assertEquals(0, oneModifierFallback.metaState) // Multiple modifier fallback. - val twoModifierFallback = keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_DEL, - KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON) + val twoModifierFallback = + keyCharacterMap.getFallbackAction( + KeyEvent.KEYCODE_DEL, + KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON, + ) assertEquals(KeyEvent.KEYCODE_BACK, twoModifierFallback.keyCode) assertEquals(0, twoModifierFallback.metaState) // No default button, fallback only. - val keyOnlyFallback = - keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_BUTTON_A, 0) + val keyOnlyFallback = keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_BUTTON_A, 0) assertEquals(KeyEvent.KEYCODE_DPAD_CENTER, keyOnlyFallback.keyCode) assertEquals(0, keyOnlyFallback.metaState) // A key event that is not an exact match for a fallback. Expect a null return. // E.g. Ctrl + Space -> LanguageSwitch // Ctrl + Alt + Space -> Ctrl + Alt + Space (No fallback). - val noMatchFallback = keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_SPACE, - KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON) + val noMatchFallback = + keyCharacterMap.getFallbackAction( + KeyEvent.KEYCODE_SPACE, + KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON, + ) assertNull(noMatchFallback) } } diff --git a/tests/Input/src/com/android/test/input/MockInputManagerRule.kt b/tests/Input/src/com/android/test/input/MockInputManagerRule.kt index cef985600c40..8fa5f4a03749 100644 --- a/tests/Input/src/com/android/test/input/MockInputManagerRule.kt +++ b/tests/Input/src/com/android/test/input/MockInputManagerRule.kt @@ -21,8 +21,8 @@ import org.junit.rules.ExternalResource import org.mockito.Mockito /** - * A test rule that temporarily replaces the [IInputManager] connection to the server with a mock - * to be used for testing. + * A test rule that temporarily replaces the [IInputManager] connection to the server with a mock to + * be used for testing. */ class MockInputManagerRule : ExternalResource() { diff --git a/tests/Input/src/com/android/test/input/MotionPredictorTest.kt b/tests/Input/src/com/android/test/input/MotionPredictorTest.kt index d3eeac147c2a..784eb1b37765 100644 --- a/tests/Input/src/com/android/test/input/MotionPredictorTest.kt +++ b/tests/Input/src/com/android/test/input/MotionPredictorTest.kt @@ -26,11 +26,10 @@ import android.view.MotionEvent.ACTION_MOVE import android.view.MotionEvent.PointerCoords import android.view.MotionEvent.PointerProperties import android.view.MotionPredictor - import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry - +import java.time.Duration import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull @@ -40,14 +39,12 @@ import org.junit.runner.RunWith import org.mockito.Mockito.mock import org.mockito.Mockito.`when` -import java.time.Duration - private fun getStylusMotionEvent( - eventTime: Duration, - action: Int, - x: Float, - y: Float, - ): MotionEvent{ + eventTime: Duration, + action: Int, + x: Float, + y: Float, +): MotionEvent { val pointerCount = 1 val properties = arrayOfNulls<MotionEvent.PointerProperties>(pointerCount) val coords = arrayOfNulls<MotionEvent.PointerCoords>(pointerCount) @@ -61,21 +58,32 @@ private fun getStylusMotionEvent( coords[i]!!.y = y } - return MotionEvent.obtain(/*downTime=*/0, eventTime.toMillis(), action, properties.size, - properties, coords, /*metaState=*/0, /*buttonState=*/0, - /*xPrecision=*/0f, /*yPrecision=*/0f, /*deviceId=*/0, /*edgeFlags=*/0, - InputDevice.SOURCE_STYLUS, /*flags=*/0) + return MotionEvent.obtain( + /*downTime=*/ 0, + eventTime.toMillis(), + action, + properties.size, + properties, + coords, + /*metaState=*/ 0, + /*buttonState=*/ 0, + /*xPrecision=*/ 0f, + /*yPrecision=*/ 0f, + /*deviceId=*/ 0, + /*edgeFlags=*/ 0, + InputDevice.SOURCE_STYLUS, + /*flags=*/ 0, + ) } private fun getPredictionContext(offset: Duration, enablePrediction: Boolean): Context { val context = mock(Context::class.java) val resources: Resources = mock(Resources::class.java) `when`(context.getResources()).thenReturn(resources) - `when`(resources.getInteger( - com.android.internal.R.integer.config_motionPredictionOffsetNanos)).thenReturn( - offset.toNanos().toInt()) - `when`(resources.getBoolean( - com.android.internal.R.bool.config_enableMotionPrediction)).thenReturn(enablePrediction) + `when`(resources.getInteger(com.android.internal.R.integer.config_motionPredictionOffsetNanos)) + .thenReturn(offset.toNanos().toInt()) + `when`(resources.getBoolean(com.android.internal.R.bool.config_enableMotionPrediction)) + .thenReturn(enablePrediction) return context } @@ -88,38 +96,36 @@ class MotionPredictorTest { @Before fun setUp() { instrumentation.uiAutomation.executeShellCommand( - "setprop persist.input.enable_motion_prediction true") + "setprop persist.input.enable_motion_prediction true" + ) } @After fun tearDown() { instrumentation.uiAutomation.executeShellCommand( - "setprop persist.input.enable_motion_prediction $initialPropertyValue") + "setprop persist.input.enable_motion_prediction $initialPropertyValue" + ) } /** - * In a typical usage, app will send the event to the predictor and then call .predict to draw - * a prediction. Here, we send 2 events to the predictor and check the returned event. - * Input: - * t = 0 x = 0 y = 0 - * t = 4 x = 10 y = 20 - * Output (expected): - * t = 12 x = 30 y = 60 ± error + * In a typical usage, app will send the event to the predictor and then call .predict to draw a + * prediction. Here, we send 2 events to the predictor and check the returned event. Input: t = + * 0 x = 0 y = 0 t = 4 x = 10 y = 20 Output (expected): t = 12 x = 30 y = 60 ± error * * Historical data is ignored for simplicity. */ @Test fun testPredictedCoordinatesAndTime() { - val context = getPredictionContext( - /*offset=*/Duration.ofMillis(1), /*enablePrediction=*/true) + val context = + getPredictionContext(/* offset= */ Duration.ofMillis(1), /* enablePrediction= */ true) val predictor = MotionPredictor(context) var eventTime = Duration.ofMillis(0) - val downEvent = getStylusMotionEvent(eventTime, ACTION_DOWN, /*x=*/0f, /*y=*/0f) + val downEvent = getStylusMotionEvent(eventTime, ACTION_DOWN, /* x= */ 0f, /* y= */ 0f) // ACTION_DOWN t=0 x=0 y=0 predictor.record(downEvent) eventTime += Duration.ofMillis(4) - val moveEvent = getStylusMotionEvent(eventTime, ACTION_MOVE, /*x=*/10f, /*y=*/20f) + val moveEvent = getStylusMotionEvent(eventTime, ACTION_MOVE, /* x= */ 10f, /* y= */ 20f) // ACTION_MOVE t=1 x=1 y=2 predictor.record(moveEvent) @@ -129,7 +135,7 @@ class MotionPredictorTest { // Prediction will happen for t=12 (since it is the next input interval after the requested // time, 8, plus the model offset, 1). assertEquals(12, predicted!!.eventTime) - assertEquals(30f, predicted.x, /*delta=*/10f) - assertEquals(60f, predicted.y, /*delta=*/15f) + assertEquals(30f, predicted.x, /* delta= */ 10f) + assertEquals(60f, predicted.y, /* delta= */ 15f) } } diff --git a/tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt b/tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt index f311bc222d22..3c4ba5a3cd09 100644 --- a/tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt +++ b/tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt @@ -21,11 +21,10 @@ import android.view.InputChannel import android.view.InputDevice import android.view.MotionEvent import android.view.WindowManagerPolicyConstants.PointerEventListener - import com.android.server.UiThread import com.android.server.wm.PointerEventDispatcher -import org.junit.Assert.assertEquals import org.junit.After +import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test @@ -39,6 +38,7 @@ class PointerEventDispatcherTest { companion object { private const val TAG = "PointerEventDispatcherTest" } + private val mHandlerThread = HandlerThread("Process input events") private lateinit var mSender: SpyInputEventSender private lateinit var mPointerEventDispatcher: PointerEventDispatcher @@ -75,8 +75,15 @@ class PointerEventDispatcherTest { // The MotionEvent properties aren't important for this test, as long as the event // is a pointer event, so that it gets processed by CrashingPointerEventListener val downTime = 0L - val motionEvent = MotionEvent.obtain(downTime, downTime, - MotionEvent.ACTION_DOWN, 0f /* x */, 0f /* y */, 0 /* metaState */) + val motionEvent = + MotionEvent.obtain( + downTime, + downTime, + MotionEvent.ACTION_DOWN, + 0f /* x */, + 0f /* y */, + 0, /* metaState */ + ) motionEvent.source = InputDevice.SOURCE_TOUCHSCREEN val seq = 10 mSender.sendInputEvent(seq, motionEvent) diff --git a/tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt b/tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt index abfe549f3d22..443ef6937c53 100644 --- a/tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt +++ b/tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt @@ -42,8 +42,7 @@ import platform.test.screenshot.matchers.PixelPerfectMatcher /** * Unit tests for PointerIcon. * - * Run with: - * atest InputTests:com.android.test.input.PointerIconLoadingTest + * Run with: atest InputTests:com.android.test.input.PointerIconLoadingTest */ @SmallTest @RunWith(AndroidJUnit4::class) @@ -51,16 +50,19 @@ class PointerIconLoadingTest { private lateinit var context: Context private lateinit var exactScreenshotMatcher: BitmapMatcher - @get:Rule - val testName = TestName() + @get:Rule val testName = TestName() @get:Rule - val screenshotRule = ScreenshotTestRule(GoldenPathManager( - InstrumentationRegistry.getInstrumentation().getContext(), - ASSETS_PATH, - TEST_OUTPUT_PATH, - PathConfig() - ), disableIconPool = false) + val screenshotRule = + ScreenshotTestRule( + GoldenPathManager( + InstrumentationRegistry.getInstrumentation().getContext(), + ASSETS_PATH, + TEST_OUTPUT_PATH, + PathConfig(), + ), + disableIconPool = false, + ) @Before fun setUp() { @@ -86,22 +88,26 @@ class PointerIconLoadingTest { theme.setTo(context.getTheme()) theme.applyStyle( PointerIcon.vectorFillStyleToResource(PointerIcon.POINTER_ICON_VECTOR_STYLE_FILL_GREEN), - /* force= */ true) - theme.applyStyle(PointerIcon.vectorStrokeStyleToResource( - PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_WHITE), /* force= */ true) + /* force= */ true, + ) + theme.applyStyle( + PointerIcon.vectorStrokeStyleToResource( + PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_WHITE + ), + /* force= */ true, + ) val pointerIcon = PointerIcon.getLoadedSystemIcon( ContextThemeWrapper(context, theme), PointerIcon.TYPE_ARROW, /* useLargeIcons= */ false, - /* pointerScale= */ 1f) + /* pointerScale= */ 1f, + ) - pointerIcon.getBitmap().assertAgainstGolden( - screenshotRule, - testName.methodName, - exactScreenshotMatcher - ) + pointerIcon + .getBitmap() + .assertAgainstGolden(screenshotRule, testName.methodName, exactScreenshotMatcher) } @Test @@ -113,22 +119,26 @@ class PointerIconLoadingTest { theme.setTo(context.getTheme()) theme.applyStyle( PointerIcon.vectorFillStyleToResource(PointerIcon.POINTER_ICON_VECTOR_STYLE_FILL_BLACK), - /* force= */ true) - theme.applyStyle(PointerIcon.vectorStrokeStyleToResource( - PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_BLACK), /* force= */ true) + /* force= */ true, + ) + theme.applyStyle( + PointerIcon.vectorStrokeStyleToResource( + PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_BLACK + ), + /* force= */ true, + ) val pointerIcon = PointerIcon.getLoadedSystemIcon( ContextThemeWrapper(context, theme), PointerIcon.TYPE_ARROW, /* useLargeIcons= */ false, - /* pointerScale= */ 1f) + /* pointerScale= */ 1f, + ) - pointerIcon.getBitmap().assertAgainstGolden( - screenshotRule, - testName.methodName, - exactScreenshotMatcher - ) + pointerIcon + .getBitmap() + .assertAgainstGolden(screenshotRule, testName.methodName, exactScreenshotMatcher) } @Test @@ -140,11 +150,14 @@ class PointerIconLoadingTest { theme.setTo(context.getTheme()) theme.applyStyle( PointerIcon.vectorFillStyleToResource(PointerIcon.POINTER_ICON_VECTOR_STYLE_FILL_BLACK), - /* force= */ true) + /* force= */ true, + ) theme.applyStyle( PointerIcon.vectorStrokeStyleToResource( - PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_WHITE), - /* force= */ true) + PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_WHITE + ), + /* force= */ true, + ) val pointerScale = 2f val pointerIcon = @@ -152,13 +165,12 @@ class PointerIconLoadingTest { ContextThemeWrapper(context, theme), PointerIcon.TYPE_ARROW, /* useLargeIcons= */ false, - pointerScale) + pointerScale, + ) - pointerIcon.getBitmap().assertAgainstGolden( - screenshotRule, - testName.methodName, - exactScreenshotMatcher - ) + pointerIcon + .getBitmap() + .assertAgainstGolden(screenshotRule, testName.methodName, exactScreenshotMatcher) } companion object { diff --git a/tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt b/tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt index 5cbfce534b15..05aa5e91132b 100644 --- a/tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt +++ b/tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt @@ -26,7 +26,6 @@ import android.view.KeyEvent import android.view.MotionEvent import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit - import org.junit.Assert.assertNull private fun <T> getEvent(queue: LinkedBlockingQueue<T>): T? { @@ -39,7 +38,7 @@ private fun <T> assertNoEvents(queue: LinkedBlockingQueue<T>) { } class SpyInputEventReceiver(channel: InputChannel, looper: Looper) : - InputEventReceiver(channel, looper) { + InputEventReceiver(channel, looper) { private val mInputEvents = LinkedBlockingQueue<InputEvent>() override fun onInputEvent(event: InputEvent) { @@ -57,8 +56,9 @@ class SpyInputEventReceiver(channel: InputChannel, looper: Looper) : } class SpyInputEventSender(channel: InputChannel, looper: Looper) : - InputEventSender(channel, looper) { + InputEventSender(channel, looper) { data class FinishedSignal(val seq: Int, val handled: Boolean) + data class Timeline(val inputEventId: Int, val gpuCompletedTime: Long, val presentTime: Long) private val mFinishedSignals = LinkedBlockingQueue<FinishedSignal>() diff --git a/tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt b/tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt index 1a0837b6d3d7..49b224a751b6 100644 --- a/tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt +++ b/tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt @@ -59,9 +59,7 @@ import org.junit.runners.Parameterized class UinputRecordingIntegrationTests { companion object { - /** - * Add new test cases by adding a new [TestData] to the following list. - */ + /** Add new test cases by adding a new [TestData] to the following list. */ @JvmStatic @Parameterized.Parameters(name = "{0}") fun data(): Iterable<Any> = @@ -74,12 +72,10 @@ class UinputRecordingIntegrationTests { vendorId = 0x0603, productId = 0x7806, deviceSources = InputDevice.SOURCE_TOUCHSCREEN, - ), + ) ) - /** - * Use the debug mode to see the JSON-encoded received events in logcat. - */ + /** Use the debug mode to see the JSON-encoded received events in logcat. */ const val DEBUG_RECEIVED_EVENTS = false const val INPUT_DEVICE_SOURCE_ALL = -1 @@ -101,14 +97,11 @@ class UinputRecordingIntegrationTests { private lateinit var instrumentation: Instrumentation private lateinit var parser: InputJsonParser - @get:Rule - val debugInputRule = DebugInputRule() + @get:Rule val debugInputRule = DebugInputRule() - @get:Rule - val testName = TestName() + @get:Rule val testName = TestName() - @Parameterized.Parameter(0) - lateinit var testData: TestData + @Parameterized.Parameter(0) lateinit var testData: TestData @Before fun setUp() { @@ -120,43 +113,47 @@ class UinputRecordingIntegrationTests { @Test fun testEvemuRecording() { VirtualDisplayActivityScenario.AutoClose<CaptureEventActivity>( - testName, - size = testData.displaySize - ).use { scenario -> - scenario.activity.window.decorView.requestUnbufferedDispatch(INPUT_DEVICE_SOURCE_ALL) - - EvemuDevice( - instrumentation, - testData.deviceSources, - testData.vendorId, - testData.productId, - testData.uinputRecordingResource, - scenario.virtualDisplay.display - ).use { evemuDevice -> - - evemuDevice.injectEvents() - - if (DEBUG_RECEIVED_EVENTS) { - printReceivedEventsToLogcat(scenario.activity) - fail("Test cannot pass in debug mode!") - } - - val verifier = EventVerifier( - BatchedEventSplitter { scenario.activity.getInputEvent() } + testName, + size = testData.displaySize, + ) + .use { scenario -> + scenario.activity.window.decorView.requestUnbufferedDispatch( + INPUT_DEVICE_SOURCE_ALL ) - verifyEvents(verifier) - scenario.activity.assertNoEvents() + + EvemuDevice( + instrumentation, + testData.deviceSources, + testData.vendorId, + testData.productId, + testData.uinputRecordingResource, + scenario.virtualDisplay.display, + ) + .use { evemuDevice -> + evemuDevice.injectEvents() + + if (DEBUG_RECEIVED_EVENTS) { + printReceivedEventsToLogcat(scenario.activity) + fail("Test cannot pass in debug mode!") + } + + val verifier = + EventVerifier( + BatchedEventSplitter { scenario.activity.getInputEvent() } + ) + verifyEvents(verifier) + scenario.activity.assertNoEvents() + } } - } } private fun printReceivedEventsToLogcat(activity: CaptureEventActivity) { val getNextEvent = BatchedEventSplitter { activity.getInputEvent() } var receivedEvent: InputEvent? = getNextEvent() while (receivedEvent != null) { - Log.d(TAG, - parser.encodeEvent(receivedEvent)?.toString() - ?: "(Failed to encode received event)" + Log.d( + TAG, + parser.encodeEvent(receivedEvent)?.toString() ?: "(Failed to encode received event)", ) receivedEvent = getNextEvent() } diff --git a/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt b/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt index 1e44617af111..0366abed1d48 100644 --- a/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt +++ b/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt @@ -1,17 +1,15 @@ /** * Copyright (c) 2020 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. */ // InputMonitor is deprecated, but we still need to test it. diff --git a/tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt b/tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt index 6ef1ecdae59b..8405a67332ef 100644 --- a/tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt +++ b/tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt @@ -28,6 +28,7 @@ class ViewFrameInfoTest { companion object { private const val TAG = "ViewFrameInfoTest" } + private val mViewFrameInfo = ViewFrameInfo() private var mTimeStarted: Long = 0 @@ -65,8 +66,8 @@ class ViewFrameInfoTest { // The values inside FrameInfo should match those from ViewFrameInfo after we update them mViewFrameInfo.populateFrameInfo(frameInfo) assertThat(frameInfo.frameInfo[FrameInfo.INPUT_EVENT_ID]).isEqualTo(139) - assertThat(frameInfo.frameInfo[FrameInfo.FLAGS]).isEqualTo( - FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED) + assertThat(frameInfo.frameInfo[FrameInfo.FLAGS]) + .isEqualTo(FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED) assertThat(frameInfo.frameInfo[FrameInfo.DRAW_START]).isGreaterThan(mTimeStarted) } -}
\ No newline at end of file +} |