1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server.wm.flicker.helpers 18 19 import android.app.Instrumentation 20 import android.os.SystemClock 21 import android.view.KeyEvent.ACTION_DOWN 22 import android.view.KeyEvent.ACTION_UP 23 import android.view.KeyEvent 24 25 /** 26 * Helper class for injecting a custom key event. This is used for instrumenting keyboard shortcut 27 * actions. 28 */ 29 class KeyEventHelper( 30 private val instr: Instrumentation, 31 ) { pressnull32 fun press(keyCode: Int, metaState: Int = 0) { 33 actionDown(keyCode, metaState) 34 actionUp(keyCode, metaState) 35 } 36 actionDownnull37 fun actionDown(keyCode: Int, metaState: Int = 0, time: Long = SystemClock.uptimeMillis()) { 38 injectKeyEvent(ACTION_DOWN, keyCode, metaState, downTime = time, eventTime = time) 39 } 40 actionUpnull41 fun actionUp(keyCode: Int, metaState: Int = 0, time: Long = SystemClock.uptimeMillis()) { 42 injectKeyEvent(ACTION_UP, keyCode, metaState, downTime = time, eventTime = time) 43 } 44 injectKeyEventnull45 private fun injectKeyEvent( 46 action: Int, 47 keyCode: Int, 48 metaState: Int = 0, 49 downTime: Long = SystemClock.uptimeMillis(), 50 eventTime: Long = SystemClock.uptimeMillis() 51 ): KeyEvent { 52 val event = KeyEvent(downTime, eventTime, action, keyCode, /* repeat= */ 0, metaState) 53 injectKeyEvent(event) 54 return event 55 } 56 injectKeyEventnull57 private fun injectKeyEvent(event: KeyEvent) { 58 instr.uiAutomation.injectInputEvent(event, true) 59 } 60 }