• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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
17 
18 import android.content.BroadcastReceiver
19 import android.content.Context
20 import android.content.Intent
21 import android.content.IntentFilter
22 import android.os.Handler
23 import android.os.HandlerThread
24 import android.os.Looper
25 import android.os.SystemClock
26 import android.view.InputDevice
27 import android.view.MotionEvent
28 import android.view.MotionEvent.ACTION_CANCEL
29 import android.view.MotionEvent.ACTION_DOWN
30 import android.view.MotionEvent.ACTION_MOVE
31 import android.view.View
32 import androidx.test.ext.junit.rules.ActivityScenarioRule
33 import androidx.test.ext.junit.runners.AndroidJUnit4
34 import androidx.test.filters.MediumTest
35 import androidx.test.platform.app.InstrumentationRegistry
36 import com.android.compatibility.common.util.PollingCheck
37 import java.util.concurrent.CompletableFuture
38 import java.util.concurrent.atomic.AtomicBoolean
39 import kotlin.concurrent.thread
40 import org.junit.Before
41 import org.junit.Rule
42 import org.junit.Test
43 import org.junit.runner.RunWith
44 
45 private const val OVERLAY_ACTIVITY_FOCUSED = "android.input.cts.action.OVERLAY_ACTIVITY_FOCUSED"
46 
getViewCenterOnScreennull47 private fun getViewCenterOnScreen(v: View): Pair<Float, Float> {
48     val location = IntArray(2)
49     v.getLocationOnScreen(location)
50     val x = location[0].toFloat() + v.width / 2
51     val y = location[1].toFloat() + v.height / 2
52     return Pair(x, y)
53 }
54 
55 /**
56  * When OverlayActivity receives focus, it will send out the OVERLAY_ACTIVITY_FOCUSED broadcast.
57  */
58 class OverlayFocusedBroadcastReceiver : BroadcastReceiver() {
59     private val isFocused = AtomicBoolean(false)
onReceivenull60     override fun onReceive(context: Context, intent: Intent) {
61         isFocused.set(true)
62     }
63 
overlayActivityIsFocusednull64     fun overlayActivityIsFocused(): Boolean {
65         return isFocused.get()
66     }
67 }
68 
69 /**
70  * This test injects an incomplete event stream and makes sure that the app processes it correctly.
71  * If it does not process it correctly, it can get ANRd.
72  *
73  * This test reproduces a bug where there was incorrect consumption logic in the InputEventReceiver
74  * jni code. If the system has this bug, this test ANRs.
75  * The bug occurs when the app consumes a focus event right after a batched MOVE event.
76  * In this test, we take care to write a batched MOVE event and a focus event prior to unblocking
77  * the UI thread to let the app process these events.
78  */
79 @MediumTest
80 @RunWith(AndroidJUnit4::class)
81 class IncompleteMotionTest {
82     @get:Rule
83     val activityRule = ActivityScenarioRule(IncompleteMotionActivity::class.java)
84     private lateinit var activity: IncompleteMotionActivity
85     private val instrumentation = InstrumentationRegistry.getInstrumentation()
86 
87     @Before
setUpnull88     fun setUp() {
89         activityRule.getScenario().onActivity {
90             activity = it
91         }
92         PollingCheck.waitFor { activity.hasWindowFocus() }
93     }
94 
95     /**
96      * Check that MOVE event is received by the activity, even if it's coupled with a FOCUS event.
97      */
98     @Test
testIncompleteMotionnull99     fun testIncompleteMotion() {
100         val downTime = SystemClock.uptimeMillis()
101         val (x, y) = getViewCenterOnScreen(activity.window.decorView)
102 
103         // Start a valid touch stream
104         sendEvent(downTime, ACTION_DOWN, x, y, true /*sync*/)
105         val resultFuture = CompletableFuture<Void>()
106         // Lock up the UI thread. This ensures that the motion event that we will write will
107         // not get processed by the app right away.
108         activity.runOnUiThread {
109             val sendMoveAndFocus = thread(start = true) {
110                 try {
111                     sendEvent(downTime, ACTION_MOVE, x, y + 10, false /*sync*/)
112                     // The MOVE event is sent async because the UI thread is blocked.
113                     // Give dispatcher some time to send it to the app
114                     SystemClock.sleep(700)
115 
116                     val handlerThread = HandlerThread("Receive broadcast from overlay activity")
117                     handlerThread.start()
118                     val looper: Looper = handlerThread.looper
119                     val handler = Handler(looper)
120                     val receiver = OverlayFocusedBroadcastReceiver()
121                     val intentFilter = IntentFilter(OVERLAY_ACTIVITY_FOCUSED)
122                     activity.registerReceiver(receiver, intentFilter, null, handler,
123                                           Context.RECEIVER_EXPORTED)
124 
125                     // Now send hasFocus=false event to the app by launching a new focusable window
126                     startOverlayActivity()
127                     PollingCheck.waitFor { receiver.overlayActivityIsFocused() }
128                     activity.unregisterReceiver(receiver)
129                     handlerThread.quit()
130                     // We need to ensure that the focus event has been written to the app's socket
131                     // before unblocking the UI thread. Having the overlay activity receive
132                     // hasFocus=true event is a good proxy for that. However, it does not guarantee
133                     // that dispatcher has written the hasFocus=false event to the current activity.
134                     // For safety, add another small sleep here
135                     SystemClock.sleep(300)
136                     resultFuture.complete(null)
137                 } catch (e: Throwable) {
138                     // Catch potential throwable as to not crash UI thread, rethrow and validate
139                     // outside.
140                     resultFuture.completeExceptionally(e)
141                 }
142             }
143             sendMoveAndFocus.join()
144         }
145         PollingCheck.waitFor { !activity.hasWindowFocus() }
146         // If the platform implementation has a bug, it would consume both MOVE and FOCUS events,
147         // but will only call 'finish' for the focus event.
148         // The MOVE event would not be propagated to the app, because the Choreographer
149         // callback never gets scheduled
150         // If we wait too long here, we will cause ANR (if the platform has a bug).
151         // If the MOVE event is received, however, we can stop the test.
152         PollingCheck.waitFor { activity.receivedMove() }
153         // Finish the gesture. No dangling injected pointers should remain
154         sendEvent(downTime, ACTION_CANCEL, x, y, true /*sync*/)
155         // Before finishing the test, check that no exceptions occurred while running the
156         // instructions in the 'sendMoveAndFocus' thread.
157         resultFuture.get()
158     }
159 
sendEventnull160     private fun sendEvent(downTime: Long, action: Int, x: Float, y: Float, sync: Boolean) {
161         val eventTime = when (action) {
162             ACTION_DOWN -> downTime
163             else -> SystemClock.uptimeMillis()
164         }
165         val event = MotionEvent.obtain(downTime, eventTime, action, x, y, 0 /*metaState*/)
166         event.source = InputDevice.SOURCE_TOUCHSCREEN
167         instrumentation.uiAutomation.injectInputEvent(event, sync)
168     }
169 
170     /**
171      * Start an activity that overlays the main activity. This is needed in order to move the focus
172      * to the newly launched activity, thus causing the bottom activity to lose focus.
173      * This activity is not full-screen, in order to prevent the bottom activity from receiving an
174      * onStop call. In the previous platform implementation, the ANR behaviour was incorrectly
175      * fixed by consuming events from the onStop event.
176      * Because the bottom activity's UI thread is locked, use 'am start' to start the new activity
177      */
startOverlayActivitynull178     private fun startOverlayActivity() {
179         val flags = " -W -n "
180         val startCmd = "am start $flags android.input.cts/.OverlayActivity"
181         instrumentation.uiAutomation.executeShellCommand(startCmd)
182     }
183 }
184