1 /* <lambda>null2 * Copyright 2023 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 package android.input.cts.hostside.app 17 18 import android.app.Activity 19 import android.content.Context 20 import android.graphics.Point 21 import android.util.DisplayMetrics 22 import android.util.Size 23 import android.view.InputDevice 24 import androidx.test.ext.junit.rules.ActivityScenarioRule 25 import androidx.test.ext.junit.runners.AndroidJUnit4 26 import androidx.test.platform.app.InstrumentationRegistry 27 import com.android.cts.input.UinputTouchDevice 28 import org.junit.After 29 import org.junit.Before 30 import org.junit.Rule 31 import org.junit.Test 32 import org.junit.runner.RunWith 33 34 /** 35 * This class contains device-side parts of input host tests. In particular, it is used to 36 * emulate input device connections and interactions for host tests. 37 */ 38 @RunWith(AndroidJUnit4::class) 39 class EmulateInputDevice { 40 private val instrumentation = InstrumentationRegistry.getInstrumentation() 41 private lateinit var context: Context 42 private lateinit var screenSize: Size 43 44 @get:Rule 45 val activityRule = ActivityScenarioRule(Activity::class.java) 46 47 @Suppress("DEPRECATION") 48 @Before 49 fun setUp() { 50 activityRule.scenario.onActivity { context = it } 51 val dm = DisplayMetrics().also { context.display!!.getRealMetrics(it) } 52 screenSize = Size(dm.widthPixels, dm.heightPixels) 53 } 54 55 @After 56 fun tearDown() { 57 } 58 59 /** 60 * Registers a USB touchscreen through uinput, interacts with it for at least 61 * five seconds, and disconnects the device. 62 */ 63 @Test 64 fun useTouchscreenForFiveSeconds() { 65 UinputTouchDevice( 66 instrumentation, 67 context.display!!, 68 screenSize, 69 R.raw.test_touchscreen_register, 70 InputDevice.SOURCE_TOUCHSCREEN 71 ).use { touchscreen -> 72 // Start the usage session. 73 touchscreen.tapOnScreen() 74 75 // Continue using the touchscreen for at least five more seconds. 76 for (i in 0 until 5) { 77 Thread.sleep(1000) 78 touchscreen.tapOnScreen() 79 } 80 } 81 } 82 83 private fun UinputTouchDevice.tapOnScreen() { 84 val pointer = Point(screenSize.width / 2, screenSize.height / 2) 85 86 // Down 87 sendBtnTouch(true) 88 sendDown(0 /*id*/, pointer) 89 90 // Move 91 pointer.offset(1, 1) 92 sendMove(0 /*id*/, pointer) 93 94 // Up 95 sendBtnTouch(false) 96 sendUp(0 /*id*/) 97 } 98 } 99