1 /*
2 * Copyright (C) 2010 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 #include "../dispatcher/InputDispatcher.h"
18
19 #include <android-base/stringprintf.h>
20 #include <android-base/thread_annotations.h>
21 #include <binder/Binder.h>
22 #include <gtest/gtest.h>
23 #include <input/Input.h>
24 #include <linux/input.h>
25
26 #include <cinttypes>
27 #include <thread>
28 #include <unordered_set>
29 #include <vector>
30
31 using android::base::StringPrintf;
32 using android::gui::FocusRequest;
33 using android::gui::TouchOcclusionMode;
34 using android::gui::WindowInfo;
35 using android::gui::WindowInfoHandle;
36 using android::os::InputEventInjectionResult;
37 using android::os::InputEventInjectionSync;
38 using namespace android::flag_operators;
39
40 namespace android::inputdispatcher {
41
42 // An arbitrary time value.
43 static const nsecs_t ARBITRARY_TIME = 1234;
44
45 // An arbitrary device id.
46 static const int32_t DEVICE_ID = 1;
47
48 // An arbitrary display id.
49 static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
50 static constexpr int32_t SECOND_DISPLAY_ID = 1;
51
52 // An arbitrary injector pid / uid pair that has permission to inject events.
53 static const int32_t INJECTOR_PID = 999;
54 static const int32_t INJECTOR_UID = 1001;
55
56 // An arbitrary pid of the gesture monitor window
57 static constexpr int32_t MONITOR_PID = 2001;
58
59 struct PointF {
60 float x;
61 float y;
62 };
63
64 /**
65 * Return a DOWN key event with KEYCODE_A.
66 */
getTestKeyEvent()67 static KeyEvent getTestKeyEvent() {
68 KeyEvent event;
69
70 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
71 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
72 ARBITRARY_TIME, ARBITRARY_TIME);
73 return event;
74 }
75
76 // --- FakeInputDispatcherPolicy ---
77
78 class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
79 InputDispatcherConfiguration mConfig;
80
81 protected:
~FakeInputDispatcherPolicy()82 virtual ~FakeInputDispatcherPolicy() {}
83
84 public:
FakeInputDispatcherPolicy()85 FakeInputDispatcherPolicy() {}
86
assertFilterInputEventWasCalled(const NotifyKeyArgs & args)87 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
88 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
89 args.displayId);
90 }
91
assertFilterInputEventWasCalled(const NotifyMotionArgs & args)92 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
93 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
94 args.displayId);
95 }
96
assertFilterInputEventWasNotCalled()97 void assertFilterInputEventWasNotCalled() {
98 std::scoped_lock lock(mLock);
99 ASSERT_EQ(nullptr, mFilteredEvent);
100 }
101
assertNotifyConfigurationChangedWasCalled(nsecs_t when)102 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
103 std::scoped_lock lock(mLock);
104 ASSERT_TRUE(mConfigurationChangedTime)
105 << "Timed out waiting for configuration changed call";
106 ASSERT_EQ(*mConfigurationChangedTime, when);
107 mConfigurationChangedTime = std::nullopt;
108 }
109
assertNotifySwitchWasCalled(const NotifySwitchArgs & args)110 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
111 std::scoped_lock lock(mLock);
112 ASSERT_TRUE(mLastNotifySwitch);
113 // We do not check id because it is not exposed to the policy
114 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
115 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
116 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
117 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
118 mLastNotifySwitch = std::nullopt;
119 }
120
assertOnPointerDownEquals(const sp<IBinder> & touchedToken)121 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
122 std::scoped_lock lock(mLock);
123 ASSERT_EQ(touchedToken, mOnPointerDownToken);
124 mOnPointerDownToken.clear();
125 }
126
assertOnPointerDownWasNotCalled()127 void assertOnPointerDownWasNotCalled() {
128 std::scoped_lock lock(mLock);
129 ASSERT_TRUE(mOnPointerDownToken == nullptr)
130 << "Expected onPointerDownOutsideFocus to not have been called";
131 }
132
133 // This function must be called soon after the expected ANR timer starts,
134 // because we are also checking how much time has passed.
assertNotifyNoFocusedWindowAnrWasCalled(std::chrono::nanoseconds timeout,const std::shared_ptr<InputApplicationHandle> & expectedApplication)135 void assertNotifyNoFocusedWindowAnrWasCalled(
136 std::chrono::nanoseconds timeout,
137 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
138 std::shared_ptr<InputApplicationHandle> application;
139 { // acquire lock
140 std::unique_lock lock(mLock);
141 android::base::ScopedLockAssertion assumeLocked(mLock);
142 ASSERT_NO_FATAL_FAILURE(
143 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
144 } // release lock
145 ASSERT_EQ(expectedApplication, application);
146 }
147
assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,const sp<IBinder> & expectedConnectionToken)148 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
149 const sp<IBinder>& expectedConnectionToken) {
150 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
151 ASSERT_EQ(expectedConnectionToken, connectionToken);
152 }
153
assertNotifyWindowResponsiveWasCalled(const sp<IBinder> & expectedConnectionToken)154 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
155 sp<IBinder> connectionToken = getResponsiveWindowToken();
156 ASSERT_EQ(expectedConnectionToken, connectionToken);
157 }
158
assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout)159 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
160 int32_t pid = getUnresponsiveMonitorPid(timeout);
161 ASSERT_EQ(MONITOR_PID, pid);
162 }
163
assertNotifyMonitorResponsiveWasCalled()164 void assertNotifyMonitorResponsiveWasCalled() {
165 int32_t pid = getResponsiveMonitorPid();
166 ASSERT_EQ(MONITOR_PID, pid);
167 }
168
getUnresponsiveWindowToken(std::chrono::nanoseconds timeout)169 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
170 std::unique_lock lock(mLock);
171 android::base::ScopedLockAssertion assumeLocked(mLock);
172 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
173 }
174
getResponsiveWindowToken()175 sp<IBinder> getResponsiveWindowToken() {
176 std::unique_lock lock(mLock);
177 android::base::ScopedLockAssertion assumeLocked(mLock);
178 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
179 }
180
getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout)181 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
182 std::unique_lock lock(mLock);
183 android::base::ScopedLockAssertion assumeLocked(mLock);
184 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
185 }
186
getResponsiveMonitorPid()187 int32_t getResponsiveMonitorPid() {
188 std::unique_lock lock(mLock);
189 android::base::ScopedLockAssertion assumeLocked(mLock);
190 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
191 }
192
193 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
194 // for a specific container to become non-empty. When the container is non-empty, return the
195 // first entry from the container and erase it.
196 template <class T>
getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout,std::queue<T> & storage,std::unique_lock<std::mutex> & lock)197 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
198 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
199 const std::chrono::time_point start = std::chrono::steady_clock::now();
200 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
201
202 // If there is an ANR, Dispatcher won't be idle because there are still events
203 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
204 // before checking if ANR was called.
205 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
206 // to provide it some time to act. 100ms seems reasonable.
207 mNotifyAnr.wait_for(lock, timeToWait,
208 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
209 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
210 if (storage.empty()) {
211 ADD_FAILURE() << "Did not receive the ANR callback";
212 return {};
213 }
214 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
215 // the dispatcher started counting before this function was called
216 if (std::chrono::abs(timeout - waited) > 100ms) {
217 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
218 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
219 << "ms, but waited "
220 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
221 << "ms instead";
222 }
223 T token = storage.front();
224 storage.pop();
225 return token;
226 }
227
assertNotifyAnrWasNotCalled()228 void assertNotifyAnrWasNotCalled() {
229 std::scoped_lock lock(mLock);
230 ASSERT_TRUE(mAnrApplications.empty());
231 ASSERT_TRUE(mAnrWindowTokens.empty());
232 ASSERT_TRUE(mAnrMonitorPids.empty());
233 ASSERT_TRUE(mResponsiveWindowTokens.empty())
234 << "ANR was not called, but please also consume the 'connection is responsive' "
235 "signal";
236 ASSERT_TRUE(mResponsiveMonitorPids.empty())
237 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
238 " signal";
239 }
240
setKeyRepeatConfiguration(nsecs_t timeout,nsecs_t delay)241 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
242 mConfig.keyRepeatTimeout = timeout;
243 mConfig.keyRepeatDelay = delay;
244 }
245
assertSetPointerCaptureCalled(bool enabled)246 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
247 std::unique_lock lock(mLock);
248 base::ScopedLockAssertion assumeLocked(mLock);
249
250 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
251 [this, enabled]() REQUIRES(mLock) {
252 return mPointerCaptureRequest->enable ==
253 enabled;
254 })) {
255 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
256 << ") to be called.";
257 return {};
258 }
259 auto request = *mPointerCaptureRequest;
260 mPointerCaptureRequest.reset();
261 return request;
262 }
263
assertSetPointerCaptureNotCalled()264 void assertSetPointerCaptureNotCalled() {
265 std::unique_lock lock(mLock);
266 base::ScopedLockAssertion assumeLocked(mLock);
267
268 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
269 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
270 "enabled = "
271 << std::to_string(mPointerCaptureRequest->enable);
272 }
273 mPointerCaptureRequest.reset();
274 }
275
assertDropTargetEquals(const sp<IBinder> & targetToken)276 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
277 std::scoped_lock lock(mLock);
278 ASSERT_TRUE(mNotifyDropWindowWasCalled);
279 ASSERT_EQ(targetToken, mDropTargetWindowToken);
280 mNotifyDropWindowWasCalled = false;
281 }
282
283 private:
284 std::mutex mLock;
285 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
286 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
287 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
288 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
289
290 std::condition_variable mPointerCaptureChangedCondition;
291
292 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
293
294 // ANR handling
295 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
296 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
297 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
298 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
299 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
300 std::condition_variable mNotifyAnr;
301
302 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
303 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
304
notifyConfigurationChanged(nsecs_t when)305 void notifyConfigurationChanged(nsecs_t when) override {
306 std::scoped_lock lock(mLock);
307 mConfigurationChangedTime = when;
308 }
309
notifyWindowUnresponsive(const sp<IBinder> & connectionToken,const std::string &)310 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
311 std::scoped_lock lock(mLock);
312 mAnrWindowTokens.push(connectionToken);
313 mNotifyAnr.notify_all();
314 }
315
notifyMonitorUnresponsive(int32_t pid,const std::string &)316 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
317 std::scoped_lock lock(mLock);
318 mAnrMonitorPids.push(pid);
319 mNotifyAnr.notify_all();
320 }
321
notifyWindowResponsive(const sp<IBinder> & connectionToken)322 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
323 std::scoped_lock lock(mLock);
324 mResponsiveWindowTokens.push(connectionToken);
325 mNotifyAnr.notify_all();
326 }
327
notifyMonitorResponsive(int32_t pid)328 void notifyMonitorResponsive(int32_t pid) override {
329 std::scoped_lock lock(mLock);
330 mResponsiveMonitorPids.push(pid);
331 mNotifyAnr.notify_all();
332 }
333
notifyNoFocusedWindowAnr(const std::shared_ptr<InputApplicationHandle> & applicationHandle)334 void notifyNoFocusedWindowAnr(
335 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
336 std::scoped_lock lock(mLock);
337 mAnrApplications.push(applicationHandle);
338 mNotifyAnr.notify_all();
339 }
340
notifyInputChannelBroken(const sp<IBinder> &)341 void notifyInputChannelBroken(const sp<IBinder>&) override {}
342
notifyFocusChanged(const sp<IBinder> &,const sp<IBinder> &)343 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
344
notifyUntrustedTouch(const std::string & obscuringPackage)345 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
notifySensorEvent(int32_t deviceId,InputDeviceSensorType sensorType,InputDeviceSensorAccuracy accuracy,nsecs_t timestamp,const std::vector<float> & values)346 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
347 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
348 const std::vector<float>& values) override {}
349
notifySensorAccuracy(int deviceId,InputDeviceSensorType sensorType,InputDeviceSensorAccuracy accuracy)350 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
351 InputDeviceSensorAccuracy accuracy) override {}
352
notifyVibratorState(int32_t deviceId,bool isOn)353 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
354
getDispatcherConfiguration(InputDispatcherConfiguration * outConfig)355 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
356 *outConfig = mConfig;
357 }
358
filterInputEvent(const InputEvent * inputEvent,uint32_t policyFlags)359 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
360 std::scoped_lock lock(mLock);
361 switch (inputEvent->getType()) {
362 case AINPUT_EVENT_TYPE_KEY: {
363 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
364 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
365 break;
366 }
367
368 case AINPUT_EVENT_TYPE_MOTION: {
369 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
370 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
371 break;
372 }
373 }
374 return true;
375 }
376
interceptKeyBeforeQueueing(const KeyEvent *,uint32_t &)377 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
378
interceptMotionBeforeQueueing(int32_t,nsecs_t,uint32_t &)379 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
380
interceptKeyBeforeDispatching(const sp<IBinder> &,const KeyEvent *,uint32_t)381 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
382 return 0;
383 }
384
dispatchUnhandledKey(const sp<IBinder> &,const KeyEvent *,uint32_t,KeyEvent *)385 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
386 return false;
387 }
388
notifySwitch(nsecs_t when,uint32_t switchValues,uint32_t switchMask,uint32_t policyFlags)389 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
390 uint32_t policyFlags) override {
391 std::scoped_lock lock(mLock);
392 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
393 * essentially a passthrough for notifySwitch.
394 */
395 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
396 }
397
pokeUserActivity(nsecs_t,int32_t,int32_t)398 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
399
checkInjectEventsPermissionNonReentrant(int32_t pid,int32_t uid)400 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
401 return pid == INJECTOR_PID && uid == INJECTOR_UID;
402 }
403
onPointerDownOutsideFocus(const sp<IBinder> & newToken)404 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
405 std::scoped_lock lock(mLock);
406 mOnPointerDownToken = newToken;
407 }
408
setPointerCapture(const PointerCaptureRequest & request)409 void setPointerCapture(const PointerCaptureRequest& request) override {
410 std::scoped_lock lock(mLock);
411 mPointerCaptureRequest = {request};
412 mPointerCaptureChangedCondition.notify_all();
413 }
414
notifyDropWindow(const sp<IBinder> & token,float x,float y)415 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
416 std::scoped_lock lock(mLock);
417 mNotifyDropWindowWasCalled = true;
418 mDropTargetWindowToken = token;
419 }
420
assertFilterInputEventWasCalled(int type,nsecs_t eventTime,int32_t action,int32_t displayId)421 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
422 int32_t displayId) {
423 std::scoped_lock lock(mLock);
424 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
425 ASSERT_EQ(mFilteredEvent->getType(), type);
426
427 if (type == AINPUT_EVENT_TYPE_KEY) {
428 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
429 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
430 EXPECT_EQ(keyEvent.getAction(), action);
431 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
432 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
433 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
434 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
435 EXPECT_EQ(motionEvent.getAction(), action);
436 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
437 } else {
438 FAIL() << "Unknown type: " << type;
439 }
440
441 mFilteredEvent = nullptr;
442 }
443 };
444
445 // --- InputDispatcherTest ---
446
447 class InputDispatcherTest : public testing::Test {
448 protected:
449 sp<FakeInputDispatcherPolicy> mFakePolicy;
450 sp<InputDispatcher> mDispatcher;
451
SetUp()452 void SetUp() override {
453 mFakePolicy = new FakeInputDispatcherPolicy();
454 mDispatcher = new InputDispatcher(mFakePolicy);
455 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
456 // Start InputDispatcher thread
457 ASSERT_EQ(OK, mDispatcher->start());
458 }
459
TearDown()460 void TearDown() override {
461 ASSERT_EQ(OK, mDispatcher->stop());
462 mFakePolicy.clear();
463 mDispatcher.clear();
464 }
465
466 /**
467 * Used for debugging when writing the test
468 */
dumpDispatcherState()469 void dumpDispatcherState() {
470 std::string dump;
471 mDispatcher->dump(dump);
472 std::stringstream ss(dump);
473 std::string to;
474
475 while (std::getline(ss, to, '\n')) {
476 ALOGE("%s", to.c_str());
477 }
478 }
479
setFocusedWindow(const sp<WindowInfoHandle> & window,const sp<WindowInfoHandle> & focusedWindow=nullptr)480 void setFocusedWindow(const sp<WindowInfoHandle>& window,
481 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
482 FocusRequest request;
483 request.token = window->getToken();
484 request.windowName = window->getName();
485 if (focusedWindow) {
486 request.focusedToken = focusedWindow->getToken();
487 }
488 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
489 request.displayId = window->getInfo()->displayId;
490 mDispatcher->setFocusedWindow(request);
491 }
492 };
493
TEST_F(InputDispatcherTest,InjectInputEvent_ValidatesKeyEvents)494 TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
495 KeyEvent event;
496
497 // Rejects undefined key actions.
498 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
499 INVALID_HMAC,
500 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
501 ARBITRARY_TIME);
502 ASSERT_EQ(InputEventInjectionResult::FAILED,
503 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
504 InputEventInjectionSync::NONE, 0ms, 0))
505 << "Should reject key events with undefined action.";
506
507 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
508 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
509 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
510 ARBITRARY_TIME, ARBITRARY_TIME);
511 ASSERT_EQ(InputEventInjectionResult::FAILED,
512 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
513 InputEventInjectionSync::NONE, 0ms, 0))
514 << "Should reject key events with ACTION_MULTIPLE.";
515 }
516
TEST_F(InputDispatcherTest,InjectInputEvent_ValidatesMotionEvents)517 TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
518 MotionEvent event;
519 PointerProperties pointerProperties[MAX_POINTERS + 1];
520 PointerCoords pointerCoords[MAX_POINTERS + 1];
521 for (int i = 0; i <= MAX_POINTERS; i++) {
522 pointerProperties[i].clear();
523 pointerProperties[i].id = i;
524 pointerCoords[i].clear();
525 }
526
527 // Some constants commonly used below
528 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
529 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
530 constexpr int32_t metaState = AMETA_NONE;
531 constexpr MotionClassification classification = MotionClassification::NONE;
532
533 ui::Transform identityTransform;
534 // Rejects undefined motion actions.
535 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
536 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
537 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
538 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
539 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
540 /*pointerCount*/ 1, pointerProperties, pointerCoords);
541 ASSERT_EQ(InputEventInjectionResult::FAILED,
542 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
543 InputEventInjectionSync::NONE, 0ms, 0))
544 << "Should reject motion events with undefined action.";
545
546 // Rejects pointer down with invalid index.
547 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
548 AMOTION_EVENT_ACTION_POINTER_DOWN |
549 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
550 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
551 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
552 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
553 ARBITRARY_TIME, ARBITRARY_TIME,
554 /*pointerCount*/ 1, pointerProperties, pointerCoords);
555 ASSERT_EQ(InputEventInjectionResult::FAILED,
556 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
557 InputEventInjectionSync::NONE, 0ms, 0))
558 << "Should reject motion events with pointer down index too large.";
559
560 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
561 AMOTION_EVENT_ACTION_POINTER_DOWN |
562 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
563 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
564 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
565 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
566 ARBITRARY_TIME, ARBITRARY_TIME,
567 /*pointerCount*/ 1, pointerProperties, pointerCoords);
568 ASSERT_EQ(InputEventInjectionResult::FAILED,
569 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
570 InputEventInjectionSync::NONE, 0ms, 0))
571 << "Should reject motion events with pointer down index too small.";
572
573 // Rejects pointer up with invalid index.
574 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
575 AMOTION_EVENT_ACTION_POINTER_UP |
576 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
577 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
578 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
579 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
580 ARBITRARY_TIME, ARBITRARY_TIME,
581 /*pointerCount*/ 1, pointerProperties, pointerCoords);
582 ASSERT_EQ(InputEventInjectionResult::FAILED,
583 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
584 InputEventInjectionSync::NONE, 0ms, 0))
585 << "Should reject motion events with pointer up index too large.";
586
587 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
588 AMOTION_EVENT_ACTION_POINTER_UP |
589 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
590 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
591 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
592 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
593 ARBITRARY_TIME, ARBITRARY_TIME,
594 /*pointerCount*/ 1, pointerProperties, pointerCoords);
595 ASSERT_EQ(InputEventInjectionResult::FAILED,
596 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
597 InputEventInjectionSync::NONE, 0ms, 0))
598 << "Should reject motion events with pointer up index too small.";
599
600 // Rejects motion events with invalid number of pointers.
601 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
602 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
603 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
604 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
605 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
606 /*pointerCount*/ 0, pointerProperties, pointerCoords);
607 ASSERT_EQ(InputEventInjectionResult::FAILED,
608 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
609 InputEventInjectionSync::NONE, 0ms, 0))
610 << "Should reject motion events with 0 pointers.";
611
612 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
613 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
614 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
615 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
616 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
617 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
618 ASSERT_EQ(InputEventInjectionResult::FAILED,
619 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
620 InputEventInjectionSync::NONE, 0ms, 0))
621 << "Should reject motion events with more than MAX_POINTERS pointers.";
622
623 // Rejects motion events with invalid pointer ids.
624 pointerProperties[0].id = -1;
625 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
626 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
627 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
628 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
629 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
630 /*pointerCount*/ 1, pointerProperties, pointerCoords);
631 ASSERT_EQ(InputEventInjectionResult::FAILED,
632 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
633 InputEventInjectionSync::NONE, 0ms, 0))
634 << "Should reject motion events with pointer ids less than 0.";
635
636 pointerProperties[0].id = MAX_POINTER_ID + 1;
637 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
638 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
639 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
640 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
641 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
642 /*pointerCount*/ 1, pointerProperties, pointerCoords);
643 ASSERT_EQ(InputEventInjectionResult::FAILED,
644 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
645 InputEventInjectionSync::NONE, 0ms, 0))
646 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
647
648 // Rejects motion events with duplicate pointer ids.
649 pointerProperties[0].id = 1;
650 pointerProperties[1].id = 1;
651 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
652 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
653 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
654 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
655 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
656 /*pointerCount*/ 2, pointerProperties, pointerCoords);
657 ASSERT_EQ(InputEventInjectionResult::FAILED,
658 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
659 InputEventInjectionSync::NONE, 0ms, 0))
660 << "Should reject motion events with duplicate pointer ids.";
661 }
662
663 /* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
664
TEST_F(InputDispatcherTest,NotifyConfigurationChanged_CallsPolicy)665 TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
666 constexpr nsecs_t eventTime = 20;
667 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
668 mDispatcher->notifyConfigurationChanged(&args);
669 ASSERT_TRUE(mDispatcher->waitForIdle());
670
671 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
672 }
673
TEST_F(InputDispatcherTest,NotifySwitch_CallsPolicy)674 TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
675 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
676 2 /*switchMask*/);
677 mDispatcher->notifySwitch(&args);
678
679 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
680 args.policyFlags |= POLICY_FLAG_TRUSTED;
681 mFakePolicy->assertNotifySwitchWasCalled(args);
682 }
683
684 // --- InputDispatcherTest SetInputWindowTest ---
685 static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
686 static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
687
688 class FakeApplicationHandle : public InputApplicationHandle {
689 public:
FakeApplicationHandle()690 FakeApplicationHandle() {
691 mInfo.name = "Fake Application";
692 mInfo.token = new BBinder();
693 mInfo.dispatchingTimeoutMillis =
694 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
695 }
~FakeApplicationHandle()696 virtual ~FakeApplicationHandle() {}
697
updateInfo()698 virtual bool updateInfo() override { return true; }
699
setDispatchingTimeout(std::chrono::milliseconds timeout)700 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
701 mInfo.dispatchingTimeoutMillis = timeout.count();
702 }
703 };
704
705 class FakeInputReceiver {
706 public:
FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel,const std::string name)707 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
708 : mName(name) {
709 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
710 }
711
consume()712 InputEvent* consume() {
713 InputEvent* event;
714 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
715 if (!consumeSeq) {
716 return nullptr;
717 }
718 finishEvent(*consumeSeq);
719 return event;
720 }
721
722 /**
723 * Receive an event without acknowledging it.
724 * Return the sequence number that could later be used to send finished signal.
725 */
receiveEvent(InputEvent ** outEvent=nullptr)726 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
727 uint32_t consumeSeq;
728 InputEvent* event;
729
730 std::chrono::time_point start = std::chrono::steady_clock::now();
731 status_t status = WOULD_BLOCK;
732 while (status == WOULD_BLOCK) {
733 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
734 &event);
735 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
736 if (elapsed > 100ms) {
737 break;
738 }
739 }
740
741 if (status == WOULD_BLOCK) {
742 // Just means there's no event available.
743 return std::nullopt;
744 }
745
746 if (status != OK) {
747 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
748 return std::nullopt;
749 }
750 if (event == nullptr) {
751 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
752 return std::nullopt;
753 }
754 if (outEvent != nullptr) {
755 *outEvent = event;
756 }
757 return consumeSeq;
758 }
759
760 /**
761 * To be used together with "receiveEvent" to complete the consumption of an event.
762 */
finishEvent(uint32_t consumeSeq)763 void finishEvent(uint32_t consumeSeq) {
764 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
765 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
766 }
767
sendTimeline(int32_t inputEventId,std::array<nsecs_t,GraphicsTimeline::SIZE> timeline)768 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
769 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
770 ASSERT_EQ(OK, status);
771 }
772
consumeEvent(int32_t expectedEventType,int32_t expectedAction,std::optional<int32_t> expectedDisplayId,std::optional<int32_t> expectedFlags)773 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
774 std::optional<int32_t> expectedDisplayId,
775 std::optional<int32_t> expectedFlags) {
776 InputEvent* event = consume();
777
778 ASSERT_NE(nullptr, event) << mName.c_str()
779 << ": consumer should have returned non-NULL event.";
780 ASSERT_EQ(expectedEventType, event->getType())
781 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
782 << " event, got " << inputEventTypeToString(event->getType()) << " event";
783
784 if (expectedDisplayId.has_value()) {
785 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
786 }
787
788 switch (expectedEventType) {
789 case AINPUT_EVENT_TYPE_KEY: {
790 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
791 EXPECT_EQ(expectedAction, keyEvent.getAction());
792 if (expectedFlags.has_value()) {
793 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
794 }
795 break;
796 }
797 case AINPUT_EVENT_TYPE_MOTION: {
798 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
799 EXPECT_EQ(expectedAction, motionEvent.getAction());
800 if (expectedFlags.has_value()) {
801 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
802 }
803 break;
804 }
805 case AINPUT_EVENT_TYPE_FOCUS: {
806 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
807 }
808 case AINPUT_EVENT_TYPE_CAPTURE: {
809 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
810 }
811 case AINPUT_EVENT_TYPE_DRAG: {
812 FAIL() << "Use 'consumeDragEvent' for DRAG events";
813 }
814 default: {
815 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
816 }
817 }
818 }
819
consumeFocusEvent(bool hasFocus,bool inTouchMode)820 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
821 InputEvent* event = consume();
822 ASSERT_NE(nullptr, event) << mName.c_str()
823 << ": consumer should have returned non-NULL event.";
824 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
825 << "Got " << inputEventTypeToString(event->getType())
826 << " event instead of FOCUS event";
827
828 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
829 << mName.c_str() << ": event displayId should always be NONE.";
830
831 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
832 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
833 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
834 }
835
consumeCaptureEvent(bool hasCapture)836 void consumeCaptureEvent(bool hasCapture) {
837 const InputEvent* event = consume();
838 ASSERT_NE(nullptr, event) << mName.c_str()
839 << ": consumer should have returned non-NULL event.";
840 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
841 << "Got " << inputEventTypeToString(event->getType())
842 << " event instead of CAPTURE event";
843
844 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
845 << mName.c_str() << ": event displayId should always be NONE.";
846
847 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
848 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
849 }
850
consumeDragEvent(bool isExiting,float x,float y)851 void consumeDragEvent(bool isExiting, float x, float y) {
852 const InputEvent* event = consume();
853 ASSERT_NE(nullptr, event) << mName.c_str()
854 << ": consumer should have returned non-NULL event.";
855 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
856 << "Got " << inputEventTypeToString(event->getType())
857 << " event instead of DRAG event";
858
859 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
860 << mName.c_str() << ": event displayId should always be NONE.";
861
862 const auto& dragEvent = static_cast<const DragEvent&>(*event);
863 EXPECT_EQ(isExiting, dragEvent.isExiting());
864 EXPECT_EQ(x, dragEvent.getX());
865 EXPECT_EQ(y, dragEvent.getY());
866 }
867
assertNoEvents()868 void assertNoEvents() {
869 InputEvent* event = consume();
870 if (event == nullptr) {
871 return;
872 }
873 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
874 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
875 ADD_FAILURE() << "Received key event "
876 << KeyEvent::actionToString(keyEvent.getAction());
877 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
878 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
879 ADD_FAILURE() << "Received motion event "
880 << MotionEvent::actionToString(motionEvent.getAction());
881 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
882 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
883 ADD_FAILURE() << "Received focus event, hasFocus = "
884 << (focusEvent.getHasFocus() ? "true" : "false");
885 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
886 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
887 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
888 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
889 }
890 FAIL() << mName.c_str()
891 << ": should not have received any events, so consume() should return NULL";
892 }
893
getToken()894 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
895
896 protected:
897 std::unique_ptr<InputConsumer> mConsumer;
898 PreallocatedInputEventFactory mEventFactory;
899
900 std::string mName;
901 };
902
903 class FakeWindowHandle : public WindowInfoHandle {
904 public:
905 static const int32_t WIDTH = 600;
906 static const int32_t HEIGHT = 800;
907
FakeWindowHandle(const std::shared_ptr<InputApplicationHandle> & inputApplicationHandle,const sp<InputDispatcher> & dispatcher,const std::string name,int32_t displayId,std::optional<sp<IBinder>> token=std::nullopt)908 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
909 const sp<InputDispatcher>& dispatcher, const std::string name,
910 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
911 : mName(name) {
912 if (token == std::nullopt) {
913 base::Result<std::unique_ptr<InputChannel>> channel =
914 dispatcher->createInputChannel(name);
915 token = (*channel)->getConnectionToken();
916 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
917 }
918
919 inputApplicationHandle->updateInfo();
920 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
921
922 mInfo.token = *token;
923 mInfo.id = sId++;
924 mInfo.name = name;
925 mInfo.type = WindowInfo::Type::APPLICATION;
926 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
927 mInfo.alpha = 1.0;
928 mInfo.frameLeft = 0;
929 mInfo.frameTop = 0;
930 mInfo.frameRight = WIDTH;
931 mInfo.frameBottom = HEIGHT;
932 mInfo.transform.set(0, 0);
933 mInfo.globalScaleFactor = 1.0;
934 mInfo.touchableRegion.clear();
935 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
936 mInfo.visible = true;
937 mInfo.focusable = false;
938 mInfo.hasWallpaper = false;
939 mInfo.paused = false;
940 mInfo.ownerPid = INJECTOR_PID;
941 mInfo.ownerUid = INJECTOR_UID;
942 mInfo.displayId = displayId;
943 }
944
clone(const std::shared_ptr<InputApplicationHandle> & inputApplicationHandle,const sp<InputDispatcher> & dispatcher,int32_t displayId)945 sp<FakeWindowHandle> clone(
946 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
947 const sp<InputDispatcher>& dispatcher, int32_t displayId) {
948 sp<FakeWindowHandle> handle =
949 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
950 displayId, mInfo.token);
951 return handle;
952 }
953
setFocusable(bool focusable)954 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
955
setVisible(bool visible)956 void setVisible(bool visible) { mInfo.visible = visible; }
957
setDispatchingTimeout(std::chrono::nanoseconds timeout)958 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
959 mInfo.dispatchingTimeout = timeout;
960 }
961
setPaused(bool paused)962 void setPaused(bool paused) { mInfo.paused = paused; }
963
setAlpha(float alpha)964 void setAlpha(float alpha) { mInfo.alpha = alpha; }
965
setTouchOcclusionMode(TouchOcclusionMode mode)966 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
967
setApplicationToken(sp<IBinder> token)968 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
969
setFrame(const Rect & frame)970 void setFrame(const Rect& frame) {
971 mInfo.frameLeft = frame.left;
972 mInfo.frameTop = frame.top;
973 mInfo.frameRight = frame.right;
974 mInfo.frameBottom = frame.bottom;
975 mInfo.transform.set(-frame.left, -frame.top);
976 mInfo.touchableRegion.clear();
977 mInfo.addTouchableRegion(frame);
978 }
979
addFlags(Flags<WindowInfo::Flag> flags)980 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
981
setFlags(Flags<WindowInfo::Flag> flags)982 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
983
setInputFeatures(WindowInfo::Feature features)984 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
985
setWindowTransform(float dsdx,float dtdx,float dtdy,float dsdy)986 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
987 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
988 }
989
setWindowScale(float xScale,float yScale)990 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
991
setWindowOffset(float offsetX,float offsetY)992 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
993
consumeKeyDown(int32_t expectedDisplayId,int32_t expectedFlags=0)994 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
995 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
996 expectedFlags);
997 }
998
consumeKeyUp(int32_t expectedDisplayId,int32_t expectedFlags=0)999 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1000 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1001 }
1002
consumeMotionCancel(int32_t expectedDisplayId=ADISPLAY_ID_DEFAULT,int32_t expectedFlags=0)1003 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1004 int32_t expectedFlags = 0) {
1005 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1006 expectedFlags);
1007 }
1008
consumeMotionMove(int32_t expectedDisplayId=ADISPLAY_ID_DEFAULT,int32_t expectedFlags=0)1009 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1010 int32_t expectedFlags = 0) {
1011 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1012 expectedFlags);
1013 }
1014
consumeMotionDown(int32_t expectedDisplayId=ADISPLAY_ID_DEFAULT,int32_t expectedFlags=0)1015 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1016 int32_t expectedFlags = 0) {
1017 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1018 }
1019
consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId=std::nullopt,std::optional<int32_t> expectedFlags=std::nullopt)1020 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1021 std::optional<int32_t> expectedFlags = std::nullopt) {
1022 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1023 expectedFlags);
1024 }
1025
consumeMotionPointerDown(int32_t pointerIdx,int32_t expectedDisplayId=ADISPLAY_ID_DEFAULT,int32_t expectedFlags=0)1026 void consumeMotionPointerDown(int32_t pointerIdx,
1027 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1028 int32_t expectedFlags = 0) {
1029 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1030 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
1031 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1032 }
1033
consumeMotionPointerUp(int32_t pointerIdx,int32_t expectedDisplayId=ADISPLAY_ID_DEFAULT,int32_t expectedFlags=0)1034 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1035 int32_t expectedFlags = 0) {
1036 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1037 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
1038 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1039 }
1040
consumeMotionUp(int32_t expectedDisplayId=ADISPLAY_ID_DEFAULT,int32_t expectedFlags=0)1041 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1042 int32_t expectedFlags = 0) {
1043 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1044 expectedFlags);
1045 }
1046
consumeMotionOutside(int32_t expectedDisplayId=ADISPLAY_ID_DEFAULT,int32_t expectedFlags=0)1047 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1048 int32_t expectedFlags = 0) {
1049 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1050 expectedFlags);
1051 }
1052
consumeFocusEvent(bool hasFocus,bool inTouchMode=true)1053 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1054 ASSERT_NE(mInputReceiver, nullptr)
1055 << "Cannot consume events from a window with no receiver";
1056 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1057 }
1058
consumeCaptureEvent(bool hasCapture)1059 void consumeCaptureEvent(bool hasCapture) {
1060 ASSERT_NE(mInputReceiver, nullptr)
1061 << "Cannot consume events from a window with no receiver";
1062 mInputReceiver->consumeCaptureEvent(hasCapture);
1063 }
1064
consumeEvent(int32_t expectedEventType,int32_t expectedAction,std::optional<int32_t> expectedDisplayId,std::optional<int32_t> expectedFlags)1065 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1066 std::optional<int32_t> expectedDisplayId,
1067 std::optional<int32_t> expectedFlags) {
1068 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1069 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1070 expectedFlags);
1071 }
1072
consumeDragEvent(bool isExiting,float x,float y)1073 void consumeDragEvent(bool isExiting, float x, float y) {
1074 mInputReceiver->consumeDragEvent(isExiting, x, y);
1075 }
1076
receiveEvent(InputEvent ** outEvent=nullptr)1077 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
1078 if (mInputReceiver == nullptr) {
1079 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1080 return std::nullopt;
1081 }
1082 return mInputReceiver->receiveEvent(outEvent);
1083 }
1084
finishEvent(uint32_t sequenceNum)1085 void finishEvent(uint32_t sequenceNum) {
1086 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1087 mInputReceiver->finishEvent(sequenceNum);
1088 }
1089
sendTimeline(int32_t inputEventId,std::array<nsecs_t,GraphicsTimeline::SIZE> timeline)1090 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1091 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1092 mInputReceiver->sendTimeline(inputEventId, timeline);
1093 }
1094
consume()1095 InputEvent* consume() {
1096 if (mInputReceiver == nullptr) {
1097 return nullptr;
1098 }
1099 return mInputReceiver->consume();
1100 }
1101
consumeMotion()1102 MotionEvent* consumeMotion() {
1103 InputEvent* event = consume();
1104 if (event == nullptr) {
1105 ADD_FAILURE() << "Consume failed : no event";
1106 return nullptr;
1107 }
1108 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1109 ADD_FAILURE() << "Instead of motion event, got "
1110 << inputEventTypeToString(event->getType());
1111 return nullptr;
1112 }
1113 return static_cast<MotionEvent*>(event);
1114 }
1115
assertNoEvents()1116 void assertNoEvents() {
1117 if (mInputReceiver == nullptr &&
1118 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
1119 return; // Can't receive events if the window does not have input channel
1120 }
1121 ASSERT_NE(nullptr, mInputReceiver)
1122 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
1123 mInputReceiver->assertNoEvents();
1124 }
1125
getToken()1126 sp<IBinder> getToken() { return mInfo.token; }
1127
getName()1128 const std::string& getName() { return mName; }
1129
setOwnerInfo(int32_t ownerPid,int32_t ownerUid)1130 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1131 mInfo.ownerPid = ownerPid;
1132 mInfo.ownerUid = ownerUid;
1133 }
1134
1135 private:
1136 const std::string mName;
1137 std::unique_ptr<FakeInputReceiver> mInputReceiver;
1138 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
1139 };
1140
1141 std::atomic<int32_t> FakeWindowHandle::sId{1};
1142
injectKey(const sp<InputDispatcher> & dispatcher,int32_t action,int32_t repeatCount,int32_t displayId=ADISPLAY_ID_NONE,InputEventInjectionSync syncMode=InputEventInjectionSync::WAIT_FOR_RESULT,std::chrono::milliseconds injectionTimeout=INJECT_EVENT_TIMEOUT,bool allowKeyRepeat=true)1143 static InputEventInjectionResult injectKey(
1144 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1145 int32_t displayId = ADISPLAY_ID_NONE,
1146 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1147 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1148 bool allowKeyRepeat = true) {
1149 KeyEvent event;
1150 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1151
1152 // Define a valid key down event.
1153 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
1154 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1155 repeatCount, currentTime, currentTime);
1156
1157 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1158 if (!allowKeyRepeat) {
1159 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1160 }
1161 // Inject event until dispatch out.
1162 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
1163 injectionTimeout, policyFlags);
1164 }
1165
injectKeyDown(const sp<InputDispatcher> & dispatcher,int32_t displayId=ADISPLAY_ID_NONE)1166 static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1167 int32_t displayId = ADISPLAY_ID_NONE) {
1168 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1169 }
1170
1171 // Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1172 // sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1173 // has to be woken up to process the repeating key.
injectKeyDownNoRepeat(const sp<InputDispatcher> & dispatcher,int32_t displayId=ADISPLAY_ID_NONE)1174 static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1175 int32_t displayId = ADISPLAY_ID_NONE) {
1176 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1177 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1178 /* allowKeyRepeat */ false);
1179 }
1180
injectKeyUp(const sp<InputDispatcher> & dispatcher,int32_t displayId=ADISPLAY_ID_NONE)1181 static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1182 int32_t displayId = ADISPLAY_ID_NONE) {
1183 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1184 }
1185
1186 class PointerBuilder {
1187 public:
PointerBuilder(int32_t id,int32_t toolType)1188 PointerBuilder(int32_t id, int32_t toolType) {
1189 mProperties.clear();
1190 mProperties.id = id;
1191 mProperties.toolType = toolType;
1192 mCoords.clear();
1193 }
1194
x(float x)1195 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1196
y(float y)1197 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1198
axis(int32_t axis,float value)1199 PointerBuilder& axis(int32_t axis, float value) {
1200 mCoords.setAxisValue(axis, value);
1201 return *this;
1202 }
1203
buildProperties() const1204 PointerProperties buildProperties() const { return mProperties; }
1205
buildCoords() const1206 PointerCoords buildCoords() const { return mCoords; }
1207
1208 private:
1209 PointerProperties mProperties;
1210 PointerCoords mCoords;
1211 };
1212
1213 class MotionEventBuilder {
1214 public:
MotionEventBuilder(int32_t action,int32_t source)1215 MotionEventBuilder(int32_t action, int32_t source) {
1216 mAction = action;
1217 mSource = source;
1218 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1219 }
1220
eventTime(nsecs_t eventTime)1221 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1222 mEventTime = eventTime;
1223 return *this;
1224 }
1225
displayId(int32_t displayId)1226 MotionEventBuilder& displayId(int32_t displayId) {
1227 mDisplayId = displayId;
1228 return *this;
1229 }
1230
actionButton(int32_t actionButton)1231 MotionEventBuilder& actionButton(int32_t actionButton) {
1232 mActionButton = actionButton;
1233 return *this;
1234 }
1235
buttonState(int32_t buttonState)1236 MotionEventBuilder& buttonState(int32_t buttonState) {
1237 mButtonState = buttonState;
1238 return *this;
1239 }
1240
rawXCursorPosition(float rawXCursorPosition)1241 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1242 mRawXCursorPosition = rawXCursorPosition;
1243 return *this;
1244 }
1245
rawYCursorPosition(float rawYCursorPosition)1246 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1247 mRawYCursorPosition = rawYCursorPosition;
1248 return *this;
1249 }
1250
pointer(PointerBuilder pointer)1251 MotionEventBuilder& pointer(PointerBuilder pointer) {
1252 mPointers.push_back(pointer);
1253 return *this;
1254 }
1255
addFlag(uint32_t flags)1256 MotionEventBuilder& addFlag(uint32_t flags) {
1257 mFlags |= flags;
1258 return *this;
1259 }
1260
build()1261 MotionEvent build() {
1262 std::vector<PointerProperties> pointerProperties;
1263 std::vector<PointerCoords> pointerCoords;
1264 for (const PointerBuilder& pointer : mPointers) {
1265 pointerProperties.push_back(pointer.buildProperties());
1266 pointerCoords.push_back(pointer.buildCoords());
1267 }
1268
1269 // Set mouse cursor position for the most common cases to avoid boilerplate.
1270 if (mSource == AINPUT_SOURCE_MOUSE &&
1271 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1272 mPointers.size() == 1) {
1273 mRawXCursorPosition = pointerCoords[0].getX();
1274 mRawYCursorPosition = pointerCoords[0].getY();
1275 }
1276
1277 MotionEvent event;
1278 ui::Transform identityTransform;
1279 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
1280 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
1281 mButtonState, MotionClassification::NONE, identityTransform,
1282 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
1283 mRawYCursorPosition, mDisplayOrientation, mDisplayWidth, mDisplayHeight,
1284 mEventTime, mEventTime, mPointers.size(), pointerProperties.data(),
1285 pointerCoords.data());
1286
1287 return event;
1288 }
1289
1290 private:
1291 int32_t mAction;
1292 int32_t mSource;
1293 nsecs_t mEventTime;
1294 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1295 int32_t mActionButton{0};
1296 int32_t mButtonState{0};
1297 int32_t mFlags{0};
1298 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1299 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1300 uint32_t mDisplayOrientation{ui::Transform::ROT_0};
1301 int32_t mDisplayWidth{INVALID_DISPLAY_SIZE};
1302 int32_t mDisplayHeight{INVALID_DISPLAY_SIZE};
1303
1304 std::vector<PointerBuilder> mPointers;
1305 };
1306
injectMotionEvent(const sp<InputDispatcher> & dispatcher,const MotionEvent & event,std::chrono::milliseconds injectionTimeout=INJECT_EVENT_TIMEOUT,InputEventInjectionSync injectionMode=InputEventInjectionSync::WAIT_FOR_RESULT)1307 static InputEventInjectionResult injectMotionEvent(
1308 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1309 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1310 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
1311 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1312 injectionTimeout,
1313 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1314 }
1315
injectMotionEvent(const sp<InputDispatcher> & dispatcher,int32_t action,int32_t source,int32_t displayId,const PointF & position,const PointF & cursorPosition={AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION},std::chrono::milliseconds injectionTimeout=INJECT_EVENT_TIMEOUT,InputEventInjectionSync injectionMode=InputEventInjectionSync::WAIT_FOR_RESULT,nsecs_t eventTime=systemTime (SYSTEM_TIME_MONOTONIC))1316 static InputEventInjectionResult injectMotionEvent(
1317 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1318 const PointF& position,
1319 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
1320 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1321 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1322 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1323 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
1324 MotionEvent event = MotionEventBuilder(action, source)
1325 .displayId(displayId)
1326 .eventTime(eventTime)
1327 .rawXCursorPosition(cursorPosition.x)
1328 .rawYCursorPosition(cursorPosition.y)
1329 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1330 .x(position.x)
1331 .y(position.y))
1332 .build();
1333
1334 // Inject event until dispatch out.
1335 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
1336 }
1337
injectMotionDown(const sp<InputDispatcher> & dispatcher,int32_t source,int32_t displayId,const PointF & location={100, 200})1338 static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1339 int32_t source, int32_t displayId,
1340 const PointF& location = {100, 200}) {
1341 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
1342 }
1343
injectMotionUp(const sp<InputDispatcher> & dispatcher,int32_t source,int32_t displayId,const PointF & location={100, 200})1344 static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1345 int32_t source, int32_t displayId,
1346 const PointF& location = {100, 200}) {
1347 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
1348 }
1349
generateKeyArgs(int32_t action,int32_t displayId=ADISPLAY_ID_NONE)1350 static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1351 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1352 // Define a valid key event.
1353 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1354 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1355 KEY_A, AMETA_NONE, currentTime);
1356
1357 return args;
1358 }
1359
generateMotionArgs(int32_t action,int32_t source,int32_t displayId,const std::vector<PointF> & points)1360 static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1361 const std::vector<PointF>& points) {
1362 size_t pointerCount = points.size();
1363 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1364 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1365 }
1366
1367 PointerProperties pointerProperties[pointerCount];
1368 PointerCoords pointerCoords[pointerCount];
1369
1370 for (size_t i = 0; i < pointerCount; i++) {
1371 pointerProperties[i].clear();
1372 pointerProperties[i].id = i;
1373 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
1374
1375 pointerCoords[i].clear();
1376 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1377 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1378 }
1379
1380 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1381 // Define a valid motion event.
1382 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
1383 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1384 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
1385 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1386 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
1387 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1388 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
1389
1390 return args;
1391 }
1392
generateMotionArgs(int32_t action,int32_t source,int32_t displayId)1393 static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1394 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1395 }
1396
generatePointerCaptureChangedArgs(const PointerCaptureRequest & request)1397 static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1398 const PointerCaptureRequest& request) {
1399 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
1400 }
1401
TEST_F(InputDispatcherTest,SetInputWindow_SingleWindowTouch)1402 TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
1403 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1404 sp<FakeWindowHandle> window =
1405 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1406
1407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1409 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1411
1412 // Window should receive motion event.
1413 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1414 }
1415
1416 /**
1417 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1418 * To ensure that window receives only events that were directly inside of it, add
1419 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1420 * when finding touched windows.
1421 * This test serves as a sanity check for the next test, where setInputWindows is
1422 * called twice.
1423 */
TEST_F(InputDispatcherTest,SetInputWindowOnce_SingleWindowTouch)1424 TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
1425 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1426 sp<FakeWindowHandle> window =
1427 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1428 window->setFrame(Rect(0, 0, 100, 100));
1429 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
1430
1431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1433 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1434 {50, 50}))
1435 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1436
1437 // Window should receive motion event.
1438 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1439 }
1440
1441 /**
1442 * Calling setInputWindows twice, with the same info, should not cause any issues.
1443 * To ensure that window receives only events that were directly inside of it, add
1444 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1445 * when finding touched windows.
1446 */
TEST_F(InputDispatcherTest,SetInputWindowTwice_SingleWindowTouch)1447 TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
1448 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1449 sp<FakeWindowHandle> window =
1450 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1451 window->setFrame(Rect(0, 0, 100, 100));
1452 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
1453
1454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1457 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1458 {50, 50}))
1459 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1460
1461 // Window should receive motion event.
1462 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1463 }
1464
1465 // The foreground window should receive the first touch down event.
TEST_F(InputDispatcherTest,SetInputWindow_MultiWindowsTouch)1466 TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
1467 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1468 sp<FakeWindowHandle> windowTop =
1469 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1470 sp<FakeWindowHandle> windowSecond =
1471 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
1472
1473 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
1474 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1475 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1476 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1477
1478 // Top window should receive the touch down event. Second window should not receive anything.
1479 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1480 windowSecond->assertNoEvents();
1481 }
1482
TEST_F(InputDispatcherTest,HoverMoveEnterMouseClickAndHoverMoveExit)1483 TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
1484 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1485 sp<FakeWindowHandle> windowLeft =
1486 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1487 windowLeft->setFrame(Rect(0, 0, 600, 800));
1488 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
1489 sp<FakeWindowHandle> windowRight =
1490 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1491 windowRight->setFrame(Rect(600, 0, 1200, 800));
1492 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
1493
1494 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1495
1496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1497
1498 // Start cursor position in right window so that we can move the cursor to left window.
1499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1500 injectMotionEvent(mDispatcher,
1501 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1502 AINPUT_SOURCE_MOUSE)
1503 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1504 .x(900)
1505 .y(400))
1506 .build()));
1507 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1508 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1509 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1510 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1511
1512 // Move cursor into left window
1513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1514 injectMotionEvent(mDispatcher,
1515 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1516 AINPUT_SOURCE_MOUSE)
1517 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1518 .x(300)
1519 .y(400))
1520 .build()));
1521 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1522 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1523 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1524 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1525 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1526 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1527
1528 // Inject a series of mouse events for a mouse click
1529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1530 injectMotionEvent(mDispatcher,
1531 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1532 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1533 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1534 .x(300)
1535 .y(400))
1536 .build()));
1537 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1538
1539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1540 injectMotionEvent(mDispatcher,
1541 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1542 AINPUT_SOURCE_MOUSE)
1543 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1544 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1545 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1546 .x(300)
1547 .y(400))
1548 .build()));
1549 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1550 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1551
1552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1553 injectMotionEvent(mDispatcher,
1554 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1555 AINPUT_SOURCE_MOUSE)
1556 .buttonState(0)
1557 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1558 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1559 .x(300)
1560 .y(400))
1561 .build()));
1562 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1563 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1564
1565 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1566 injectMotionEvent(mDispatcher,
1567 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1568 .buttonState(0)
1569 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1570 .x(300)
1571 .y(400))
1572 .build()));
1573 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1574
1575 // Move mouse cursor back to right window
1576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1577 injectMotionEvent(mDispatcher,
1578 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1579 AINPUT_SOURCE_MOUSE)
1580 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1581 .x(900)
1582 .y(400))
1583 .build()));
1584 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1585 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1586 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1587 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1588 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1589 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1590 }
1591
1592 // This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1593 // directly in this test.
TEST_F(InputDispatcherTest,HoverEnterMouseClickAndHoverExit)1594 TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
1595 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1596 sp<FakeWindowHandle> window =
1597 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1598 window->setFrame(Rect(0, 0, 1200, 800));
1599 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
1600
1601 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1602
1603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1604
1605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1606 injectMotionEvent(mDispatcher,
1607 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1608 AINPUT_SOURCE_MOUSE)
1609 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1610 .x(300)
1611 .y(400))
1612 .build()));
1613 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1614 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1615
1616 // Inject a series of mouse events for a mouse click
1617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1618 injectMotionEvent(mDispatcher,
1619 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1620 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1621 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1622 .x(300)
1623 .y(400))
1624 .build()));
1625 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1626
1627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1628 injectMotionEvent(mDispatcher,
1629 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1630 AINPUT_SOURCE_MOUSE)
1631 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1632 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1633 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1634 .x(300)
1635 .y(400))
1636 .build()));
1637 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1638 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1639
1640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1641 injectMotionEvent(mDispatcher,
1642 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1643 AINPUT_SOURCE_MOUSE)
1644 .buttonState(0)
1645 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1646 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1647 .x(300)
1648 .y(400))
1649 .build()));
1650 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1651 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1652
1653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1654 injectMotionEvent(mDispatcher,
1655 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1656 .buttonState(0)
1657 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1658 .x(300)
1659 .y(400))
1660 .build()));
1661 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1662
1663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1664 injectMotionEvent(mDispatcher,
1665 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1666 AINPUT_SOURCE_MOUSE)
1667 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1668 .x(300)
1669 .y(400))
1670 .build()));
1671 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1672 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1673 }
1674
TEST_F(InputDispatcherTest,DispatchMouseEventsUnderCursor)1675 TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
1676 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1677
1678 sp<FakeWindowHandle> windowLeft =
1679 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1680 windowLeft->setFrame(Rect(0, 0, 600, 800));
1681 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
1682 sp<FakeWindowHandle> windowRight =
1683 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1684 windowRight->setFrame(Rect(600, 0, 1200, 800));
1685 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
1686
1687 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1688
1689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1690
1691 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1692 // left window. This event should be dispatched to the left window.
1693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1694 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
1695 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
1696 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1697 windowRight->assertNoEvents();
1698 }
1699
TEST_F(InputDispatcherTest,NotifyDeviceReset_CancelsKeyStream)1700 TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
1701 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1702 sp<FakeWindowHandle> window =
1703 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1704 window->setFocusable(true);
1705
1706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1707 setFocusedWindow(window);
1708
1709 window->consumeFocusEvent(true);
1710
1711 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1712 mDispatcher->notifyKey(&keyArgs);
1713
1714 // Window should receive key down event.
1715 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1716
1717 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1718 // on the app side.
1719 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
1720 mDispatcher->notifyDeviceReset(&args);
1721 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1722 AKEY_EVENT_FLAG_CANCELED);
1723 }
1724
TEST_F(InputDispatcherTest,NotifyDeviceReset_CancelsMotionStream)1725 TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
1726 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1727 sp<FakeWindowHandle> window =
1728 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1729
1730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1731
1732 NotifyMotionArgs motionArgs =
1733 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1734 ADISPLAY_ID_DEFAULT);
1735 mDispatcher->notifyMotion(&motionArgs);
1736
1737 // Window should receive motion down event.
1738 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1739
1740 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1741 // on the app side.
1742 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
1743 mDispatcher->notifyDeviceReset(&args);
1744 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1745 0 /*expectedFlags*/);
1746 }
1747
1748 using TransferFunction =
1749 std::function<bool(sp<InputDispatcher> dispatcher, sp<IBinder>, sp<IBinder>)>;
1750
1751 class TransferTouchFixture : public InputDispatcherTest,
1752 public ::testing::WithParamInterface<TransferFunction> {};
1753
TEST_P(TransferTouchFixture,TransferTouch_OnePointer)1754 TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
1755 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1756
1757 // Create a couple of windows
1758 sp<FakeWindowHandle> firstWindow =
1759 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1760 sp<FakeWindowHandle> secondWindow =
1761 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1762
1763 // Add the windows to the dispatcher
1764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1765
1766 // Send down to the first window
1767 NotifyMotionArgs downMotionArgs =
1768 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1769 ADISPLAY_ID_DEFAULT);
1770 mDispatcher->notifyMotion(&downMotionArgs);
1771 // Only the first window should get the down event
1772 firstWindow->consumeMotionDown();
1773 secondWindow->assertNoEvents();
1774
1775 // Transfer touch to the second window
1776 TransferFunction f = GetParam();
1777 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1778 ASSERT_TRUE(success);
1779 // The first window gets cancel and the second gets down
1780 firstWindow->consumeMotionCancel();
1781 secondWindow->consumeMotionDown();
1782
1783 // Send up event to the second window
1784 NotifyMotionArgs upMotionArgs =
1785 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1786 ADISPLAY_ID_DEFAULT);
1787 mDispatcher->notifyMotion(&upMotionArgs);
1788 // The first window gets no events and the second gets up
1789 firstWindow->assertNoEvents();
1790 secondWindow->consumeMotionUp();
1791 }
1792
TEST_P(TransferTouchFixture,TransferTouch_TwoPointersNonSplitTouch)1793 TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
1794 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1795
1796 PointF touchPoint = {10, 10};
1797
1798 // Create a couple of windows
1799 sp<FakeWindowHandle> firstWindow =
1800 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1801 sp<FakeWindowHandle> secondWindow =
1802 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1803
1804 // Add the windows to the dispatcher
1805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1806
1807 // Send down to the first window
1808 NotifyMotionArgs downMotionArgs =
1809 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1810 ADISPLAY_ID_DEFAULT, {touchPoint});
1811 mDispatcher->notifyMotion(&downMotionArgs);
1812 // Only the first window should get the down event
1813 firstWindow->consumeMotionDown();
1814 secondWindow->assertNoEvents();
1815
1816 // Send pointer down to the first window
1817 NotifyMotionArgs pointerDownMotionArgs =
1818 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1819 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1820 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1821 {touchPoint, touchPoint});
1822 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1823 // Only the first window should get the pointer down event
1824 firstWindow->consumeMotionPointerDown(1);
1825 secondWindow->assertNoEvents();
1826
1827 // Transfer touch focus to the second window
1828 TransferFunction f = GetParam();
1829 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1830 ASSERT_TRUE(success);
1831 // The first window gets cancel and the second gets down and pointer down
1832 firstWindow->consumeMotionCancel();
1833 secondWindow->consumeMotionDown();
1834 secondWindow->consumeMotionPointerDown(1);
1835
1836 // Send pointer up to the second window
1837 NotifyMotionArgs pointerUpMotionArgs =
1838 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1839 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1840 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1841 {touchPoint, touchPoint});
1842 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1843 // The first window gets nothing and the second gets pointer up
1844 firstWindow->assertNoEvents();
1845 secondWindow->consumeMotionPointerUp(1);
1846
1847 // Send up event to the second window
1848 NotifyMotionArgs upMotionArgs =
1849 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1850 ADISPLAY_ID_DEFAULT);
1851 mDispatcher->notifyMotion(&upMotionArgs);
1852 // The first window gets nothing and the second gets up
1853 firstWindow->assertNoEvents();
1854 secondWindow->consumeMotionUp();
1855 }
1856
1857 // For the cases of single pointer touch and two pointers non-split touch, the api's
1858 // 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
1859 // for the case where there are multiple pointers split across several windows.
1860 INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
1861 ::testing::Values(
1862 [&](sp<InputDispatcher> dispatcher, sp<IBinder> /*ignored*/,
__anon90001ff30102(sp<InputDispatcher> dispatcher, sp<IBinder> , sp<IBinder> destChannelToken) 1863 sp<IBinder> destChannelToken) {
1864 return dispatcher->transferTouch(destChannelToken);
1865 },
1866 [&](sp<InputDispatcher> dispatcher, sp<IBinder> from,
__anon90001ff30202(sp<InputDispatcher> dispatcher, sp<IBinder> from, sp<IBinder> to) 1867 sp<IBinder> to) {
1868 return dispatcher->transferTouchFocus(from, to,
1869 false /*isDragAndDrop*/);
1870 }));
1871
TEST_F(InputDispatcherTest,TransferTouchFocus_TwoPointersSplitTouch)1872 TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
1873 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1874
1875 // Create a non touch modal window that supports split touch
1876 sp<FakeWindowHandle> firstWindow =
1877 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1878 firstWindow->setFrame(Rect(0, 0, 600, 400));
1879 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
1880
1881 // Create a non touch modal window that supports split touch
1882 sp<FakeWindowHandle> secondWindow =
1883 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1884 secondWindow->setFrame(Rect(0, 400, 600, 800));
1885 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
1886
1887 // Add the windows to the dispatcher
1888 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1889
1890 PointF pointInFirst = {300, 200};
1891 PointF pointInSecond = {300, 600};
1892
1893 // Send down to the first window
1894 NotifyMotionArgs firstDownMotionArgs =
1895 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1896 ADISPLAY_ID_DEFAULT, {pointInFirst});
1897 mDispatcher->notifyMotion(&firstDownMotionArgs);
1898 // Only the first window should get the down event
1899 firstWindow->consumeMotionDown();
1900 secondWindow->assertNoEvents();
1901
1902 // Send down to the second window
1903 NotifyMotionArgs secondDownMotionArgs =
1904 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1905 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1906 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1907 {pointInFirst, pointInSecond});
1908 mDispatcher->notifyMotion(&secondDownMotionArgs);
1909 // The first window gets a move and the second a down
1910 firstWindow->consumeMotionMove();
1911 secondWindow->consumeMotionDown();
1912
1913 // Transfer touch focus to the second window
1914 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1915 // The first window gets cancel and the new gets pointer down (it already saw down)
1916 firstWindow->consumeMotionCancel();
1917 secondWindow->consumeMotionPointerDown(1);
1918
1919 // Send pointer up to the second window
1920 NotifyMotionArgs pointerUpMotionArgs =
1921 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1922 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1923 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1924 {pointInFirst, pointInSecond});
1925 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1926 // The first window gets nothing and the second gets pointer up
1927 firstWindow->assertNoEvents();
1928 secondWindow->consumeMotionPointerUp(1);
1929
1930 // Send up event to the second window
1931 NotifyMotionArgs upMotionArgs =
1932 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1933 ADISPLAY_ID_DEFAULT);
1934 mDispatcher->notifyMotion(&upMotionArgs);
1935 // The first window gets nothing and the second gets up
1936 firstWindow->assertNoEvents();
1937 secondWindow->consumeMotionUp();
1938 }
1939
1940 // Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
1941 // Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
1942 // touch is not supported, so the touch should continue on those windows and the transferred-to
1943 // window should get nothing.
TEST_F(InputDispatcherTest,TransferTouch_TwoPointersSplitTouch)1944 TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
1945 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1946
1947 // Create a non touch modal window that supports split touch
1948 sp<FakeWindowHandle> firstWindow =
1949 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1950 firstWindow->setFrame(Rect(0, 0, 600, 400));
1951 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
1952
1953 // Create a non touch modal window that supports split touch
1954 sp<FakeWindowHandle> secondWindow =
1955 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1956 secondWindow->setFrame(Rect(0, 400, 600, 800));
1957 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
1958
1959 // Add the windows to the dispatcher
1960 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1961
1962 PointF pointInFirst = {300, 200};
1963 PointF pointInSecond = {300, 600};
1964
1965 // Send down to the first window
1966 NotifyMotionArgs firstDownMotionArgs =
1967 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1968 ADISPLAY_ID_DEFAULT, {pointInFirst});
1969 mDispatcher->notifyMotion(&firstDownMotionArgs);
1970 // Only the first window should get the down event
1971 firstWindow->consumeMotionDown();
1972 secondWindow->assertNoEvents();
1973
1974 // Send down to the second window
1975 NotifyMotionArgs secondDownMotionArgs =
1976 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1977 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1978 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1979 {pointInFirst, pointInSecond});
1980 mDispatcher->notifyMotion(&secondDownMotionArgs);
1981 // The first window gets a move and the second a down
1982 firstWindow->consumeMotionMove();
1983 secondWindow->consumeMotionDown();
1984
1985 // Transfer touch focus to the second window
1986 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
1987 // The 'transferTouch' call should not succeed, because there are 2 touched windows
1988 ASSERT_FALSE(transferred);
1989 firstWindow->assertNoEvents();
1990 secondWindow->assertNoEvents();
1991
1992 // The rest of the dispatch should proceed as normal
1993 // Send pointer up to the second window
1994 NotifyMotionArgs pointerUpMotionArgs =
1995 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1996 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1997 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1998 {pointInFirst, pointInSecond});
1999 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2000 // The first window gets MOVE and the second gets pointer up
2001 firstWindow->consumeMotionMove();
2002 secondWindow->consumeMotionUp();
2003
2004 // Send up event to the first window
2005 NotifyMotionArgs upMotionArgs =
2006 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2007 ADISPLAY_ID_DEFAULT);
2008 mDispatcher->notifyMotion(&upMotionArgs);
2009 // The first window gets nothing and the second gets up
2010 firstWindow->consumeMotionUp();
2011 secondWindow->assertNoEvents();
2012 }
2013
2014 // This case will create two windows and one mirrored window on the default display and mirror
2015 // two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2016 // the windows info of second display before default display.
TEST_F(InputDispatcherTest,TransferTouchFocus_CloneSurface)2017 TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2018 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2019 sp<FakeWindowHandle> firstWindowInPrimary =
2020 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2021 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2022 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2023 sp<FakeWindowHandle> secondWindowInPrimary =
2024 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2025 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2026 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2027
2028 sp<FakeWindowHandle> mirrorWindowInPrimary =
2029 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2030 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2031 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2032
2033 sp<FakeWindowHandle> firstWindowInSecondary =
2034 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2035 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2036 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2037
2038 sp<FakeWindowHandle> secondWindowInSecondary =
2039 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2040 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2041 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2042
2043 // Update window info, let it find window handle of second display first.
2044 mDispatcher->setInputWindows(
2045 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2046 {ADISPLAY_ID_DEFAULT,
2047 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2048
2049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2050 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2051 {50, 50}))
2052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2053
2054 // Window should receive motion event.
2055 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2056
2057 // Transfer touch focus
2058 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2059 secondWindowInPrimary->getToken()));
2060 // The first window gets cancel.
2061 firstWindowInPrimary->consumeMotionCancel();
2062 secondWindowInPrimary->consumeMotionDown();
2063
2064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2065 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2066 ADISPLAY_ID_DEFAULT, {150, 50}))
2067 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2068 firstWindowInPrimary->assertNoEvents();
2069 secondWindowInPrimary->consumeMotionMove();
2070
2071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2072 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2073 {150, 50}))
2074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2075 firstWindowInPrimary->assertNoEvents();
2076 secondWindowInPrimary->consumeMotionUp();
2077 }
2078
2079 // Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2080 // 'transferTouch' api.
TEST_F(InputDispatcherTest,TransferTouch_CloneSurface)2081 TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2082 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2083 sp<FakeWindowHandle> firstWindowInPrimary =
2084 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2085 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2086 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2087 sp<FakeWindowHandle> secondWindowInPrimary =
2088 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2089 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2090 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2091
2092 sp<FakeWindowHandle> mirrorWindowInPrimary =
2093 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2094 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2095 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2096
2097 sp<FakeWindowHandle> firstWindowInSecondary =
2098 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2099 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2100 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2101
2102 sp<FakeWindowHandle> secondWindowInSecondary =
2103 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2104 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2105 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2106
2107 // Update window info, let it find window handle of second display first.
2108 mDispatcher->setInputWindows(
2109 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2110 {ADISPLAY_ID_DEFAULT,
2111 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2112
2113 // Touch on second display.
2114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2115 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2116 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2117
2118 // Window should receive motion event.
2119 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2120
2121 // Transfer touch focus
2122 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2123
2124 // The first window gets cancel.
2125 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2126 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2127
2128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2129 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2130 SECOND_DISPLAY_ID, {150, 50}))
2131 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2132 firstWindowInPrimary->assertNoEvents();
2133 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2134
2135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2136 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2138 firstWindowInPrimary->assertNoEvents();
2139 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2140 }
2141
TEST_F(InputDispatcherTest,FocusedWindow_ReceivesFocusEventAndKeyEvent)2142 TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
2143 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2144 sp<FakeWindowHandle> window =
2145 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2146
2147 window->setFocusable(true);
2148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2149 setFocusedWindow(window);
2150
2151 window->consumeFocusEvent(true);
2152
2153 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2154 mDispatcher->notifyKey(&keyArgs);
2155
2156 // Window should receive key down event.
2157 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2158 }
2159
TEST_F(InputDispatcherTest,UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent)2160 TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
2161 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2162 sp<FakeWindowHandle> window =
2163 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2164
2165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2166
2167 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2168 mDispatcher->notifyKey(&keyArgs);
2169 mDispatcher->waitForIdle();
2170
2171 window->assertNoEvents();
2172 }
2173
2174 // If a window is touchable, but does not have focus, it should receive motion events, but not keys
TEST_F(InputDispatcherTest,UnfocusedWindow_ReceivesMotionsButNotKeys)2175 TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
2176 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2177 sp<FakeWindowHandle> window =
2178 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2179
2180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2181
2182 // Send key
2183 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2184 mDispatcher->notifyKey(&keyArgs);
2185 // Send motion
2186 NotifyMotionArgs motionArgs =
2187 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2188 ADISPLAY_ID_DEFAULT);
2189 mDispatcher->notifyMotion(&motionArgs);
2190
2191 // Window should receive only the motion event
2192 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2193 window->assertNoEvents(); // Key event or focus event will not be received
2194 }
2195
TEST_F(InputDispatcherTest,PointerCancel_SendCancelWhenSplitTouch)2196 TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2197 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2198
2199 // Create first non touch modal window that supports split touch
2200 sp<FakeWindowHandle> firstWindow =
2201 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2202 firstWindow->setFrame(Rect(0, 0, 600, 400));
2203 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
2204
2205 // Create second non touch modal window that supports split touch
2206 sp<FakeWindowHandle> secondWindow =
2207 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2208 secondWindow->setFrame(Rect(0, 400, 600, 800));
2209 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
2210
2211 // Add the windows to the dispatcher
2212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2213
2214 PointF pointInFirst = {300, 200};
2215 PointF pointInSecond = {300, 600};
2216
2217 // Send down to the first window
2218 NotifyMotionArgs firstDownMotionArgs =
2219 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2220 ADISPLAY_ID_DEFAULT, {pointInFirst});
2221 mDispatcher->notifyMotion(&firstDownMotionArgs);
2222 // Only the first window should get the down event
2223 firstWindow->consumeMotionDown();
2224 secondWindow->assertNoEvents();
2225
2226 // Send down to the second window
2227 NotifyMotionArgs secondDownMotionArgs =
2228 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2229 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2230 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2231 {pointInFirst, pointInSecond});
2232 mDispatcher->notifyMotion(&secondDownMotionArgs);
2233 // The first window gets a move and the second a down
2234 firstWindow->consumeMotionMove();
2235 secondWindow->consumeMotionDown();
2236
2237 // Send pointer cancel to the second window
2238 NotifyMotionArgs pointerUpMotionArgs =
2239 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2240 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2241 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2242 {pointInFirst, pointInSecond});
2243 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2244 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2245 // The first window gets move and the second gets cancel.
2246 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2247 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2248
2249 // Send up event.
2250 NotifyMotionArgs upMotionArgs =
2251 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2252 ADISPLAY_ID_DEFAULT);
2253 mDispatcher->notifyMotion(&upMotionArgs);
2254 // The first window gets up and the second gets nothing.
2255 firstWindow->consumeMotionUp();
2256 secondWindow->assertNoEvents();
2257 }
2258
TEST_F(InputDispatcherTest,SendTimeline_DoesNotCrashDispatcher)2259 TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2260 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2261
2262 sp<FakeWindowHandle> window =
2263 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2265 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2266 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2267 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2268
2269 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2270 window->assertNoEvents();
2271 mDispatcher->waitForIdle();
2272 }
2273
2274 class FakeMonitorReceiver {
2275 public:
FakeMonitorReceiver(const sp<InputDispatcher> & dispatcher,const std::string name,int32_t displayId,bool isGestureMonitor=false)2276 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
2277 int32_t displayId, bool isGestureMonitor = false) {
2278 base::Result<std::unique_ptr<InputChannel>> channel =
2279 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
2280 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
2281 }
2282
getToken()2283 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2284
consumeKeyDown(int32_t expectedDisplayId,int32_t expectedFlags=0)2285 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2286 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2287 expectedDisplayId, expectedFlags);
2288 }
2289
receiveEvent()2290 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2291
finishEvent(uint32_t consumeSeq)2292 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2293
consumeMotionDown(int32_t expectedDisplayId,int32_t expectedFlags=0)2294 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2295 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2296 expectedDisplayId, expectedFlags);
2297 }
2298
consumeMotionUp(int32_t expectedDisplayId,int32_t expectedFlags=0)2299 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2300 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2301 expectedDisplayId, expectedFlags);
2302 }
2303
consumeMotionCancel(int32_t expectedDisplayId,int32_t expectedFlags=0)2304 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2305 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2306 expectedDisplayId, expectedFlags);
2307 }
2308
consumeMotionPointerDown(int32_t pointerIdx)2309 void consumeMotionPointerDown(int32_t pointerIdx) {
2310 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2311 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2312 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2313 0 /*expectedFlags*/);
2314 }
2315
consumeMotion()2316 MotionEvent* consumeMotion() {
2317 InputEvent* event = mInputReceiver->consume();
2318 if (!event) {
2319 ADD_FAILURE() << "No event was produced";
2320 return nullptr;
2321 }
2322 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2323 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2324 return nullptr;
2325 }
2326 return static_cast<MotionEvent*>(event);
2327 }
2328
assertNoEvents()2329 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2330
2331 private:
2332 std::unique_ptr<FakeInputReceiver> mInputReceiver;
2333 };
2334
2335 // Tests for gesture monitors
TEST_F(InputDispatcherTest,GestureMonitor_ReceivesMotionEvents)2336 TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
2337 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2338 sp<FakeWindowHandle> window =
2339 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2340 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2341
2342 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2343 true /*isGestureMonitor*/);
2344
2345 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2346 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2347 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2348 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2349 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2350 }
2351
TEST_F(InputDispatcherTest,GestureMonitor_DoesNotReceiveKeyEvents)2352 TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
2353 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2354 sp<FakeWindowHandle> window =
2355 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2356
2357 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2358 window->setFocusable(true);
2359
2360 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2361 setFocusedWindow(window);
2362
2363 window->consumeFocusEvent(true);
2364
2365 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2366 true /*isGestureMonitor*/);
2367
2368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2369 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
2370 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2371 monitor.assertNoEvents();
2372 }
2373
TEST_F(InputDispatcherTest,GestureMonitor_CanPilferAfterWindowIsRemovedMidStream)2374 TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
2375 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2376 sp<FakeWindowHandle> window =
2377 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2378 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2379
2380 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2381 true /*isGestureMonitor*/);
2382
2383 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2384 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2385 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2386 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2387 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2388
2389 window->releaseChannel();
2390
2391 mDispatcher->pilferPointers(monitor.getToken());
2392
2393 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2394 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2395 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2396 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
2397 }
2398
TEST_F(InputDispatcherTest,UnresponsiveGestureMonitor_GetsAnr)2399 TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2400 FakeMonitorReceiver monitor =
2401 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2402 true /*isGestureMonitor*/);
2403
2404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2405 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2406 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2407 ASSERT_TRUE(consumeSeq);
2408
2409 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
2410 monitor.finishEvent(*consumeSeq);
2411 ASSERT_TRUE(mDispatcher->waitForIdle());
2412 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
2413 }
2414
2415 // Tests for gesture monitors
TEST_F(InputDispatcherTest,GestureMonitor_NoWindowTransform)2416 TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2417 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2418 sp<FakeWindowHandle> window =
2419 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2420 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2421 window->setWindowOffset(20, 40);
2422 window->setWindowTransform(0, 1, -1, 0);
2423
2424 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2425 true /*isGestureMonitor*/);
2426
2427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2428 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2430 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2431 MotionEvent* event = monitor.consumeMotion();
2432 // Even though window has transform, gesture monitor must not.
2433 ASSERT_EQ(ui::Transform(), event->getTransform());
2434 }
2435
TEST_F(InputDispatcherTest,TestMoveEvent)2436 TEST_F(InputDispatcherTest, TestMoveEvent) {
2437 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2438 sp<FakeWindowHandle> window =
2439 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2440
2441 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2442
2443 NotifyMotionArgs motionArgs =
2444 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2445 ADISPLAY_ID_DEFAULT);
2446
2447 mDispatcher->notifyMotion(&motionArgs);
2448 // Window should receive motion down event.
2449 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2450
2451 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
2452 motionArgs.id += 1;
2453 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2454 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2455 motionArgs.pointerCoords[0].getX() - 10);
2456
2457 mDispatcher->notifyMotion(&motionArgs);
2458 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2459 0 /*expectedFlags*/);
2460 }
2461
TEST_F(InputDispatcherTest,GestureMonitor_SplitIfNoWindowTouched)2462 TEST_F(InputDispatcherTest, GestureMonitor_SplitIfNoWindowTouched) {
2463 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2464 true /*isGestureMonitor*/);
2465
2466 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2467 // Create a non touch modal window that supports split touch
2468 sp<FakeWindowHandle> window =
2469 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2470 window->setFrame(Rect(0, 0, 100, 100));
2471 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
2472 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2473
2474 // First finger down, no window touched.
2475 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2476 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2477 {100, 200}))
2478 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2479 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2480 window->assertNoEvents();
2481
2482 // Second finger down on window, the window should receive touch down.
2483 const MotionEvent secondFingerDownEvent =
2484 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
2485 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2486 AINPUT_SOURCE_TOUCHSCREEN)
2487 .displayId(ADISPLAY_ID_DEFAULT)
2488 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2489 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2490 .x(100)
2491 .y(200))
2492 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2493 .build();
2494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2495 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2496 InputEventInjectionSync::WAIT_FOR_RESULT))
2497 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2498
2499 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2500 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
2501 }
2502
TEST_F(InputDispatcherTest,GestureMonitor_NoSplitAfterPilfer)2503 TEST_F(InputDispatcherTest, GestureMonitor_NoSplitAfterPilfer) {
2504 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2505 true /*isGestureMonitor*/);
2506
2507 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2508 // Create a non touch modal window that supports split touch
2509 sp<FakeWindowHandle> window =
2510 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2511 window->setFrame(Rect(0, 0, 100, 100));
2512 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
2513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2514
2515 // First finger down, no window touched.
2516 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2517 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2518 {100, 200}))
2519 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2520 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2521 window->assertNoEvents();
2522
2523 // Gesture monitor pilfer the pointers.
2524 mDispatcher->pilferPointers(monitor.getToken());
2525
2526 // Second finger down on window, the window should not receive touch down.
2527 const MotionEvent secondFingerDownEvent =
2528 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
2529 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2530 AINPUT_SOURCE_TOUCHSCREEN)
2531 .displayId(ADISPLAY_ID_DEFAULT)
2532 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2533 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2534 .x(100)
2535 .y(200))
2536 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2537 .build();
2538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2539 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2540 InputEventInjectionSync::WAIT_FOR_RESULT))
2541 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2542
2543 window->assertNoEvents();
2544 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
2545 }
2546
2547 /**
2548 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2549 * the device default right away. In the test scenario, we check both the default value,
2550 * and the action of enabling / disabling.
2551 */
TEST_F(InputDispatcherTest,TouchModeState_IsSentToApps)2552 TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
2553 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2554 sp<FakeWindowHandle> window =
2555 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2556
2557 // Set focused application.
2558 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2559 window->setFocusable(true);
2560
2561 SCOPED_TRACE("Check default value of touch mode");
2562 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2563 setFocusedWindow(window);
2564
2565 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2566
2567 SCOPED_TRACE("Remove the window to trigger focus loss");
2568 window->setFocusable(false);
2569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2570 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2571
2572 SCOPED_TRACE("Disable touch mode");
2573 mDispatcher->setInTouchMode(false);
2574 window->setFocusable(true);
2575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2576 setFocusedWindow(window);
2577 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2578
2579 SCOPED_TRACE("Remove the window to trigger focus loss");
2580 window->setFocusable(false);
2581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2582 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2583
2584 SCOPED_TRACE("Enable touch mode again");
2585 mDispatcher->setInTouchMode(true);
2586 window->setFocusable(true);
2587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2588 setFocusedWindow(window);
2589 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2590
2591 window->assertNoEvents();
2592 }
2593
TEST_F(InputDispatcherTest,VerifyInputEvent_KeyEvent)2594 TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
2595 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2596 sp<FakeWindowHandle> window =
2597 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2598
2599 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2600 window->setFocusable(true);
2601
2602 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2603 setFocusedWindow(window);
2604
2605 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2606
2607 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2608 mDispatcher->notifyKey(&keyArgs);
2609
2610 InputEvent* event = window->consume();
2611 ASSERT_NE(event, nullptr);
2612
2613 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2614 ASSERT_NE(verified, nullptr);
2615 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2616
2617 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2618 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2619 ASSERT_EQ(keyArgs.source, verified->source);
2620 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2621
2622 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2623
2624 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2625 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
2626 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2627 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2628 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2629 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2630 ASSERT_EQ(0, verifiedKey.repeatCount);
2631 }
2632
TEST_F(InputDispatcherTest,VerifyInputEvent_MotionEvent)2633 TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
2634 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2635 sp<FakeWindowHandle> window =
2636 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2637
2638 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2639
2640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2641
2642 NotifyMotionArgs motionArgs =
2643 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2644 ADISPLAY_ID_DEFAULT);
2645 mDispatcher->notifyMotion(&motionArgs);
2646
2647 InputEvent* event = window->consume();
2648 ASSERT_NE(event, nullptr);
2649
2650 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2651 ASSERT_NE(verified, nullptr);
2652 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2653
2654 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2655 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2656 EXPECT_EQ(motionArgs.source, verified->source);
2657 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2658
2659 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2660
2661 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2662 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2663 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2664 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2665 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2666 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2667 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2668 }
2669
TEST_F(InputDispatcherTest,NonPointerMotionEvent_JoystickAndTouchpadNotTransformed)2670 TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
2671 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2672 sp<FakeWindowHandle> window =
2673 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2674 const std::string name = window->getName();
2675
2676 // Window gets transformed by offset values.
2677 window->setWindowOffset(500.0f, 500.0f);
2678
2679 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2680 window->setFocusable(true);
2681
2682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2683
2684 // First, we set focused window so that focusedWindowHandle is not null.
2685 setFocusedWindow(window);
2686
2687 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2688 window->consumeFocusEvent(true);
2689
2690 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
2691 AMOTION_EVENT_ACTION_DOWN),
2692 std::pair(AINPUT_SOURCE_JOYSTICK,
2693 AMOTION_EVENT_ACTION_MOVE)};
2694 for (const auto& [source, action] : nonTransformedSources) {
2695 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
2696 mDispatcher->notifyMotion(&motionArgs);
2697
2698 MotionEvent* event = window->consumeMotion();
2699 ASSERT_NE(event, nullptr);
2700
2701 const MotionEvent& motionEvent = *event;
2702 EXPECT_EQ(action, motionEvent.getAction());
2703 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
2704
2705 float expectedX = motionArgs.pointerCoords[0].getX();
2706 float expectedY = motionArgs.pointerCoords[0].getY();
2707
2708 // Ensure the axis values from the final motion event are not transformed.
2709 EXPECT_EQ(expectedX, motionEvent.getX(0))
2710 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2711 << motionEvent.getX(0);
2712 EXPECT_EQ(expectedY, motionEvent.getY(0))
2713 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2714 << motionEvent.getY(0);
2715 // Ensure the raw and transformed axis values for the motion event are the same.
2716 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2717 << "expected raw and transformed X-axis values to be equal";
2718 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2719 << "expected raw and transformed Y-axis values to be equal";
2720 }
2721 }
2722
2723 /**
2724 * Ensure that separate calls to sign the same data are generating the same key.
2725 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2726 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2727 * tests.
2728 */
TEST_F(InputDispatcherTest,GeneratedHmac_IsConsistent)2729 TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2730 KeyEvent event = getTestKeyEvent();
2731 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2732
2733 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2734 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2735 ASSERT_EQ(hmac1, hmac2);
2736 }
2737
2738 /**
2739 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2740 */
TEST_F(InputDispatcherTest,GeneratedHmac_ChangesWhenFieldsChange)2741 TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2742 KeyEvent event = getTestKeyEvent();
2743 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2744 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2745
2746 verifiedEvent.deviceId += 1;
2747 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2748
2749 verifiedEvent.source += 1;
2750 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2751
2752 verifiedEvent.eventTimeNanos += 1;
2753 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2754
2755 verifiedEvent.displayId += 1;
2756 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2757
2758 verifiedEvent.action += 1;
2759 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2760
2761 verifiedEvent.downTimeNanos += 1;
2762 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2763
2764 verifiedEvent.flags += 1;
2765 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2766
2767 verifiedEvent.keyCode += 1;
2768 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2769
2770 verifiedEvent.scanCode += 1;
2771 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2772
2773 verifiedEvent.metaState += 1;
2774 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2775
2776 verifiedEvent.repeatCount += 1;
2777 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2778 }
2779
TEST_F(InputDispatcherTest,SetFocusedWindow)2780 TEST_F(InputDispatcherTest, SetFocusedWindow) {
2781 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2782 sp<FakeWindowHandle> windowTop =
2783 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2784 sp<FakeWindowHandle> windowSecond =
2785 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2786 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2787
2788 // Top window is also focusable but is not granted focus.
2789 windowTop->setFocusable(true);
2790 windowSecond->setFocusable(true);
2791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2792 setFocusedWindow(windowSecond);
2793
2794 windowSecond->consumeFocusEvent(true);
2795 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2796 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
2797
2798 // Focused window should receive event.
2799 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2800 windowTop->assertNoEvents();
2801 }
2802
TEST_F(InputDispatcherTest,SetFocusedWindow_DropRequestInvalidChannel)2803 TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2804 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2805 sp<FakeWindowHandle> window =
2806 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2807 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2808
2809 window->setFocusable(true);
2810 // Release channel for window is no longer valid.
2811 window->releaseChannel();
2812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2813 setFocusedWindow(window);
2814
2815 // Test inject a key down, should timeout.
2816 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2817 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
2818
2819 // window channel is invalid, so it should not receive any input event.
2820 window->assertNoEvents();
2821 }
2822
TEST_F(InputDispatcherTest,SetFocusedWindow_DropRequestNoFocusableWindow)2823 TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2824 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2825 sp<FakeWindowHandle> window =
2826 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2827 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2828
2829 // Window is not focusable.
2830 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2831 setFocusedWindow(window);
2832
2833 // Test inject a key down, should timeout.
2834 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2835 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
2836
2837 // window is invalid, so it should not receive any input event.
2838 window->assertNoEvents();
2839 }
2840
TEST_F(InputDispatcherTest,SetFocusedWindow_CheckFocusedToken)2841 TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2842 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2843 sp<FakeWindowHandle> windowTop =
2844 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2845 sp<FakeWindowHandle> windowSecond =
2846 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2847 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2848
2849 windowTop->setFocusable(true);
2850 windowSecond->setFocusable(true);
2851 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2852 setFocusedWindow(windowTop);
2853 windowTop->consumeFocusEvent(true);
2854
2855 setFocusedWindow(windowSecond, windowTop);
2856 windowSecond->consumeFocusEvent(true);
2857 windowTop->consumeFocusEvent(false);
2858
2859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2860 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
2861
2862 // Focused window should receive event.
2863 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2864 }
2865
TEST_F(InputDispatcherTest,SetFocusedWindow_DropRequestFocusTokenNotFocused)2866 TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2867 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2868 sp<FakeWindowHandle> windowTop =
2869 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2870 sp<FakeWindowHandle> windowSecond =
2871 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2872 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2873
2874 windowTop->setFocusable(true);
2875 windowSecond->setFocusable(true);
2876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2877 setFocusedWindow(windowSecond, windowTop);
2878
2879 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2880 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
2881
2882 // Event should be dropped.
2883 windowTop->assertNoEvents();
2884 windowSecond->assertNoEvents();
2885 }
2886
TEST_F(InputDispatcherTest,SetFocusedWindow_DeferInvisibleWindow)2887 TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2888 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2889 sp<FakeWindowHandle> window =
2890 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2891 sp<FakeWindowHandle> previousFocusedWindow =
2892 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2893 ADISPLAY_ID_DEFAULT);
2894 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2895
2896 window->setFocusable(true);
2897 previousFocusedWindow->setFocusable(true);
2898 window->setVisible(false);
2899 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2900 setFocusedWindow(previousFocusedWindow);
2901 previousFocusedWindow->consumeFocusEvent(true);
2902
2903 // Requesting focus on invisible window takes focus from currently focused window.
2904 setFocusedWindow(window);
2905 previousFocusedWindow->consumeFocusEvent(false);
2906
2907 // Injected key goes to pending queue.
2908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2909 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
2910 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
2911
2912 // Window does not get focus event or key down.
2913 window->assertNoEvents();
2914
2915 // Window becomes visible.
2916 window->setVisible(true);
2917 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2918
2919 // Window receives focus event.
2920 window->consumeFocusEvent(true);
2921 // Focused window receives key down.
2922 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2923 }
2924
TEST_F(InputDispatcherTest,DisplayRemoved)2925 TEST_F(InputDispatcherTest, DisplayRemoved) {
2926 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2927 sp<FakeWindowHandle> window =
2928 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
2929 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2930
2931 // window is granted focus.
2932 window->setFocusable(true);
2933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2934 setFocusedWindow(window);
2935 window->consumeFocusEvent(true);
2936
2937 // When a display is removed window loses focus.
2938 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
2939 window->consumeFocusEvent(false);
2940 }
2941
2942 /**
2943 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2944 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2945 * of the 'slipperyEnterWindow'.
2946 *
2947 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2948 * a way so that the touched location is no longer covered by the top window.
2949 *
2950 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2951 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2952 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2953 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2954 * with ACTION_DOWN).
2955 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2956 * window moved itself away from the touched location and had Flag::SLIPPERY.
2957 *
2958 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2959 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2960 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2961 *
2962 * In this test, we ensure that the event received by the bottom window has
2963 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2964 */
TEST_F(InputDispatcherTest,SlipperyWindow_SetsFlagPartiallyObscured)2965 TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2966 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2967 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2968
2969 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2970 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2971
2972 sp<FakeWindowHandle> slipperyExitWindow =
2973 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2974 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
2975 // Make sure this one overlaps the bottom window
2976 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2977 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2978 // one. Windows with the same owner are not considered to be occluding each other.
2979 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2980
2981 sp<FakeWindowHandle> slipperyEnterWindow =
2982 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2983 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2984
2985 mDispatcher->setInputWindows(
2986 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2987
2988 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2989 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2990 ADISPLAY_ID_DEFAULT, {{50, 50}});
2991 mDispatcher->notifyMotion(&args);
2992 slipperyExitWindow->consumeMotionDown();
2993 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2994 mDispatcher->setInputWindows(
2995 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2996
2997 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2998 ADISPLAY_ID_DEFAULT, {{51, 51}});
2999 mDispatcher->notifyMotion(&args);
3000
3001 slipperyExitWindow->consumeMotionCancel();
3002
3003 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3004 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3005 }
3006
3007 class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3008 protected:
3009 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3010 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3011
3012 std::shared_ptr<FakeApplicationHandle> mApp;
3013 sp<FakeWindowHandle> mWindow;
3014
SetUp()3015 virtual void SetUp() override {
3016 mFakePolicy = new FakeInputDispatcherPolicy();
3017 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
3018 mDispatcher = new InputDispatcher(mFakePolicy);
3019 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3020 ASSERT_EQ(OK, mDispatcher->start());
3021
3022 setUpWindow();
3023 }
3024
setUpWindow()3025 void setUpWindow() {
3026 mApp = std::make_shared<FakeApplicationHandle>();
3027 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3028
3029 mWindow->setFocusable(true);
3030 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3031 setFocusedWindow(mWindow);
3032 mWindow->consumeFocusEvent(true);
3033 }
3034
sendAndConsumeKeyDown(int32_t deviceId)3035 void sendAndConsumeKeyDown(int32_t deviceId) {
3036 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3037 keyArgs.deviceId = deviceId;
3038 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3039 mDispatcher->notifyKey(&keyArgs);
3040
3041 // Window should receive key down event.
3042 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3043 }
3044
expectKeyRepeatOnce(int32_t repeatCount)3045 void expectKeyRepeatOnce(int32_t repeatCount) {
3046 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3047 InputEvent* repeatEvent = mWindow->consume();
3048 ASSERT_NE(nullptr, repeatEvent);
3049
3050 uint32_t eventType = repeatEvent->getType();
3051 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3052
3053 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3054 uint32_t eventAction = repeatKeyEvent->getAction();
3055 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3056 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3057 }
3058
sendAndConsumeKeyUp(int32_t deviceId)3059 void sendAndConsumeKeyUp(int32_t deviceId) {
3060 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
3061 keyArgs.deviceId = deviceId;
3062 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3063 mDispatcher->notifyKey(&keyArgs);
3064
3065 // Window should receive key down event.
3066 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3067 0 /*expectedFlags*/);
3068 }
3069 };
3070
TEST_F(InputDispatcherKeyRepeatTest,FocusedWindow_ReceivesKeyRepeat)3071 TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
3072 sendAndConsumeKeyDown(1 /* deviceId */);
3073 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3074 expectKeyRepeatOnce(repeatCount);
3075 }
3076 }
3077
TEST_F(InputDispatcherKeyRepeatTest,FocusedWindow_ReceivesKeyRepeatFromTwoDevices)3078 TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3079 sendAndConsumeKeyDown(1 /* deviceId */);
3080 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3081 expectKeyRepeatOnce(repeatCount);
3082 }
3083 sendAndConsumeKeyDown(2 /* deviceId */);
3084 /* repeatCount will start from 1 for deviceId 2 */
3085 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3086 expectKeyRepeatOnce(repeatCount);
3087 }
3088 }
3089
TEST_F(InputDispatcherKeyRepeatTest,FocusedWindow_StopsKeyRepeatAfterUp)3090 TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
3091 sendAndConsumeKeyDown(1 /* deviceId */);
3092 expectKeyRepeatOnce(1 /*repeatCount*/);
3093 sendAndConsumeKeyUp(1 /* deviceId */);
3094 mWindow->assertNoEvents();
3095 }
3096
TEST_F(InputDispatcherKeyRepeatTest,FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp)3097 TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3098 sendAndConsumeKeyDown(1 /* deviceId */);
3099 expectKeyRepeatOnce(1 /*repeatCount*/);
3100 sendAndConsumeKeyDown(2 /* deviceId */);
3101 expectKeyRepeatOnce(1 /*repeatCount*/);
3102 // Stale key up from device 1.
3103 sendAndConsumeKeyUp(1 /* deviceId */);
3104 // Device 2 is still down, keep repeating
3105 expectKeyRepeatOnce(2 /*repeatCount*/);
3106 expectKeyRepeatOnce(3 /*repeatCount*/);
3107 // Device 2 key up
3108 sendAndConsumeKeyUp(2 /* deviceId */);
3109 mWindow->assertNoEvents();
3110 }
3111
TEST_F(InputDispatcherKeyRepeatTest,FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp)3112 TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3113 sendAndConsumeKeyDown(1 /* deviceId */);
3114 expectKeyRepeatOnce(1 /*repeatCount*/);
3115 sendAndConsumeKeyDown(2 /* deviceId */);
3116 expectKeyRepeatOnce(1 /*repeatCount*/);
3117 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3118 sendAndConsumeKeyUp(2 /* deviceId */);
3119 // Device 1 still holds key down, but the repeating was already stopped
3120 mWindow->assertNoEvents();
3121 }
3122
TEST_F(InputDispatcherKeyRepeatTest,FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher)3123 TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
3124 sendAndConsumeKeyDown(1 /* deviceId */);
3125 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3126 InputEvent* repeatEvent = mWindow->consume();
3127 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3128 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3129 IdGenerator::getSource(repeatEvent->getId()));
3130 }
3131 }
3132
TEST_F(InputDispatcherKeyRepeatTest,FocusedWindow_RepeatKeyEventsUseUniqueEventId)3133 TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
3134 sendAndConsumeKeyDown(1 /* deviceId */);
3135
3136 std::unordered_set<int32_t> idSet;
3137 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3138 InputEvent* repeatEvent = mWindow->consume();
3139 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3140 int32_t id = repeatEvent->getId();
3141 EXPECT_EQ(idSet.end(), idSet.find(id));
3142 idSet.insert(id);
3143 }
3144 }
3145
3146 /* Test InputDispatcher for MultiDisplay */
3147 class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3148 public:
SetUp()3149 virtual void SetUp() override {
3150 InputDispatcherTest::SetUp();
3151
3152 application1 = std::make_shared<FakeApplicationHandle>();
3153 windowInPrimary =
3154 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
3155
3156 // Set focus window for primary display, but focused display would be second one.
3157 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
3158 windowInPrimary->setFocusable(true);
3159 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
3160 setFocusedWindow(windowInPrimary);
3161 windowInPrimary->consumeFocusEvent(true);
3162
3163 application2 = std::make_shared<FakeApplicationHandle>();
3164 windowInSecondary =
3165 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
3166 // Set focus to second display window.
3167 // Set focus display to second one.
3168 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3169 // Set focus window for second display.
3170 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
3171 windowInSecondary->setFocusable(true);
3172 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
3173 setFocusedWindow(windowInSecondary);
3174 windowInSecondary->consumeFocusEvent(true);
3175 }
3176
TearDown()3177 virtual void TearDown() override {
3178 InputDispatcherTest::TearDown();
3179
3180 application1.reset();
3181 windowInPrimary.clear();
3182 application2.reset();
3183 windowInSecondary.clear();
3184 }
3185
3186 protected:
3187 std::shared_ptr<FakeApplicationHandle> application1;
3188 sp<FakeWindowHandle> windowInPrimary;
3189 std::shared_ptr<FakeApplicationHandle> application2;
3190 sp<FakeWindowHandle> windowInSecondary;
3191 };
3192
TEST_F(InputDispatcherFocusOnTwoDisplaysTest,SetInputWindow_MultiDisplayTouch)3193 TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3194 // Test touch down on primary display.
3195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3196 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3198 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3199 windowInSecondary->assertNoEvents();
3200
3201 // Test touch down on second display.
3202 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3203 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3204 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3205 windowInPrimary->assertNoEvents();
3206 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3207 }
3208
TEST_F(InputDispatcherFocusOnTwoDisplaysTest,SetInputWindow_MultiDisplayFocus)3209 TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
3210 // Test inject a key down with display id specified.
3211 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3212 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
3213 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
3214 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3215 windowInSecondary->assertNoEvents();
3216
3217 // Test inject a key down without display id specified.
3218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
3219 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
3220 windowInPrimary->assertNoEvents();
3221 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
3222
3223 // Remove all windows in secondary display.
3224 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
3225
3226 // Old focus should receive a cancel event.
3227 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3228 AKEY_EVENT_FLAG_CANCELED);
3229
3230 // Test inject a key down, should timeout because of no target window.
3231 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
3232 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
3233 windowInPrimary->assertNoEvents();
3234 windowInSecondary->consumeFocusEvent(false);
3235 windowInSecondary->assertNoEvents();
3236 }
3237
3238 // Test per-display input monitors for motion event.
TEST_F(InputDispatcherFocusOnTwoDisplaysTest,MonitorMotionEvent_MultiDisplay)3239 TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
3240 FakeMonitorReceiver monitorInPrimary =
3241 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3242 FakeMonitorReceiver monitorInSecondary =
3243 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3244
3245 // Test touch down on primary display.
3246 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3247 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3248 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3249 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3250 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3251 windowInSecondary->assertNoEvents();
3252 monitorInSecondary.assertNoEvents();
3253
3254 // Test touch down on second display.
3255 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3256 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3257 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3258 windowInPrimary->assertNoEvents();
3259 monitorInPrimary.assertNoEvents();
3260 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3261 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3262
3263 // Test inject a non-pointer motion event.
3264 // If specific a display, it will dispatch to the focused window of particular display,
3265 // or it will dispatch to the focused window of focused display.
3266 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3267 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3268 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3269 windowInPrimary->assertNoEvents();
3270 monitorInPrimary.assertNoEvents();
3271 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
3272 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
3273 }
3274
3275 // Test per-display input monitors for key event.
TEST_F(InputDispatcherFocusOnTwoDisplaysTest,MonitorKeyEvent_MultiDisplay)3276 TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
3277 // Input monitor per display.
3278 FakeMonitorReceiver monitorInPrimary =
3279 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3280 FakeMonitorReceiver monitorInSecondary =
3281 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3282
3283 // Test inject a key down.
3284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3285 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
3286 windowInPrimary->assertNoEvents();
3287 monitorInPrimary.assertNoEvents();
3288 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
3289 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
3290 }
3291
TEST_F(InputDispatcherFocusOnTwoDisplaysTest,CanFocusWindowOnUnfocusedDisplay)3292 TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3293 sp<FakeWindowHandle> secondWindowInPrimary =
3294 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3295 secondWindowInPrimary->setFocusable(true);
3296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3297 setFocusedWindow(secondWindowInPrimary);
3298 windowInPrimary->consumeFocusEvent(false);
3299 secondWindowInPrimary->consumeFocusEvent(true);
3300
3301 // Test inject a key down.
3302 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3303 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
3304 windowInPrimary->assertNoEvents();
3305 windowInSecondary->assertNoEvents();
3306 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3307 }
3308
3309 class InputFilterTest : public InputDispatcherTest {
3310 protected:
testNotifyMotion(int32_t displayId,bool expectToBeFiltered)3311 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
3312 NotifyMotionArgs motionArgs;
3313
3314 motionArgs =
3315 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
3316 mDispatcher->notifyMotion(&motionArgs);
3317 motionArgs =
3318 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
3319 mDispatcher->notifyMotion(&motionArgs);
3320 ASSERT_TRUE(mDispatcher->waitForIdle());
3321 if (expectToBeFiltered) {
3322 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
3323 } else {
3324 mFakePolicy->assertFilterInputEventWasNotCalled();
3325 }
3326 }
3327
testNotifyKey(bool expectToBeFiltered)3328 void testNotifyKey(bool expectToBeFiltered) {
3329 NotifyKeyArgs keyArgs;
3330
3331 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3332 mDispatcher->notifyKey(&keyArgs);
3333 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3334 mDispatcher->notifyKey(&keyArgs);
3335 ASSERT_TRUE(mDispatcher->waitForIdle());
3336
3337 if (expectToBeFiltered) {
3338 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
3339 } else {
3340 mFakePolicy->assertFilterInputEventWasNotCalled();
3341 }
3342 }
3343 };
3344
3345 // Test InputFilter for MotionEvent
TEST_F(InputFilterTest,MotionEvent_InputFilter)3346 TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3347 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3348 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3349 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3350
3351 // Enable InputFilter
3352 mDispatcher->setInputFilterEnabled(true);
3353 // Test touch on both primary and second display, and check if both events are filtered.
3354 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3355 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3356
3357 // Disable InputFilter
3358 mDispatcher->setInputFilterEnabled(false);
3359 // Test touch on both primary and second display, and check if both events aren't filtered.
3360 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3361 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3362 }
3363
3364 // Test InputFilter for KeyEvent
TEST_F(InputFilterTest,KeyEvent_InputFilter)3365 TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3366 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3367 testNotifyKey(/*expectToBeFiltered*/ false);
3368
3369 // Enable InputFilter
3370 mDispatcher->setInputFilterEnabled(true);
3371 // Send a key event, and check if it is filtered.
3372 testNotifyKey(/*expectToBeFiltered*/ true);
3373
3374 // Disable InputFilter
3375 mDispatcher->setInputFilterEnabled(false);
3376 // Send a key event, and check if it isn't filtered.
3377 testNotifyKey(/*expectToBeFiltered*/ false);
3378 }
3379
3380 class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3381 protected:
SetUp()3382 virtual void SetUp() override {
3383 InputDispatcherTest::SetUp();
3384
3385 /**
3386 * We don't need to enable input filter to test the injected event policy, but we enabled it
3387 * here to make the tests more realistic, since this policy only matters when inputfilter is
3388 * on.
3389 */
3390 mDispatcher->setInputFilterEnabled(true);
3391
3392 std::shared_ptr<InputApplicationHandle> application =
3393 std::make_shared<FakeApplicationHandle>();
3394 mWindow =
3395 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3396
3397 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3398 mWindow->setFocusable(true);
3399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3400 setFocusedWindow(mWindow);
3401 mWindow->consumeFocusEvent(true);
3402 }
3403
testInjectedKey(int32_t policyFlags,int32_t injectedDeviceId,int32_t resolvedDeviceId,int32_t flags)3404 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3405 int32_t flags) {
3406 KeyEvent event;
3407
3408 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3409 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3410 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3411 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3412 const int32_t additionalPolicyFlags =
3413 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3414 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3415 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3416 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3417 policyFlags | additionalPolicyFlags));
3418
3419 InputEvent* received = mWindow->consume();
3420 ASSERT_NE(nullptr, received);
3421 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3422 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3423 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3424 ASSERT_EQ(flags, keyEvent.getFlags());
3425 }
3426
testInjectedMotion(int32_t policyFlags,int32_t injectedDeviceId,int32_t resolvedDeviceId,int32_t flags)3427 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3428 int32_t flags) {
3429 MotionEvent event;
3430 PointerProperties pointerProperties[1];
3431 PointerCoords pointerCoords[1];
3432 pointerProperties[0].clear();
3433 pointerProperties[0].id = 0;
3434 pointerCoords[0].clear();
3435 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3436 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3437
3438 ui::Transform identityTransform;
3439 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3440 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3441 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3442 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3443 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
3444 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
3445 0 /*INVALID_DISPLAY_SIZE*/, 0 /*INVALID_DISPLAY_SIZE*/, eventTime,
3446 eventTime,
3447 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3448
3449 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3451 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3452 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3453 policyFlags | additionalPolicyFlags));
3454
3455 InputEvent* received = mWindow->consume();
3456 ASSERT_NE(nullptr, received);
3457 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3458 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3459 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3460 ASSERT_EQ(flags, motionEvent.getFlags());
3461 }
3462
3463 private:
3464 sp<FakeWindowHandle> mWindow;
3465 };
3466
TEST_F(InputFilterInjectionPolicyTest,TrustedFilteredEvents_KeepOriginalDeviceId)3467 TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
3468 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3469 // filter. Without it, the event will no different from a regularly injected event, and the
3470 // injected device id will be overwritten.
3471 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3472 0 /*flags*/);
3473 }
3474
TEST_F(InputFilterInjectionPolicyTest,KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag)3475 TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3476 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3477 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3478 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3479 }
3480
TEST_F(InputFilterInjectionPolicyTest,MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag)3481 TEST_F(InputFilterInjectionPolicyTest,
3482 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3483 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3484 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3485 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3486 }
3487
TEST_F(InputFilterInjectionPolicyTest,RegularInjectedEvents_ReceiveVirtualDeviceId)3488 TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3489 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
3490 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
3491 }
3492
3493 class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
SetUp()3494 virtual void SetUp() override {
3495 InputDispatcherTest::SetUp();
3496
3497 std::shared_ptr<FakeApplicationHandle> application =
3498 std::make_shared<FakeApplicationHandle>();
3499 mUnfocusedWindow =
3500 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3501 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3502 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3503 // window.
3504 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
3505
3506 mFocusedWindow =
3507 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3508 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
3509 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
3510
3511 // Set focused application.
3512 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3513 mFocusedWindow->setFocusable(true);
3514
3515 // Expect one focus window exist in display.
3516 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3517 setFocusedWindow(mFocusedWindow);
3518 mFocusedWindow->consumeFocusEvent(true);
3519 }
3520
TearDown()3521 virtual void TearDown() override {
3522 InputDispatcherTest::TearDown();
3523
3524 mUnfocusedWindow.clear();
3525 mFocusedWindow.clear();
3526 }
3527
3528 protected:
3529 sp<FakeWindowHandle> mUnfocusedWindow;
3530 sp<FakeWindowHandle> mFocusedWindow;
3531 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
3532 };
3533
3534 // Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3535 // DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3536 // the onPointerDownOutsideFocus callback.
TEST_F(InputDispatcherOnPointerDownOutsideFocus,OnPointerDownOutsideFocus_Success)3537 TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
3538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3539 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3540 {20, 20}))
3541 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3542 mUnfocusedWindow->consumeMotionDown();
3543
3544 ASSERT_TRUE(mDispatcher->waitForIdle());
3545 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3546 }
3547
3548 // Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3549 // DOWN on the window that doesn't have focus. Ensure no window received the
3550 // onPointerDownOutsideFocus callback.
TEST_F(InputDispatcherOnPointerDownOutsideFocus,OnPointerDownOutsideFocus_NonPointerSource)3551 TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
3552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3553 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
3554 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3555 mFocusedWindow->consumeMotionDown();
3556
3557 ASSERT_TRUE(mDispatcher->waitForIdle());
3558 mFakePolicy->assertOnPointerDownWasNotCalled();
3559 }
3560
3561 // Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3562 // have focus. Ensure no window received the onPointerDownOutsideFocus callback.
TEST_F(InputDispatcherOnPointerDownOutsideFocus,OnPointerDownOutsideFocus_NonMotionFailure)3563 TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
3564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3565 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
3566 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
3567 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3568
3569 ASSERT_TRUE(mDispatcher->waitForIdle());
3570 mFakePolicy->assertOnPointerDownWasNotCalled();
3571 }
3572
3573 // Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3574 // DOWN on the window that already has focus. Ensure no window received the
3575 // onPointerDownOutsideFocus callback.
TEST_F(InputDispatcherOnPointerDownOutsideFocus,OnPointerDownOutsideFocus_OnAlreadyFocusedWindow)3576 TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
3577 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3578 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3579 FOCUSED_WINDOW_TOUCH_POINT))
3580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3581 mFocusedWindow->consumeMotionDown();
3582
3583 ASSERT_TRUE(mDispatcher->waitForIdle());
3584 mFakePolicy->assertOnPointerDownWasNotCalled();
3585 }
3586
3587 // Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3588 // NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
TEST_F(InputDispatcherOnPointerDownOutsideFocus,NoFocusChangeFlag)3589 TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3590 const MotionEvent event =
3591 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3592 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3593 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3594 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3595 .build();
3596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3597 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3598 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3599
3600 ASSERT_TRUE(mDispatcher->waitForIdle());
3601 mFakePolicy->assertOnPointerDownWasNotCalled();
3602 // Ensure that the unfocused window did not receive any FOCUS events.
3603 mUnfocusedWindow->assertNoEvents();
3604 }
3605
3606 // These tests ensures we can send touch events to a single client when there are multiple input
3607 // windows that point to the same client token.
3608 class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
SetUp()3609 virtual void SetUp() override {
3610 InputDispatcherTest::SetUp();
3611
3612 std::shared_ptr<FakeApplicationHandle> application =
3613 std::make_shared<FakeApplicationHandle>();
3614 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3615 ADISPLAY_ID_DEFAULT);
3616 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3617 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
3618 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3619 mWindow1->setFrame(Rect(0, 0, 100, 100));
3620
3621 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3622 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
3623 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3624 mWindow2->setFrame(Rect(100, 100, 200, 200));
3625
3626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
3627 }
3628
3629 protected:
3630 sp<FakeWindowHandle> mWindow1;
3631 sp<FakeWindowHandle> mWindow2;
3632
3633 // Helper function to convert the point from screen coordinates into the window's space
getPointInWindow(const WindowInfo * windowInfo,const PointF & point)3634 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
3635 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3636 return {vals.x, vals.y};
3637 }
3638
consumeMotionEvent(const sp<FakeWindowHandle> & window,int32_t expectedAction,const std::vector<PointF> & points)3639 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3640 const std::vector<PointF>& points) {
3641 const std::string name = window->getName();
3642 InputEvent* event = window->consume();
3643
3644 ASSERT_NE(nullptr, event) << name.c_str()
3645 << ": consumer should have returned non-NULL event.";
3646
3647 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3648 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3649 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3650
3651 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3652 EXPECT_EQ(expectedAction, motionEvent.getAction());
3653
3654 for (size_t i = 0; i < points.size(); i++) {
3655 float expectedX = points[i].x;
3656 float expectedY = points[i].y;
3657
3658 EXPECT_EQ(expectedX, motionEvent.getX(i))
3659 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3660 << ", got " << motionEvent.getX(i);
3661 EXPECT_EQ(expectedY, motionEvent.getY(i))
3662 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3663 << ", got " << motionEvent.getY(i);
3664 }
3665 }
3666
touchAndAssertPositions(int32_t action,std::vector<PointF> touchedPoints,std::vector<PointF> expectedPoints)3667 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3668 std::vector<PointF> expectedPoints) {
3669 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3670 ADISPLAY_ID_DEFAULT, touchedPoints);
3671 mDispatcher->notifyMotion(&motionArgs);
3672
3673 // Always consume from window1 since it's the window that has the InputReceiver
3674 consumeMotionEvent(mWindow1, action, expectedPoints);
3675 }
3676 };
3677
TEST_F(InputDispatcherMultiWindowSameTokenTests,SingleTouchSameScale)3678 TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3679 // Touch Window 1
3680 PointF touchedPoint = {10, 10};
3681 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
3682 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3683
3684 // Release touch on Window 1
3685 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
3686
3687 // Touch Window 2
3688 touchedPoint = {150, 150};
3689 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3690 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3691 }
3692
TEST_F(InputDispatcherMultiWindowSameTokenTests,SingleTouchDifferentTransform)3693 TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3694 // Set scale value for window2
3695 mWindow2->setWindowScale(0.5f, 0.5f);
3696
3697 // Touch Window 1
3698 PointF touchedPoint = {10, 10};
3699 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
3700 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3701 // Release touch on Window 1
3702 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
3703
3704 // Touch Window 2
3705 touchedPoint = {150, 150};
3706 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3707 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3708 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
3709
3710 // Update the transform so rotation is set
3711 mWindow2->setWindowTransform(0, -1, 1, 0);
3712 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3713 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3714 }
3715
TEST_F(InputDispatcherMultiWindowSameTokenTests,MultipleTouchDifferentTransform)3716 TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
3717 mWindow2->setWindowScale(0.5f, 0.5f);
3718
3719 // Touch Window 1
3720 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3721 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
3722 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
3723
3724 // Touch Window 2
3725 int32_t actionPointerDown =
3726 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3727 touchedPoints.push_back(PointF{150, 150});
3728 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3729 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3730
3731 // Release Window 2
3732 int32_t actionPointerUp =
3733 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3734 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3735 expectedPoints.pop_back();
3736
3737 // Update the transform so rotation is set for Window 2
3738 mWindow2->setWindowTransform(0, -1, 1, 0);
3739 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3740 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3741 }
3742
TEST_F(InputDispatcherMultiWindowSameTokenTests,MultipleTouchMoveDifferentTransform)3743 TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
3744 mWindow2->setWindowScale(0.5f, 0.5f);
3745
3746 // Touch Window 1
3747 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3748 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
3749 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
3750
3751 // Touch Window 2
3752 int32_t actionPointerDown =
3753 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3754 touchedPoints.push_back(PointF{150, 150});
3755 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3756
3757 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3758
3759 // Move both windows
3760 touchedPoints = {{20, 20}, {175, 175}};
3761 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3762 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3763
3764 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
3765
3766 // Release Window 2
3767 int32_t actionPointerUp =
3768 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3769 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3770 expectedPoints.pop_back();
3771
3772 // Touch Window 2
3773 mWindow2->setWindowTransform(0, -1, 1, 0);
3774 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3775 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3776
3777 // Move both windows
3778 touchedPoints = {{20, 20}, {175, 175}};
3779 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3780 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3781
3782 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
3783 }
3784
TEST_F(InputDispatcherMultiWindowSameTokenTests,MultipleWindowsFirstTouchWithScale)3785 TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3786 mWindow1->setWindowScale(0.5f, 0.5f);
3787
3788 // Touch Window 1
3789 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3790 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
3791 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
3792
3793 // Touch Window 2
3794 int32_t actionPointerDown =
3795 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3796 touchedPoints.push_back(PointF{150, 150});
3797 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3798
3799 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3800
3801 // Move both windows
3802 touchedPoints = {{20, 20}, {175, 175}};
3803 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3804 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3805
3806 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
3807 }
3808
3809 class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
SetUp()3810 virtual void SetUp() override {
3811 InputDispatcherTest::SetUp();
3812
3813 mApplication = std::make_shared<FakeApplicationHandle>();
3814 mApplication->setDispatchingTimeout(20ms);
3815 mWindow =
3816 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3817 mWindow->setFrame(Rect(0, 0, 30, 30));
3818 mWindow->setDispatchingTimeout(30ms);
3819 mWindow->setFocusable(true);
3820 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3821 // window.
3822 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
3823
3824 // Set focused application.
3825 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3826
3827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3828 setFocusedWindow(mWindow);
3829 mWindow->consumeFocusEvent(true);
3830 }
3831
TearDown()3832 virtual void TearDown() override {
3833 InputDispatcherTest::TearDown();
3834 mWindow.clear();
3835 }
3836
3837 protected:
3838 std::shared_ptr<FakeApplicationHandle> mApplication;
3839 sp<FakeWindowHandle> mWindow;
3840 static constexpr PointF WINDOW_LOCATION = {20, 20};
3841
tapOnWindow()3842 void tapOnWindow() {
3843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3844 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3845 WINDOW_LOCATION));
3846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3847 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3848 WINDOW_LOCATION));
3849 }
3850 };
3851
3852 // Send a tap and respond, which should not cause an ANR.
TEST_F(InputDispatcherSingleWindowAnr,WhenTouchIsConsumed_NoAnr)3853 TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3854 tapOnWindow();
3855 mWindow->consumeMotionDown();
3856 mWindow->consumeMotionUp();
3857 ASSERT_TRUE(mDispatcher->waitForIdle());
3858 mFakePolicy->assertNotifyAnrWasNotCalled();
3859 }
3860
3861 // Send a regular key and respond, which should not cause an ANR.
TEST_F(InputDispatcherSingleWindowAnr,WhenKeyIsConsumed_NoAnr)3862 TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
3863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
3864 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3865 ASSERT_TRUE(mDispatcher->waitForIdle());
3866 mFakePolicy->assertNotifyAnrWasNotCalled();
3867 }
3868
TEST_F(InputDispatcherSingleWindowAnr,WhenFocusedApplicationChanges_NoAnr)3869 TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3870 mWindow->setFocusable(false);
3871 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3872 mWindow->consumeFocusEvent(false);
3873
3874 InputEventInjectionResult result =
3875 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
3876 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3877 false /* allowKeyRepeat */);
3878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
3879 // Key will not go to window because we have no focused window.
3880 // The 'no focused window' ANR timer should start instead.
3881
3882 // Now, the focused application goes away.
3883 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3884 // The key should get dropped and there should be no ANR.
3885
3886 ASSERT_TRUE(mDispatcher->waitForIdle());
3887 mFakePolicy->assertNotifyAnrWasNotCalled();
3888 }
3889
3890 // Send an event to the app and have the app not respond right away.
3891 // When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3892 // So InputDispatcher will enqueue ACTION_CANCEL event as well.
TEST_F(InputDispatcherSingleWindowAnr,OnPointerDown_BasicAnr)3893 TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
3894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3895 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3896 WINDOW_LOCATION));
3897
3898 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3899 ASSERT_TRUE(sequenceNum);
3900 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
3901 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
3902
3903 mWindow->finishEvent(*sequenceNum);
3904 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3905 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3906 ASSERT_TRUE(mDispatcher->waitForIdle());
3907 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
3908 }
3909
3910 // Send a key to the app and have the app not respond right away.
TEST_F(InputDispatcherSingleWindowAnr,OnKeyDown_BasicAnr)3911 TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3912 // Inject a key, and don't respond - expect that ANR is called.
3913 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
3914 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3915 ASSERT_TRUE(sequenceNum);
3916 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
3917 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
3918 ASSERT_TRUE(mDispatcher->waitForIdle());
3919 }
3920
3921 // We have a focused application, but no focused window
TEST_F(InputDispatcherSingleWindowAnr,FocusedApplication_NoFocusedWindow)3922 TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
3923 mWindow->setFocusable(false);
3924 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3925 mWindow->consumeFocusEvent(false);
3926
3927 // taps on the window work as normal
3928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3929 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3930 WINDOW_LOCATION));
3931 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3932 mDispatcher->waitForIdle();
3933 mFakePolicy->assertNotifyAnrWasNotCalled();
3934
3935 // Once a focused event arrives, we get an ANR for this application
3936 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3937 // injection times out (instead of failing).
3938 const InputEventInjectionResult result =
3939 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
3940 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
3941 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
3942 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
3943 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
3944 ASSERT_TRUE(mDispatcher->waitForIdle());
3945 }
3946
3947 // We have a focused application, but no focused window
3948 // Make sure that we don't notify policy twice about the same ANR.
TEST_F(InputDispatcherSingleWindowAnr,NoFocusedWindow_DoesNotSendDuplicateAnr)3949 TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
3950 mWindow->setFocusable(false);
3951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3952 mWindow->consumeFocusEvent(false);
3953
3954 // Once a focused event arrives, we get an ANR for this application
3955 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3956 // injection times out (instead of failing).
3957 const InputEventInjectionResult result =
3958 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
3959 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
3960 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
3961 const std::chrono::duration appTimeout =
3962 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
3963 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
3964
3965 std::this_thread::sleep_for(appTimeout);
3966 // ANR should not be raised again. It is up to policy to do that if it desires.
3967 mFakePolicy->assertNotifyAnrWasNotCalled();
3968
3969 // If we now get a focused window, the ANR should stop, but the policy handles that via
3970 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
3971 ASSERT_TRUE(mDispatcher->waitForIdle());
3972 }
3973
3974 // We have a focused application, but no focused window
TEST_F(InputDispatcherSingleWindowAnr,NoFocusedWindow_DropsFocusedEvents)3975 TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
3976 mWindow->setFocusable(false);
3977 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3978 mWindow->consumeFocusEvent(false);
3979
3980 // Once a focused event arrives, we get an ANR for this application
3981 const InputEventInjectionResult result =
3982 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
3983 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3984 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
3985
3986 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
3987 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
3988
3989 // Future focused events get dropped right away
3990 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
3991 ASSERT_TRUE(mDispatcher->waitForIdle());
3992 mWindow->assertNoEvents();
3993 }
3994
3995 /**
3996 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3997 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3998 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3999 * the ANR mechanism should still work.
4000 *
4001 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4002 * DOWN event, while not responding on the second one.
4003 */
TEST_F(InputDispatcherSingleWindowAnr,Anr_HandlesEventsWithIdenticalTimestamps)4004 TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4005 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4006 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4007 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4008 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4009 AMOTION_EVENT_INVALID_CURSOR_POSITION},
4010 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
4011
4012 // Now send ACTION_UP, with identical timestamp
4013 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4014 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4015 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4016 AMOTION_EVENT_INVALID_CURSOR_POSITION},
4017 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
4018
4019 // We have now sent down and up. Let's consume first event and then ANR on the second.
4020 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4021 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4022 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
4023 }
4024
4025 // If an app is not responding to a key event, gesture monitors should continue to receive
4026 // new motion events
TEST_F(InputDispatcherSingleWindowAnr,GestureMonitors_ReceiveEventsDuringAppAnrOnKey)4027 TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4028 FakeMonitorReceiver monitor =
4029 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4030 true /*isGestureMonitor*/);
4031
4032 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4033 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
4034 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
4036
4037 // Stuck on the ACTION_UP
4038 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4039 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
4040
4041 // New tap will go to the gesture monitor, but not to the window
4042 tapOnWindow();
4043 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4044 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4045
4046 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4047 mDispatcher->waitForIdle();
4048 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
4049 mWindow->assertNoEvents();
4050 monitor.assertNoEvents();
4051 }
4052
4053 // If an app is not responding to a motion event, gesture monitors should continue to receive
4054 // new motion events
TEST_F(InputDispatcherSingleWindowAnr,GestureMonitors_ReceiveEventsDuringAppAnrOnMotion)4055 TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4056 FakeMonitorReceiver monitor =
4057 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4058 true /*isGestureMonitor*/);
4059
4060 tapOnWindow();
4061 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4062 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4063
4064 mWindow->consumeMotionDown();
4065 // Stuck on the ACTION_UP
4066 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4067 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
4068
4069 // New tap will go to the gesture monitor, but not to the window
4070 tapOnWindow();
4071 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4072 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4073
4074 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4075 mDispatcher->waitForIdle();
4076 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
4077 mWindow->assertNoEvents();
4078 monitor.assertNoEvents();
4079 }
4080
4081 // If a window is unresponsive, then you get anr. if the window later catches up and starts to
4082 // process events, you don't get an anr. When the window later becomes unresponsive again, you
4083 // get an ANR again.
4084 // 1. tap -> block on ACTION_UP -> receive ANR
4085 // 2. consume all pending events (= queue becomes healthy again)
4086 // 3. tap again -> block on ACTION_UP again -> receive ANR second time
TEST_F(InputDispatcherSingleWindowAnr,SameWindow_CanReceiveAnrTwice)4087 TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4088 tapOnWindow();
4089
4090 mWindow->consumeMotionDown();
4091 // Block on ACTION_UP
4092 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4093 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
4094 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4095 mDispatcher->waitForIdle();
4096 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
4097 mWindow->assertNoEvents();
4098
4099 tapOnWindow();
4100 mWindow->consumeMotionDown();
4101 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
4102 mWindow->consumeMotionUp();
4103
4104 mDispatcher->waitForIdle();
4105 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
4106 mFakePolicy->assertNotifyAnrWasNotCalled();
4107 mWindow->assertNoEvents();
4108 }
4109
4110 // If a connection remains unresponsive for a while, make sure policy is only notified once about
4111 // it.
TEST_F(InputDispatcherSingleWindowAnr,Policy_DoesNotGetDuplicateAnr)4112 TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
4113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4114 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4115 WINDOW_LOCATION));
4116
4117 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4118 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
4119 std::this_thread::sleep_for(windowTimeout);
4120 // 'notifyConnectionUnresponsive' should only be called once per connection
4121 mFakePolicy->assertNotifyAnrWasNotCalled();
4122 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
4123 mWindow->consumeMotionDown();
4124 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4125 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4126 mWindow->assertNoEvents();
4127 mDispatcher->waitForIdle();
4128 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
4129 mFakePolicy->assertNotifyAnrWasNotCalled();
4130 }
4131
4132 /**
4133 * If a window is processing a motion event, and then a key event comes in, the key event should
4134 * not to to the focused window until the motion is processed.
4135 *
4136 * Warning!!!
4137 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4138 * and the injection timeout that we specify when injecting the key.
4139 * We must have the injection timeout (10ms) be smaller than
4140 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4141 *
4142 * If that value changes, this test should also change.
4143 */
TEST_F(InputDispatcherSingleWindowAnr,Key_StaysPendingWhileMotionIsProcessed)4144 TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4145 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4147
4148 tapOnWindow();
4149 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4150 ASSERT_TRUE(downSequenceNum);
4151 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4152 ASSERT_TRUE(upSequenceNum);
4153 // Don't finish the events yet, and send a key
4154 // Injection will "succeed" because we will eventually give up and send the key to the focused
4155 // window even if motions are still being processed. But because the injection timeout is short,
4156 // we will receive INJECTION_TIMED_OUT as the result.
4157
4158 InputEventInjectionResult result =
4159 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
4160 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4161 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
4162 // Key will not be sent to the window, yet, because the window is still processing events
4163 // and the key remains pending, waiting for the touch events to be processed
4164 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4165 ASSERT_FALSE(keySequenceNum);
4166
4167 std::this_thread::sleep_for(500ms);
4168 // if we wait long enough though, dispatcher will give up, and still send the key
4169 // to the focused window, even though we have not yet finished the motion event
4170 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4171 mWindow->finishEvent(*downSequenceNum);
4172 mWindow->finishEvent(*upSequenceNum);
4173 }
4174
4175 /**
4176 * If a window is processing a motion event, and then a key event comes in, the key event should
4177 * not go to the focused window until the motion is processed.
4178 * If then a new motion comes in, then the pending key event should be going to the currently
4179 * focused window right away.
4180 */
TEST_F(InputDispatcherSingleWindowAnr,PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn)4181 TEST_F(InputDispatcherSingleWindowAnr,
4182 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4183 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4184 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4185
4186 tapOnWindow();
4187 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4188 ASSERT_TRUE(downSequenceNum);
4189 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4190 ASSERT_TRUE(upSequenceNum);
4191 // Don't finish the events yet, and send a key
4192 // Injection is async, so it will succeed
4193 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4194 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
4195 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
4196 // At this point, key is still pending, and should not be sent to the application yet.
4197 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4198 ASSERT_FALSE(keySequenceNum);
4199
4200 // Now tap down again. It should cause the pending key to go to the focused window right away.
4201 tapOnWindow();
4202 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4203 // the other events yet. We can finish events in any order.
4204 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4205 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4206 mWindow->consumeMotionDown();
4207 mWindow->consumeMotionUp();
4208 mWindow->assertNoEvents();
4209 }
4210
4211 class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
SetUp()4212 virtual void SetUp() override {
4213 InputDispatcherTest::SetUp();
4214
4215 mApplication = std::make_shared<FakeApplicationHandle>();
4216 mApplication->setDispatchingTimeout(10ms);
4217 mUnfocusedWindow =
4218 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4219 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4220 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4221 // window.
4222 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
4223 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4224 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4225 WindowInfo::Flag::SPLIT_TOUCH);
4226
4227 mFocusedWindow =
4228 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
4229 mFocusedWindow->setDispatchingTimeout(30ms);
4230 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
4231 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
4232
4233 // Set focused application.
4234 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4235 mFocusedWindow->setFocusable(true);
4236
4237 // Expect one focus window exist in display.
4238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4239 setFocusedWindow(mFocusedWindow);
4240 mFocusedWindow->consumeFocusEvent(true);
4241 }
4242
TearDown()4243 virtual void TearDown() override {
4244 InputDispatcherTest::TearDown();
4245
4246 mUnfocusedWindow.clear();
4247 mFocusedWindow.clear();
4248 }
4249
4250 protected:
4251 std::shared_ptr<FakeApplicationHandle> mApplication;
4252 sp<FakeWindowHandle> mUnfocusedWindow;
4253 sp<FakeWindowHandle> mFocusedWindow;
4254 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4255 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4256 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4257
tapOnFocusedWindow()4258 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4259
tapOnUnfocusedWindow()4260 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4261
4262 private:
tap(const PointF & location)4263 void tap(const PointF& location) {
4264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4265 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4266 location));
4267 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4268 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4269 location));
4270 }
4271 };
4272
4273 // If we have 2 windows that are both unresponsive, the one with the shortest timeout
4274 // should be ANR'd first.
TEST_F(InputDispatcherMultiWindowAnr,TwoWindows_BothUnresponsive)4275 TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
4276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4277 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4278 FOCUSED_WINDOW_LOCATION))
4279 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4280 mFocusedWindow->consumeMotionDown();
4281 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4282 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4283 // We consumed all events, so no ANR
4284 ASSERT_TRUE(mDispatcher->waitForIdle());
4285 mFakePolicy->assertNotifyAnrWasNotCalled();
4286
4287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4288 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4289 FOCUSED_WINDOW_LOCATION));
4290 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4291 ASSERT_TRUE(unfocusedSequenceNum);
4292
4293 const std::chrono::duration timeout =
4294 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4295 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
4296 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4297 // sequence to make it consistent
4298 mFocusedWindow->consumeMotionCancel();
4299 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
4300 mFocusedWindow->consumeMotionDown();
4301 // This cancel is generated because the connection was unresponsive
4302 mFocusedWindow->consumeMotionCancel();
4303 mFocusedWindow->assertNoEvents();
4304 mUnfocusedWindow->assertNoEvents();
4305 ASSERT_TRUE(mDispatcher->waitForIdle());
4306 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
4307 mFakePolicy->assertNotifyAnrWasNotCalled();
4308 }
4309
4310 // If we have 2 windows with identical timeouts that are both unresponsive,
4311 // it doesn't matter which order they should have ANR.
4312 // But we should receive ANR for both.
TEST_F(InputDispatcherMultiWindowAnr,TwoWindows_BothUnresponsiveWithSameTimeout)4313 TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4314 // Set the timeout for unfocused window to match the focused window
4315 mUnfocusedWindow->setDispatchingTimeout(10ms);
4316 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4317
4318 tapOnFocusedWindow();
4319 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
4320 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4321 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
4322
4323 // We don't know which window will ANR first. But both of them should happen eventually.
4324 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4325 mFocusedWindow->getToken() == anrConnectionToken2);
4326 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4327 mUnfocusedWindow->getToken() == anrConnectionToken2);
4328
4329 ASSERT_TRUE(mDispatcher->waitForIdle());
4330 mFakePolicy->assertNotifyAnrWasNotCalled();
4331
4332 mFocusedWindow->consumeMotionDown();
4333 mFocusedWindow->consumeMotionUp();
4334 mUnfocusedWindow->consumeMotionOutside();
4335
4336 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4337 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
4338
4339 // Both applications should be marked as responsive, in any order
4340 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4341 mFocusedWindow->getToken() == responsiveToken2);
4342 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4343 mUnfocusedWindow->getToken() == responsiveToken2);
4344 mFakePolicy->assertNotifyAnrWasNotCalled();
4345 }
4346
4347 // If a window is already not responding, the second tap on the same window should be ignored.
4348 // We should also log an error to account for the dropped event (not tested here).
4349 // At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
TEST_F(InputDispatcherMultiWindowAnr,DuringAnr_SecondTapIsIgnored)4350 TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4351 tapOnFocusedWindow();
4352 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4353 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4354 // Receive the events, but don't respond
4355 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4356 ASSERT_TRUE(downEventSequenceNum);
4357 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4358 ASSERT_TRUE(upEventSequenceNum);
4359 const std::chrono::duration timeout =
4360 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4361 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
4362
4363 // Tap once again
4364 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
4365 ASSERT_EQ(InputEventInjectionResult::FAILED,
4366 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4367 FOCUSED_WINDOW_LOCATION));
4368 ASSERT_EQ(InputEventInjectionResult::FAILED,
4369 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4370 FOCUSED_WINDOW_LOCATION));
4371 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4372 // valid touch target
4373 mUnfocusedWindow->assertNoEvents();
4374
4375 // Consume the first tap
4376 mFocusedWindow->finishEvent(*downEventSequenceNum);
4377 mFocusedWindow->finishEvent(*upEventSequenceNum);
4378 ASSERT_TRUE(mDispatcher->waitForIdle());
4379 // The second tap did not go to the focused window
4380 mFocusedWindow->assertNoEvents();
4381 // Since all events are finished, connection should be deemed healthy again
4382 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
4383 mFakePolicy->assertNotifyAnrWasNotCalled();
4384 }
4385
4386 // If you tap outside of all windows, there will not be ANR
TEST_F(InputDispatcherMultiWindowAnr,TapOutsideAllWindows_DoesNotAnr)4387 TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
4388 ASSERT_EQ(InputEventInjectionResult::FAILED,
4389 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4390 LOCATION_OUTSIDE_ALL_WINDOWS));
4391 ASSERT_TRUE(mDispatcher->waitForIdle());
4392 mFakePolicy->assertNotifyAnrWasNotCalled();
4393 }
4394
4395 // Since the focused window is paused, tapping on it should not produce any events
TEST_F(InputDispatcherMultiWindowAnr,Window_CanBePaused)4396 TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4397 mFocusedWindow->setPaused(true);
4398 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4399
4400 ASSERT_EQ(InputEventInjectionResult::FAILED,
4401 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4402 FOCUSED_WINDOW_LOCATION));
4403
4404 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4405 ASSERT_TRUE(mDispatcher->waitForIdle());
4406 // Should not ANR because the window is paused, and touches shouldn't go to it
4407 mFakePolicy->assertNotifyAnrWasNotCalled();
4408
4409 mFocusedWindow->assertNoEvents();
4410 mUnfocusedWindow->assertNoEvents();
4411 }
4412
4413 /**
4414 * If a window is processing a motion event, and then a key event comes in, the key event should
4415 * not to to the focused window until the motion is processed.
4416 * If a different window becomes focused at this time, the key should go to that window instead.
4417 *
4418 * Warning!!!
4419 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4420 * and the injection timeout that we specify when injecting the key.
4421 * We must have the injection timeout (10ms) be smaller than
4422 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4423 *
4424 * If that value changes, this test should also change.
4425 */
TEST_F(InputDispatcherMultiWindowAnr,PendingKey_GoesToNewlyFocusedWindow)4426 TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4427 // Set a long ANR timeout to prevent it from triggering
4428 mFocusedWindow->setDispatchingTimeout(2s);
4429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4430
4431 tapOnUnfocusedWindow();
4432 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4433 ASSERT_TRUE(downSequenceNum);
4434 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4435 ASSERT_TRUE(upSequenceNum);
4436 // Don't finish the events yet, and send a key
4437 // Injection will succeed because we will eventually give up and send the key to the focused
4438 // window even if motions are still being processed.
4439
4440 InputEventInjectionResult result =
4441 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
4442 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4443 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
4444 // Key will not be sent to the window, yet, because the window is still processing events
4445 // and the key remains pending, waiting for the touch events to be processed
4446 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4447 ASSERT_FALSE(keySequenceNum);
4448
4449 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
4450 mFocusedWindow->setFocusable(false);
4451 mUnfocusedWindow->setFocusable(true);
4452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4453 setFocusedWindow(mUnfocusedWindow);
4454
4455 // Focus events should precede the key events
4456 mUnfocusedWindow->consumeFocusEvent(true);
4457 mFocusedWindow->consumeFocusEvent(false);
4458
4459 // Finish the tap events, which should unblock dispatcher
4460 mUnfocusedWindow->finishEvent(*downSequenceNum);
4461 mUnfocusedWindow->finishEvent(*upSequenceNum);
4462
4463 // Now that all queues are cleared and no backlog in the connections, the key event
4464 // can finally go to the newly focused "mUnfocusedWindow".
4465 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4466 mFocusedWindow->assertNoEvents();
4467 mUnfocusedWindow->assertNoEvents();
4468 mFakePolicy->assertNotifyAnrWasNotCalled();
4469 }
4470
4471 // When the touch stream is split across 2 windows, and one of them does not respond,
4472 // then ANR should be raised and the touch should be canceled for the unresponsive window.
4473 // The other window should not be affected by that.
TEST_F(InputDispatcherMultiWindowAnr,SplitTouch_SingleWindowAnr)4474 TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4475 // Touch Window 1
4476 NotifyMotionArgs motionArgs =
4477 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4478 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4479 mDispatcher->notifyMotion(&motionArgs);
4480 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4481 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4482
4483 // Touch Window 2
4484 int32_t actionPointerDown =
4485 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4486
4487 motionArgs =
4488 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4489 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4490 mDispatcher->notifyMotion(&motionArgs);
4491
4492 const std::chrono::duration timeout =
4493 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4494 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
4495
4496 mUnfocusedWindow->consumeMotionDown();
4497 mFocusedWindow->consumeMotionDown();
4498 // Focused window may or may not receive ACTION_MOVE
4499 // But it should definitely receive ACTION_CANCEL due to the ANR
4500 InputEvent* event;
4501 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4502 ASSERT_TRUE(moveOrCancelSequenceNum);
4503 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4504 ASSERT_NE(nullptr, event);
4505 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4506 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4507 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4508 mFocusedWindow->consumeMotionCancel();
4509 } else {
4510 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4511 }
4512 ASSERT_TRUE(mDispatcher->waitForIdle());
4513 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
4514
4515 mUnfocusedWindow->assertNoEvents();
4516 mFocusedWindow->assertNoEvents();
4517 mFakePolicy->assertNotifyAnrWasNotCalled();
4518 }
4519
4520 /**
4521 * If we have no focused window, and a key comes in, we start the ANR timer.
4522 * The focused application should add a focused window before the timer runs out to prevent ANR.
4523 *
4524 * If the user touches another application during this time, the key should be dropped.
4525 * Next, if a new focused window comes in, without toggling the focused application,
4526 * then no ANR should occur.
4527 *
4528 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4529 * but in some cases the policy may not update the focused application.
4530 */
TEST_F(InputDispatcherMultiWindowAnr,FocusedWindowWithoutSetFocusedApplication_NoAnr)4531 TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4532 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4533 std::make_shared<FakeApplicationHandle>();
4534 focusedApplication->setDispatchingTimeout(60ms);
4535 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4536 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4537 mFocusedWindow->setFocusable(false);
4538
4539 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4540 mFocusedWindow->consumeFocusEvent(false);
4541
4542 // Send a key. The ANR timer should start because there is no focused window.
4543 // 'focusedApplication' will get blamed if this timer completes.
4544 // Key will not be sent anywhere because we have no focused window. It will remain pending.
4545 InputEventInjectionResult result =
4546 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
4547 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4548 false /* allowKeyRepeat */);
4549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
4550
4551 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4552 // then the injected touches won't cause the focused event to get dropped.
4553 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4554 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4555 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4556 // For this test, it means that the key would get delivered to the window once it becomes
4557 // focused.
4558 std::this_thread::sleep_for(10ms);
4559
4560 // Touch unfocused window. This should force the pending key to get dropped.
4561 NotifyMotionArgs motionArgs =
4562 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4563 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4564 mDispatcher->notifyMotion(&motionArgs);
4565
4566 // We do not consume the motion right away, because that would require dispatcher to first
4567 // process (== drop) the key event, and by that time, ANR will be raised.
4568 // Set the focused window first.
4569 mFocusedWindow->setFocusable(true);
4570 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4571 setFocusedWindow(mFocusedWindow);
4572 mFocusedWindow->consumeFocusEvent(true);
4573 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4574 // to another application. This could be a bug / behaviour in the policy.
4575
4576 mUnfocusedWindow->consumeMotionDown();
4577
4578 ASSERT_TRUE(mDispatcher->waitForIdle());
4579 // Should not ANR because we actually have a focused window. It was just added too slowly.
4580 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4581 }
4582
4583 // These tests ensure we cannot send touch events to a window that's positioned behind a window
4584 // that has feature NO_INPUT_CHANNEL.
4585 // Layout:
4586 // Top (closest to user)
4587 // mNoInputWindow (above all windows)
4588 // mBottomWindow
4589 // Bottom (furthest from user)
4590 class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
SetUp()4591 virtual void SetUp() override {
4592 InputDispatcherTest::SetUp();
4593
4594 mApplication = std::make_shared<FakeApplicationHandle>();
4595 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4596 "Window without input channel", ADISPLAY_ID_DEFAULT,
4597 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4598
4599 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
4600 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4601 // It's perfectly valid for this window to not have an associated input channel
4602
4603 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4604 ADISPLAY_ID_DEFAULT);
4605 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4606
4607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4608 }
4609
4610 protected:
4611 std::shared_ptr<FakeApplicationHandle> mApplication;
4612 sp<FakeWindowHandle> mNoInputWindow;
4613 sp<FakeWindowHandle> mBottomWindow;
4614 };
4615
TEST_F(InputDispatcherMultiWindowOcclusionTests,NoInputChannelFeature_DropsTouches)4616 TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4617 PointF touchedPoint = {10, 10};
4618
4619 NotifyMotionArgs motionArgs =
4620 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4621 ADISPLAY_ID_DEFAULT, {touchedPoint});
4622 mDispatcher->notifyMotion(&motionArgs);
4623
4624 mNoInputWindow->assertNoEvents();
4625 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4626 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4627 // and therefore should prevent mBottomWindow from receiving touches
4628 mBottomWindow->assertNoEvents();
4629 }
4630
4631 /**
4632 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4633 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4634 */
TEST_F(InputDispatcherMultiWindowOcclusionTests,NoInputChannelFeature_DropsTouchesWithValidChannel)4635 TEST_F(InputDispatcherMultiWindowOcclusionTests,
4636 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4637 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4638 "Window with input channel and NO_INPUT_CHANNEL",
4639 ADISPLAY_ID_DEFAULT);
4640
4641 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
4642 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4644
4645 PointF touchedPoint = {10, 10};
4646
4647 NotifyMotionArgs motionArgs =
4648 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4649 ADISPLAY_ID_DEFAULT, {touchedPoint});
4650 mDispatcher->notifyMotion(&motionArgs);
4651
4652 mNoInputWindow->assertNoEvents();
4653 mBottomWindow->assertNoEvents();
4654 }
4655
4656 class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4657 protected:
4658 std::shared_ptr<FakeApplicationHandle> mApp;
4659 sp<FakeWindowHandle> mWindow;
4660 sp<FakeWindowHandle> mMirror;
4661
SetUp()4662 virtual void SetUp() override {
4663 InputDispatcherTest::SetUp();
4664 mApp = std::make_shared<FakeApplicationHandle>();
4665 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4666 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4667 mWindow->getToken());
4668 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4669 mWindow->setFocusable(true);
4670 mMirror->setFocusable(true);
4671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4672 }
4673 };
4674
TEST_F(InputDispatcherMirrorWindowFocusTests,CanGetFocus)4675 TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4676 // Request focus on a mirrored window
4677 setFocusedWindow(mMirror);
4678
4679 // window gets focused
4680 mWindow->consumeFocusEvent(true);
4681 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4682 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4683 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4684 }
4685
4686 // A focused & mirrored window remains focused only if the window and its mirror are both
4687 // focusable.
TEST_F(InputDispatcherMirrorWindowFocusTests,FocusedIfAllWindowsFocusable)4688 TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4689 setFocusedWindow(mMirror);
4690
4691 // window gets focused
4692 mWindow->consumeFocusEvent(true);
4693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4694 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4695 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4696 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4697 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4698 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4699
4700 mMirror->setFocusable(false);
4701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4702
4703 // window loses focus since one of the windows associated with the token in not focusable
4704 mWindow->consumeFocusEvent(false);
4705
4706 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4707 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
4708 mWindow->assertNoEvents();
4709 }
4710
4711 // A focused & mirrored window remains focused until the window and its mirror both become
4712 // invisible.
TEST_F(InputDispatcherMirrorWindowFocusTests,FocusedIfAnyWindowVisible)4713 TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4714 setFocusedWindow(mMirror);
4715
4716 // window gets focused
4717 mWindow->consumeFocusEvent(true);
4718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4719 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4720 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4722 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4723 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4724
4725 mMirror->setVisible(false);
4726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4727
4728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4729 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4730 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4732 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4733 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4734
4735 mWindow->setVisible(false);
4736 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4737
4738 // window loses focus only after all windows associated with the token become invisible.
4739 mWindow->consumeFocusEvent(false);
4740
4741 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4742 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
4743 mWindow->assertNoEvents();
4744 }
4745
4746 // A focused & mirrored window remains focused until both windows are removed.
TEST_F(InputDispatcherMirrorWindowFocusTests,FocusedWhileWindowsAlive)4747 TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4748 setFocusedWindow(mMirror);
4749
4750 // window gets focused
4751 mWindow->consumeFocusEvent(true);
4752 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4753 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4754 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4755 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4756 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4757 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4758
4759 // single window is removed but the window token remains focused
4760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4761
4762 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4763 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4764 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4766 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
4767 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4768
4769 // Both windows are removed
4770 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4771 mWindow->consumeFocusEvent(false);
4772
4773 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4774 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
4775 mWindow->assertNoEvents();
4776 }
4777
4778 // Focus request can be pending until one window becomes visible.
TEST_F(InputDispatcherMirrorWindowFocusTests,DeferFocusWhenInvisible)4779 TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4780 // Request focus on an invisible mirror.
4781 mWindow->setVisible(false);
4782 mMirror->setVisible(false);
4783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4784 setFocusedWindow(mMirror);
4785
4786 // Injected key goes to pending queue.
4787 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4788 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
4789 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
4790
4791 mMirror->setVisible(true);
4792 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4793
4794 // window gets focused
4795 mWindow->consumeFocusEvent(true);
4796 // window gets the pending key event
4797 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4798 }
4799
4800 class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4801 protected:
4802 std::shared_ptr<FakeApplicationHandle> mApp;
4803 sp<FakeWindowHandle> mWindow;
4804 sp<FakeWindowHandle> mSecondWindow;
4805
SetUp()4806 void SetUp() override {
4807 InputDispatcherTest::SetUp();
4808 mApp = std::make_shared<FakeApplicationHandle>();
4809 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4810 mWindow->setFocusable(true);
4811 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4812 mSecondWindow->setFocusable(true);
4813
4814 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4815 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4816
4817 setFocusedWindow(mWindow);
4818 mWindow->consumeFocusEvent(true);
4819 }
4820
notifyPointerCaptureChanged(const PointerCaptureRequest & request)4821 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
4822 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
4823 mDispatcher->notifyPointerCaptureChanged(&args);
4824 }
4825
requestAndVerifyPointerCapture(const sp<FakeWindowHandle> & window,bool enabled)4826 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
4827 bool enabled) {
4828 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4829 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
4830 notifyPointerCaptureChanged(request);
4831 window->consumeCaptureEvent(enabled);
4832 return request;
4833 }
4834 };
4835
TEST_F(InputDispatcherPointerCaptureTests,EnablePointerCaptureWhenFocused)4836 TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4837 // Ensure that capture cannot be obtained for unfocused windows.
4838 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4839 mFakePolicy->assertSetPointerCaptureNotCalled();
4840 mSecondWindow->assertNoEvents();
4841
4842 // Ensure that capture can be enabled from the focus window.
4843 requestAndVerifyPointerCapture(mWindow, true);
4844
4845 // Ensure that capture cannot be disabled from a window that does not have capture.
4846 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4847 mFakePolicy->assertSetPointerCaptureNotCalled();
4848
4849 // Ensure that capture can be disabled from the window with capture.
4850 requestAndVerifyPointerCapture(mWindow, false);
4851 }
4852
TEST_F(InputDispatcherPointerCaptureTests,DisablesPointerCaptureAfterWindowLosesFocus)4853 TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4854 auto request = requestAndVerifyPointerCapture(mWindow, true);
4855
4856 setFocusedWindow(mSecondWindow);
4857
4858 // Ensure that the capture disabled event was sent first.
4859 mWindow->consumeCaptureEvent(false);
4860 mWindow->consumeFocusEvent(false);
4861 mSecondWindow->consumeFocusEvent(true);
4862 mFakePolicy->assertSetPointerCaptureCalled(false);
4863
4864 // Ensure that additional state changes from InputReader are not sent to the window.
4865 notifyPointerCaptureChanged({});
4866 notifyPointerCaptureChanged(request);
4867 notifyPointerCaptureChanged({});
4868 mWindow->assertNoEvents();
4869 mSecondWindow->assertNoEvents();
4870 mFakePolicy->assertSetPointerCaptureNotCalled();
4871 }
4872
TEST_F(InputDispatcherPointerCaptureTests,UnexpectedStateChangeDisablesPointerCapture)4873 TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4874 auto request = requestAndVerifyPointerCapture(mWindow, true);
4875
4876 // InputReader unexpectedly disables and enables pointer capture.
4877 notifyPointerCaptureChanged({});
4878 notifyPointerCaptureChanged(request);
4879
4880 // Ensure that Pointer Capture is disabled.
4881 mFakePolicy->assertSetPointerCaptureCalled(false);
4882 mWindow->consumeCaptureEvent(false);
4883 mWindow->assertNoEvents();
4884 }
4885
TEST_F(InputDispatcherPointerCaptureTests,OutOfOrderRequests)4886 TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4887 requestAndVerifyPointerCapture(mWindow, true);
4888
4889 // The first window loses focus.
4890 setFocusedWindow(mSecondWindow);
4891 mFakePolicy->assertSetPointerCaptureCalled(false);
4892 mWindow->consumeCaptureEvent(false);
4893
4894 // Request Pointer Capture from the second window before the notification from InputReader
4895 // arrives.
4896 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4897 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
4898
4899 // InputReader notifies Pointer Capture was disabled (because of the focus change).
4900 notifyPointerCaptureChanged({});
4901
4902 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
4903 notifyPointerCaptureChanged(request);
4904
4905 mSecondWindow->consumeFocusEvent(true);
4906 mSecondWindow->consumeCaptureEvent(true);
4907 }
4908
TEST_F(InputDispatcherPointerCaptureTests,EnableRequestFollowsSequenceNumbers)4909 TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
4910 // App repeatedly enables and disables capture.
4911 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
4912 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
4913 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
4914 mFakePolicy->assertSetPointerCaptureCalled(false);
4915 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
4916 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
4917
4918 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
4919 // first request is now stale, this should do nothing.
4920 notifyPointerCaptureChanged(firstRequest);
4921 mWindow->assertNoEvents();
4922
4923 // InputReader notifies that the second request was enabled.
4924 notifyPointerCaptureChanged(secondRequest);
4925 mWindow->consumeCaptureEvent(true);
4926 }
4927
4928 class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4929 protected:
4930 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
4931
4932 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4933 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4934
4935 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4936 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4937
4938 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4939 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4940 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4941 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4942 MAXIMUM_OBSCURING_OPACITY);
4943
4944 static const int32_t TOUCHED_APP_UID = 10001;
4945 static const int32_t APP_B_UID = 10002;
4946 static const int32_t APP_C_UID = 10003;
4947
4948 sp<FakeWindowHandle> mTouchWindow;
4949
SetUp()4950 virtual void SetUp() override {
4951 InputDispatcherTest::SetUp();
4952 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
4953 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4954 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4955 }
4956
TearDown()4957 virtual void TearDown() override {
4958 InputDispatcherTest::TearDown();
4959 mTouchWindow.clear();
4960 }
4961
getOccludingWindow(int32_t uid,std::string name,TouchOcclusionMode mode,float alpha=1.0f)4962 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
4963 float alpha = 1.0f) {
4964 sp<FakeWindowHandle> window = getWindow(uid, name);
4965 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
4966 window->setTouchOcclusionMode(mode);
4967 window->setAlpha(alpha);
4968 return window;
4969 }
4970
getWindow(int32_t uid,std::string name)4971 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4972 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4973 sp<FakeWindowHandle> window =
4974 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4975 // Generate an arbitrary PID based on the UID
4976 window->setOwnerInfo(1777 + (uid % 10000), uid);
4977 return window;
4978 }
4979
touch(const std::vector<PointF> & points={PointF{100, 200}})4980 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4981 NotifyMotionArgs args =
4982 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4983 ADISPLAY_ID_DEFAULT, points);
4984 mDispatcher->notifyMotion(&args);
4985 }
4986 };
4987
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithBlockUntrustedOcclusionMode_BlocksTouch)4988 TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
4989 const sp<FakeWindowHandle>& w =
4990 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4991 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4992
4993 touch();
4994
4995 mTouchWindow->assertNoEvents();
4996 }
4997
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch)4998 TEST_F(InputDispatcherUntrustedTouchesTest,
4999 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5000 const sp<FakeWindowHandle>& w =
5001 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5003
5004 touch();
5005
5006 mTouchWindow->assertNoEvents();
5007 }
5008
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch)5009 TEST_F(InputDispatcherUntrustedTouchesTest,
5010 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5011 const sp<FakeWindowHandle>& w =
5012 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5013 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5014
5015 touch();
5016
5017 w->assertNoEvents();
5018 }
5019
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithAllowOcclusionMode_AllowsTouch)5020 TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
5021 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5023
5024 touch();
5025
5026 mTouchWindow->consumeAnyMotionDown();
5027 }
5028
TEST_F(InputDispatcherUntrustedTouchesTest,TouchOutsideOccludingWindow_AllowsTouch)5029 TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
5030 const sp<FakeWindowHandle>& w =
5031 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5032 w->setFrame(Rect(0, 0, 50, 50));
5033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5034
5035 touch({PointF{100, 100}});
5036
5037 mTouchWindow->consumeAnyMotionDown();
5038 }
5039
TEST_F(InputDispatcherUntrustedTouchesTest,WindowFromSameUid_AllowsTouch)5040 TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
5041 const sp<FakeWindowHandle>& w =
5042 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
5043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5044
5045 touch();
5046
5047 mTouchWindow->consumeAnyMotionDown();
5048 }
5049
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithZeroOpacity_AllowsTouch)5050 TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5051 const sp<FakeWindowHandle>& w =
5052 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5054
5055 touch();
5056
5057 mTouchWindow->consumeAnyMotionDown();
5058 }
5059
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithZeroOpacity_DoesNotReceiveTouch)5060 TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5061 const sp<FakeWindowHandle>& w =
5062 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5064
5065 touch();
5066
5067 w->assertNoEvents();
5068 }
5069
5070 /**
5071 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5072 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5073 * window, the occluding window will still receive ACTION_OUTSIDE event.
5074 */
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent)5075 TEST_F(InputDispatcherUntrustedTouchesTest,
5076 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5077 const sp<FakeWindowHandle>& w =
5078 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5079 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
5080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5081
5082 touch();
5083
5084 w->consumeMotionOutside();
5085 }
5086
TEST_F(InputDispatcherUntrustedTouchesTest,OutsideEvent_HasZeroCoordinates)5087 TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5088 const sp<FakeWindowHandle>& w =
5089 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5090 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
5091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5092
5093 touch();
5094
5095 InputEvent* event = w->consume();
5096 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5097 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5098 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5099 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5100 }
5101
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithOpacityBelowThreshold_AllowsTouch)5102 TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
5103 const sp<FakeWindowHandle>& w =
5104 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5105 OPACITY_BELOW_THRESHOLD);
5106 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5107
5108 touch();
5109
5110 mTouchWindow->consumeAnyMotionDown();
5111 }
5112
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithOpacityAtThreshold_AllowsTouch)5113 TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5114 const sp<FakeWindowHandle>& w =
5115 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5116 MAXIMUM_OBSCURING_OPACITY);
5117 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5118
5119 touch();
5120
5121 mTouchWindow->consumeAnyMotionDown();
5122 }
5123
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithOpacityAboveThreshold_BlocksTouch)5124 TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
5125 const sp<FakeWindowHandle>& w =
5126 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5127 OPACITY_ABOVE_THRESHOLD);
5128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5129
5130 touch();
5131
5132 mTouchWindow->assertNoEvents();
5133 }
5134
TEST_F(InputDispatcherUntrustedTouchesTest,WindowsWithCombinedOpacityAboveThreshold_BlocksTouch)5135 TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5136 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5137 const sp<FakeWindowHandle>& w1 =
5138 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5139 OPACITY_BELOW_THRESHOLD);
5140 const sp<FakeWindowHandle>& w2 =
5141 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5142 OPACITY_BELOW_THRESHOLD);
5143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5144
5145 touch();
5146
5147 mTouchWindow->assertNoEvents();
5148 }
5149
TEST_F(InputDispatcherUntrustedTouchesTest,WindowsWithCombinedOpacityBelowThreshold_AllowsTouch)5150 TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5151 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5152 const sp<FakeWindowHandle>& w1 =
5153 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5154 OPACITY_FAR_BELOW_THRESHOLD);
5155 const sp<FakeWindowHandle>& w2 =
5156 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5157 OPACITY_FAR_BELOW_THRESHOLD);
5158 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5159
5160 touch();
5161
5162 mTouchWindow->consumeAnyMotionDown();
5163 }
5164
TEST_F(InputDispatcherUntrustedTouchesTest,WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch)5165 TEST_F(InputDispatcherUntrustedTouchesTest,
5166 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5167 const sp<FakeWindowHandle>& wB =
5168 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5169 OPACITY_BELOW_THRESHOLD);
5170 const sp<FakeWindowHandle>& wC =
5171 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5172 OPACITY_BELOW_THRESHOLD);
5173 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5174
5175 touch();
5176
5177 mTouchWindow->consumeAnyMotionDown();
5178 }
5179
TEST_F(InputDispatcherUntrustedTouchesTest,WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch)5180 TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5181 const sp<FakeWindowHandle>& wB =
5182 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5183 OPACITY_BELOW_THRESHOLD);
5184 const sp<FakeWindowHandle>& wC =
5185 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5186 OPACITY_ABOVE_THRESHOLD);
5187 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5188
5189 touch();
5190
5191 mTouchWindow->assertNoEvents();
5192 }
5193
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch)5194 TEST_F(InputDispatcherUntrustedTouchesTest,
5195 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5196 const sp<FakeWindowHandle>& wA =
5197 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5198 OPACITY_BELOW_THRESHOLD);
5199 const sp<FakeWindowHandle>& wB =
5200 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5201 OPACITY_ABOVE_THRESHOLD);
5202 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5203
5204 touch();
5205
5206 mTouchWindow->assertNoEvents();
5207 }
5208
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch)5209 TEST_F(InputDispatcherUntrustedTouchesTest,
5210 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5211 const sp<FakeWindowHandle>& wA =
5212 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5213 OPACITY_ABOVE_THRESHOLD);
5214 const sp<FakeWindowHandle>& wB =
5215 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5216 OPACITY_BELOW_THRESHOLD);
5217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5218
5219 touch();
5220
5221 mTouchWindow->consumeAnyMotionDown();
5222 }
5223
TEST_F(InputDispatcherUntrustedTouchesTest,SelfWindowWithOpacityAboveThreshold_AllowsTouch)5224 TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5225 const sp<FakeWindowHandle>& w =
5226 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5227 OPACITY_ABOVE_THRESHOLD);
5228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5229
5230 touch();
5231
5232 mTouchWindow->consumeAnyMotionDown();
5233 }
5234
TEST_F(InputDispatcherUntrustedTouchesTest,SelfWindowWithBlockUntrustedMode_AllowsTouch)5235 TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5236 const sp<FakeWindowHandle>& w =
5237 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5239
5240 touch();
5241
5242 mTouchWindow->consumeAnyMotionDown();
5243 }
5244
TEST_F(InputDispatcherUntrustedTouchesTest,OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch)5245 TEST_F(InputDispatcherUntrustedTouchesTest,
5246 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5247 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5248 const sp<FakeWindowHandle>& w =
5249 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5251
5252 touch();
5253
5254 mTouchWindow->assertNoEvents();
5255 }
5256
TEST_F(InputDispatcherUntrustedTouchesTest,OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch)5257 TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5258 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5259 const sp<FakeWindowHandle>& w =
5260 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5261 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5262
5263 touch();
5264
5265 mTouchWindow->consumeAnyMotionDown();
5266 }
5267
TEST_F(InputDispatcherUntrustedTouchesTest,OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch)5268 TEST_F(InputDispatcherUntrustedTouchesTest,
5269 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5270 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5271 const sp<FakeWindowHandle>& w =
5272 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5273 OPACITY_ABOVE_THRESHOLD);
5274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5275
5276 touch();
5277
5278 mTouchWindow->consumeAnyMotionDown();
5279 }
5280
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch)5281 TEST_F(InputDispatcherUntrustedTouchesTest,
5282 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5283 const sp<FakeWindowHandle>& w1 =
5284 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5285 OPACITY_BELOW_THRESHOLD);
5286 const sp<FakeWindowHandle>& w2 =
5287 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5288 OPACITY_BELOW_THRESHOLD);
5289 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5290
5291 touch();
5292
5293 mTouchWindow->assertNoEvents();
5294 }
5295
5296 /**
5297 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5298 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5299 * (which alone would result in allowing touches) does not affect the blocking behavior.
5300 */
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch)5301 TEST_F(InputDispatcherUntrustedTouchesTest,
5302 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5303 const sp<FakeWindowHandle>& wB =
5304 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5305 OPACITY_BELOW_THRESHOLD);
5306 const sp<FakeWindowHandle>& wC =
5307 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5308 OPACITY_BELOW_THRESHOLD);
5309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5310
5311 touch();
5312
5313 mTouchWindow->assertNoEvents();
5314 }
5315
5316 /**
5317 * This test is testing that a window from a different UID but with same application token doesn't
5318 * block the touch. Apps can share the application token for close UI collaboration for example.
5319 */
TEST_F(InputDispatcherUntrustedTouchesTest,WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch)5320 TEST_F(InputDispatcherUntrustedTouchesTest,
5321 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5322 const sp<FakeWindowHandle>& w =
5323 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5324 w->setApplicationToken(mTouchWindow->getApplicationToken());
5325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5326
5327 touch();
5328
5329 mTouchWindow->consumeAnyMotionDown();
5330 }
5331
5332 class InputDispatcherDragTests : public InputDispatcherTest {
5333 protected:
5334 std::shared_ptr<FakeApplicationHandle> mApp;
5335 sp<FakeWindowHandle> mWindow;
5336 sp<FakeWindowHandle> mSecondWindow;
5337 sp<FakeWindowHandle> mDragWindow;
5338
SetUp()5339 void SetUp() override {
5340 InputDispatcherTest::SetUp();
5341 mApp = std::make_shared<FakeApplicationHandle>();
5342 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5343 mWindow->setFrame(Rect(0, 0, 100, 100));
5344 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
5345
5346 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5347 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
5348 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
5349
5350 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5351 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5352 }
5353
5354 // Start performing drag, we will create a drag window and transfer touch to it.
performDrag()5355 void performDrag() {
5356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5357 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5358 {50, 50}))
5359 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5360
5361 // Window should receive motion event.
5362 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5363
5364 // The drag window covers the entire display
5365 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5366 mDispatcher->setInputWindows(
5367 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5368
5369 // Transfer touch focus to the drag window
5370 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5371 true /* isDragDrop */);
5372 mWindow->consumeMotionCancel();
5373 mDragWindow->consumeMotionDown();
5374 }
5375
5376 // Start performing drag, we will create a drag window and transfer touch to it.
performStylusDrag()5377 void performStylusDrag() {
5378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5379 injectMotionEvent(mDispatcher,
5380 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5381 AINPUT_SOURCE_STYLUS)
5382 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5383 .pointer(PointerBuilder(0,
5384 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5385 .x(50)
5386 .y(50))
5387 .build()));
5388 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5389
5390 // The drag window covers the entire display
5391 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5392 mDispatcher->setInputWindows(
5393 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5394
5395 // Transfer touch focus to the drag window
5396 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5397 true /* isDragDrop */);
5398 mWindow->consumeMotionCancel();
5399 mDragWindow->consumeMotionDown();
5400 }
5401 };
5402
TEST_F(InputDispatcherDragTests,DragEnterAndDragExit)5403 TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5404 performDrag();
5405
5406 // Move on window.
5407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5408 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5409 ADISPLAY_ID_DEFAULT, {50, 50}))
5410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5411 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5412 mWindow->consumeDragEvent(false, 50, 50);
5413 mSecondWindow->assertNoEvents();
5414
5415 // Move to another window.
5416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5417 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5418 ADISPLAY_ID_DEFAULT, {150, 50}))
5419 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5420 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5421 mWindow->consumeDragEvent(true, 150, 50);
5422 mSecondWindow->consumeDragEvent(false, 50, 50);
5423
5424 // Move back to original window.
5425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5426 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5427 ADISPLAY_ID_DEFAULT, {50, 50}))
5428 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5429 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5430 mWindow->consumeDragEvent(false, 50, 50);
5431 mSecondWindow->consumeDragEvent(true, -50, 50);
5432
5433 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5434 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5435 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5436 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5437 mWindow->assertNoEvents();
5438 mSecondWindow->assertNoEvents();
5439 }
5440
TEST_F(InputDispatcherDragTests,DragAndDrop)5441 TEST_F(InputDispatcherDragTests, DragAndDrop) {
5442 performDrag();
5443
5444 // Move on window.
5445 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5446 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5447 ADISPLAY_ID_DEFAULT, {50, 50}))
5448 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5449 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5450 mWindow->consumeDragEvent(false, 50, 50);
5451 mSecondWindow->assertNoEvents();
5452
5453 // Move to another window.
5454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5455 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5456 ADISPLAY_ID_DEFAULT, {150, 50}))
5457 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5458 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5459 mWindow->consumeDragEvent(true, 150, 50);
5460 mSecondWindow->consumeDragEvent(false, 50, 50);
5461
5462 // drop to another window.
5463 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5464 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5465 {150, 50}))
5466 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5467 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5468 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5469 mWindow->assertNoEvents();
5470 mSecondWindow->assertNoEvents();
5471 }
5472
TEST_F(InputDispatcherDragTests,StylusDragAndDrop)5473 TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5474 performStylusDrag();
5475
5476 // Move on window and keep button pressed.
5477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5478 injectMotionEvent(mDispatcher,
5479 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5480 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5481 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5482 .x(50)
5483 .y(50))
5484 .build()))
5485 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5486 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5487 mWindow->consumeDragEvent(false, 50, 50);
5488 mSecondWindow->assertNoEvents();
5489
5490 // Move to another window and release button, expect to drop item.
5491 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5492 injectMotionEvent(mDispatcher,
5493 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5494 .buttonState(0)
5495 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5496 .x(150)
5497 .y(50))
5498 .build()))
5499 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5500 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5501 mWindow->assertNoEvents();
5502 mSecondWindow->assertNoEvents();
5503 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5504
5505 // nothing to the window.
5506 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5507 injectMotionEvent(mDispatcher,
5508 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5509 .buttonState(0)
5510 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5511 .x(150)
5512 .y(50))
5513 .build()))
5514 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5515 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5516 mWindow->assertNoEvents();
5517 mSecondWindow->assertNoEvents();
5518 }
5519
TEST_F(InputDispatcherDragTests,DragAndDrop_InvalidWindow)5520 TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5521 performDrag();
5522
5523 // Set second window invisible.
5524 mSecondWindow->setVisible(false);
5525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5526
5527 // Move on window.
5528 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5529 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5530 ADISPLAY_ID_DEFAULT, {50, 50}))
5531 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5532 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5533 mWindow->consumeDragEvent(false, 50, 50);
5534 mSecondWindow->assertNoEvents();
5535
5536 // Move to another window.
5537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5538 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5539 ADISPLAY_ID_DEFAULT, {150, 50}))
5540 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5541 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5542 mWindow->consumeDragEvent(true, 150, 50);
5543 mSecondWindow->assertNoEvents();
5544
5545 // drop to another window.
5546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5547 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5548 {150, 50}))
5549 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5550 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5551 mFakePolicy->assertDropTargetEquals(nullptr);
5552 mWindow->assertNoEvents();
5553 mSecondWindow->assertNoEvents();
5554 }
5555
5556 class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5557
TEST_F(InputDispatcherDropInputFeatureTest,WindowDropsInput)5558 TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5559 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5560 sp<FakeWindowHandle> window =
5561 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5562 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5563 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5564 window->setFocusable(true);
5565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5566 setFocusedWindow(window);
5567 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5568
5569 // With the flag set, window should not get any input
5570 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5571 mDispatcher->notifyKey(&keyArgs);
5572 window->assertNoEvents();
5573
5574 NotifyMotionArgs motionArgs =
5575 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5576 ADISPLAY_ID_DEFAULT);
5577 mDispatcher->notifyMotion(&motionArgs);
5578 window->assertNoEvents();
5579
5580 // With the flag cleared, the window should get input
5581 window->setInputFeatures({});
5582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5583
5584 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5585 mDispatcher->notifyKey(&keyArgs);
5586 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5587
5588 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5589 ADISPLAY_ID_DEFAULT);
5590 mDispatcher->notifyMotion(&motionArgs);
5591 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5592 window->assertNoEvents();
5593 }
5594
TEST_F(InputDispatcherDropInputFeatureTest,ObscuredWindowDropsInput)5595 TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5596 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5597 std::make_shared<FakeApplicationHandle>();
5598 sp<FakeWindowHandle> obscuringWindow =
5599 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5600 ADISPLAY_ID_DEFAULT);
5601 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5602 obscuringWindow->setOwnerInfo(111, 111);
5603 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5604 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5605 sp<FakeWindowHandle> window =
5606 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5607 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5608 window->setOwnerInfo(222, 222);
5609 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5610 window->setFocusable(true);
5611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5612 setFocusedWindow(window);
5613 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5614
5615 // With the flag set, window should not get any input
5616 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5617 mDispatcher->notifyKey(&keyArgs);
5618 window->assertNoEvents();
5619
5620 NotifyMotionArgs motionArgs =
5621 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5622 ADISPLAY_ID_DEFAULT);
5623 mDispatcher->notifyMotion(&motionArgs);
5624 window->assertNoEvents();
5625
5626 // With the flag cleared, the window should get input
5627 window->setInputFeatures({});
5628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5629
5630 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5631 mDispatcher->notifyKey(&keyArgs);
5632 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5633
5634 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5635 ADISPLAY_ID_DEFAULT);
5636 mDispatcher->notifyMotion(&motionArgs);
5637 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5638 window->assertNoEvents();
5639 }
5640
TEST_F(InputDispatcherDropInputFeatureTest,UnobscuredWindowGetsInput)5641 TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
5642 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5643 std::make_shared<FakeApplicationHandle>();
5644 sp<FakeWindowHandle> obscuringWindow =
5645 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5646 ADISPLAY_ID_DEFAULT);
5647 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5648 obscuringWindow->setOwnerInfo(111, 111);
5649 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5650 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5651 sp<FakeWindowHandle> window =
5652 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5653 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5654 window->setOwnerInfo(222, 222);
5655 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5656 window->setFocusable(true);
5657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5658 setFocusedWindow(window);
5659 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5660
5661 // With the flag set, window should not get any input
5662 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5663 mDispatcher->notifyKey(&keyArgs);
5664 window->assertNoEvents();
5665
5666 NotifyMotionArgs motionArgs =
5667 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5668 ADISPLAY_ID_DEFAULT);
5669 mDispatcher->notifyMotion(&motionArgs);
5670 window->assertNoEvents();
5671
5672 // When the window is no longer obscured because it went on top, it should get input
5673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
5674
5675 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5676 mDispatcher->notifyKey(&keyArgs);
5677 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5678
5679 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5680 ADISPLAY_ID_DEFAULT);
5681 mDispatcher->notifyMotion(&motionArgs);
5682 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5683 window->assertNoEvents();
5684 }
5685
5686 } // namespace android::inputdispatcher
5687