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