blob: 7c4bf7797afbd33d8d129917fe8e81f46251056c [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
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
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Garfield Tan1c7bc862020-01-28 13:24:04 -080019#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070020#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070021#include <binder/Binder.h>
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -080022#include <input/Input.h>
Robert Carr803535b2018-08-02 16:38:15 -070023
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <gtest/gtest.h>
25#include <linux/input.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080026#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070027#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080028#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080029#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080030
Garfield Tan1c7bc862020-01-28 13:24:04 -080031using android::base::StringPrintf;
Michael Wright44753b12020-07-08 13:48:11 +010032using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080033
Garfield Tane84e6f92019-08-29 17:28:41 -070034namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080035
36// An arbitrary time value.
37static const nsecs_t ARBITRARY_TIME = 1234;
38
39// An arbitrary device id.
40static const int32_t DEVICE_ID = 1;
41
Jeff Brownf086ddb2014-02-11 14:28:48 -080042// An arbitrary display id.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -080043static const int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
Jeff Brownf086ddb2014-02-11 14:28:48 -080044
Michael Wrightd02c5b62014-02-10 15:10:22 -080045// An arbitrary injector pid / uid pair that has permission to inject events.
46static const int32_t INJECTOR_PID = 999;
47static const int32_t INJECTOR_UID = 1001;
48
chaviwd1c23182019-12-20 18:44:56 -080049struct PointF {
50 float x;
51 float y;
52};
Michael Wrightd02c5b62014-02-10 15:10:22 -080053
Gang Wang342c9272020-01-13 13:15:04 -050054/**
55 * Return a DOWN key event with KEYCODE_A.
56 */
57static KeyEvent getTestKeyEvent() {
58 KeyEvent event;
59
Garfield Tanfbe732e2020-01-24 11:26:14 -080060 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
61 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
62 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050063 return event;
64}
65
Michael Wrightd02c5b62014-02-10 15:10:22 -080066// --- FakeInputDispatcherPolicy ---
67
68class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
69 InputDispatcherConfiguration mConfig;
70
71protected:
72 virtual ~FakeInputDispatcherPolicy() {
73 }
74
75public:
76 FakeInputDispatcherPolicy() {
Jackal Guof9696682018-10-05 12:23:23 +080077 }
78
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080079 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080080 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
81 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080082 }
83
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080084 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080085 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
86 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080087 }
88
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070089 void assertFilterInputEventWasNotCalled() {
90 std::scoped_lock lock(mLock);
91 ASSERT_EQ(nullptr, mFilteredEvent);
92 }
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080094 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070095 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080096 ASSERT_TRUE(mConfigurationChangedTime)
97 << "Timed out waiting for configuration changed call";
98 ASSERT_EQ(*mConfigurationChangedTime, when);
99 mConfigurationChangedTime = std::nullopt;
100 }
101
102 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700103 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800104 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800105 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800106 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
107 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
108 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
109 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
110 mLastNotifySwitch = std::nullopt;
111 }
112
chaviwfd6d3512019-03-25 13:23:49 -0700113 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700114 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800115 ASSERT_EQ(touchedToken, mOnPointerDownToken);
116 mOnPointerDownToken.clear();
117 }
118
119 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700120 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800121 ASSERT_TRUE(mOnPointerDownToken == nullptr)
122 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700123 }
124
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700125 // This function must be called soon after the expected ANR timer starts,
126 // because we are also checking how much time has passed.
Chris Yea209fde2020-07-22 13:54:51 -0700127 void assertNotifyAnrWasCalled(
128 std::chrono::nanoseconds timeout,
129 const std::shared_ptr<InputApplicationHandle>& expectedApplication,
130 const sp<IBinder>& expectedToken) {
131 std::pair<std::shared_ptr<InputApplicationHandle>, sp<IBinder>> anrData;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700132 ASSERT_NO_FATAL_FAILURE(anrData = getNotifyAnrData(timeout));
133 ASSERT_EQ(expectedApplication, anrData.first);
134 ASSERT_EQ(expectedToken, anrData.second);
135 }
136
Chris Yea209fde2020-07-22 13:54:51 -0700137 std::pair<std::shared_ptr<InputApplicationHandle>, sp<IBinder>> getNotifyAnrData(
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700138 std::chrono::nanoseconds timeout) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700139 const std::chrono::time_point start = std::chrono::steady_clock::now();
140 std::unique_lock lock(mLock);
141 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
142 android::base::ScopedLockAssertion assumeLocked(mLock);
143
144 // If there is an ANR, Dispatcher won't be idle because there are still events
145 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
146 // before checking if ANR was called.
147 // Since dispatcher is not guaranteed to call notifyAnr right away, we need to provide
148 // it some time to act. 100ms seems reasonable.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700149 mNotifyAnr.wait_for(lock, timeToWait, [this]() REQUIRES(mLock) {
150 return !mAnrApplications.empty() && !mAnrWindowTokens.empty();
151 });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700152 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700153 if (mAnrApplications.empty() || mAnrWindowTokens.empty()) {
154 ADD_FAILURE() << "Did not receive ANR callback";
155 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700156 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
157 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700158 if (std::chrono::abs(timeout - waited) > 100ms) {
159 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
160 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
161 << "ms, but waited "
162 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
163 << "ms instead";
164 }
Chris Yea209fde2020-07-22 13:54:51 -0700165 std::pair<std::shared_ptr<InputApplicationHandle>, sp<IBinder>> result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700166 std::make_pair(mAnrApplications.front(), mAnrWindowTokens.front());
167 mAnrApplications.pop();
168 mAnrWindowTokens.pop();
169 return result;
170 }
171
172 void assertNotifyAnrWasNotCalled() {
173 std::scoped_lock lock(mLock);
174 ASSERT_TRUE(mAnrApplications.empty());
175 ASSERT_TRUE(mAnrWindowTokens.empty());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700176 }
177
Garfield Tan1c7bc862020-01-28 13:24:04 -0800178 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
179 mConfig.keyRepeatTimeout = timeout;
180 mConfig.keyRepeatDelay = delay;
181 }
182
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700183 void setAnrTimeout(std::chrono::nanoseconds timeout) { mAnrTimeout = timeout; }
184
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700186 std::mutex mLock;
187 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
188 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
189 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
190 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800191
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700192 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700193 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700194 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700195 std::condition_variable mNotifyAnr;
196 std::chrono::nanoseconds mAnrTimeout = 0ms;
197
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800198 virtual void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700199 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800200 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800201 }
202
Chris Yea209fde2020-07-22 13:54:51 -0700203 std::chrono::nanoseconds notifyAnr(const std::shared_ptr<InputApplicationHandle>& application,
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500204 const sp<IBinder>& windowToken,
205 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700206 std::scoped_lock lock(mLock);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700207 mAnrApplications.push(application);
208 mAnrWindowTokens.push(windowToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700209 mNotifyAnr.notify_all();
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500210 return mAnrTimeout;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800211 }
212
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700213 virtual void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700215 virtual void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700216
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700217 virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800218 *outConfig = mConfig;
219 }
220
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800221 virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700222 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800223 switch (inputEvent->getType()) {
224 case AINPUT_EVENT_TYPE_KEY: {
225 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800226 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800227 break;
228 }
229
230 case AINPUT_EVENT_TYPE_MOTION: {
231 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800232 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800233 break;
234 }
235 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800236 return true;
237 }
238
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700239 virtual void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700241 virtual void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700243 virtual nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*,
244 uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245 return 0;
246 }
247
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700248 virtual bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t,
249 KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 return false;
251 }
252
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800253 virtual void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
254 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700255 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800256 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
257 * essentially a passthrough for notifySwitch.
258 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800259 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260 }
261
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700262 virtual void pokeUserActivity(nsecs_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800263
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700264 virtual bool checkInjectEventsPermissionNonReentrant(int32_t, int32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265 return false;
266 }
Jackal Guof9696682018-10-05 12:23:23 +0800267
Siarhei Vishniakoub1a16272020-05-06 16:09:19 -0700268 virtual void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700269 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700270 mOnPointerDownToken = newToken;
271 }
272
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800273 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
274 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700275 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800276 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
277 ASSERT_EQ(mFilteredEvent->getType(), type);
278
279 if (type == AINPUT_EVENT_TYPE_KEY) {
280 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
281 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
282 EXPECT_EQ(keyEvent.getAction(), action);
283 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
284 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
285 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
286 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
287 EXPECT_EQ(motionEvent.getAction(), action);
288 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
289 } else {
290 FAIL() << "Unknown type: " << type;
291 }
292
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800293 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800294 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295};
296
Gang Wang342c9272020-01-13 13:15:04 -0500297// --- HmacKeyManagerTest ---
298
299class HmacKeyManagerTest : public testing::Test {
300protected:
301 HmacKeyManager mHmacKeyManager;
302};
303
304/**
305 * Ensure that separate calls to sign the same data are generating the same key.
306 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
307 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
308 * tests.
309 */
310TEST_F(HmacKeyManagerTest, GeneratedHmac_IsConsistent) {
311 KeyEvent event = getTestKeyEvent();
312 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
313
314 std::array<uint8_t, 32> hmac1 = mHmacKeyManager.sign(verifiedEvent);
315 std::array<uint8_t, 32> hmac2 = mHmacKeyManager.sign(verifiedEvent);
316 ASSERT_EQ(hmac1, hmac2);
317}
318
319/**
320 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
321 */
322TEST_F(HmacKeyManagerTest, GeneratedHmac_ChangesWhenFieldsChange) {
323 KeyEvent event = getTestKeyEvent();
324 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
325 std::array<uint8_t, 32> initialHmac = mHmacKeyManager.sign(verifiedEvent);
326
327 verifiedEvent.deviceId += 1;
328 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
329
330 verifiedEvent.source += 1;
331 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
332
333 verifiedEvent.eventTimeNanos += 1;
334 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
335
336 verifiedEvent.displayId += 1;
337 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
338
339 verifiedEvent.action += 1;
340 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
341
342 verifiedEvent.downTimeNanos += 1;
343 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
344
345 verifiedEvent.flags += 1;
346 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
347
348 verifiedEvent.keyCode += 1;
349 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
350
351 verifiedEvent.scanCode += 1;
352 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
353
354 verifiedEvent.metaState += 1;
355 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
356
357 verifiedEvent.repeatCount += 1;
358 ASSERT_NE(initialHmac, mHmacKeyManager.sign(verifiedEvent));
359}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360
361// --- InputDispatcherTest ---
362
363class InputDispatcherTest : public testing::Test {
364protected:
365 sp<FakeInputDispatcherPolicy> mFakePolicy;
366 sp<InputDispatcher> mDispatcher;
367
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700368 virtual void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800369 mFakePolicy = new FakeInputDispatcherPolicy();
370 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800371 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
372 //Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700373 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800374 }
375
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700376 virtual void TearDown() override {
377 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378 mFakePolicy.clear();
379 mDispatcher.clear();
380 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700381
382 /**
383 * Used for debugging when writing the test
384 */
385 void dumpDispatcherState() {
386 std::string dump;
387 mDispatcher->dump(dump);
388 std::stringstream ss(dump);
389 std::string to;
390
391 while (std::getline(ss, to, '\n')) {
392 ALOGE("%s", to.c_str());
393 }
394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395};
396
397
398TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
399 KeyEvent event;
400
401 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800402 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
403 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600404 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
405 ARBITRARY_TIME);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700406 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
407 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
408 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 << "Should reject key events with undefined action.";
410
411 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800412 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
413 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600414 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700415 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
416 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
417 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 << "Should reject key events with ACTION_MULTIPLE.";
419}
420
421TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
422 MotionEvent event;
423 PointerProperties pointerProperties[MAX_POINTERS + 1];
424 PointerCoords pointerCoords[MAX_POINTERS + 1];
425 for (int i = 0; i <= MAX_POINTERS; i++) {
426 pointerProperties[i].clear();
427 pointerProperties[i].id = i;
428 pointerCoords[i].clear();
429 }
430
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800431 // Some constants commonly used below
432 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
433 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
434 constexpr int32_t metaState = AMETA_NONE;
435 constexpr MotionClassification classification = MotionClassification::NONE;
436
chaviw9eaa22c2020-07-01 16:21:27 -0700437 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800439 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700440 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
441 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600442 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700443 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700444 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
445 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
446 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 << "Should reject motion events with undefined action.";
448
449 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800450 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700451 AMOTION_EVENT_ACTION_POINTER_DOWN |
452 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700453 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
454 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
455 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
456 pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700457 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
458 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
459 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460 << "Should reject motion events with pointer down index too large.";
461
Garfield Tanfbe732e2020-01-24 11:26:14 -0800462 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700463 AMOTION_EVENT_ACTION_POINTER_DOWN |
464 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700465 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
466 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
467 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
468 pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700469 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
470 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
471 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 << "Should reject motion events with pointer down index too small.";
473
474 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800475 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700476 AMOTION_EVENT_ACTION_POINTER_UP |
477 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700478 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
479 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
480 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
481 pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700482 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
483 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
484 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485 << "Should reject motion events with pointer up index too large.";
486
Garfield Tanfbe732e2020-01-24 11:26:14 -0800487 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700488 AMOTION_EVENT_ACTION_POINTER_UP |
489 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700490 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
491 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
492 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
493 pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700494 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
495 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
496 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 << "Should reject motion events with pointer up index too small.";
498
499 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800500 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
501 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700502 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
503 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700504 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700505 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
506 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
507 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800508 << "Should reject motion events with 0 pointers.";
509
Garfield Tanfbe732e2020-01-24 11:26:14 -0800510 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
511 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700512 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
513 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700514 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700515 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
516 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
517 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 << "Should reject motion events with more than MAX_POINTERS pointers.";
519
520 // Rejects motion events with invalid pointer ids.
521 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800522 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
523 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700524 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
525 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700526 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700527 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
528 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
529 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 << "Should reject motion events with pointer ids less than 0.";
531
532 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800533 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
534 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700535 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
536 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700537 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700538 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
539 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
540 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800541 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
542
543 // Rejects motion events with duplicate pointer ids.
544 pointerProperties[0].id = 1;
545 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800546 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
547 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700548 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
549 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700550 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700551 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
552 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
553 INPUT_EVENT_INJECTION_SYNC_NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 << "Should reject motion events with duplicate pointer ids.";
555}
556
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800557/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
558
559TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
560 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800561 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800562 mDispatcher->notifyConfigurationChanged(&args);
563 ASSERT_TRUE(mDispatcher->waitForIdle());
564
565 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
566}
567
568TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800569 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
570 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800571 mDispatcher->notifySwitch(&args);
572
573 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
574 args.policyFlags |= POLICY_FLAG_TRUSTED;
575 mFakePolicy->assertNotifySwitchWasCalled(args);
576}
577
Arthur Hungb92218b2018-08-14 12:00:21 +0800578// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700579static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700580static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800581
582class FakeApplicationHandle : public InputApplicationHandle {
583public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700584 FakeApplicationHandle() {
585 mInfo.name = "Fake Application";
586 mInfo.token = new BBinder();
Chris Ye6c4243b2020-07-22 12:07:12 -0700587 mInfo.dispatchingTimeoutNanos = DISPATCHING_TIMEOUT.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700588 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800589 virtual ~FakeApplicationHandle() {}
590
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700591 virtual bool updateInfo() override {
Arthur Hungb92218b2018-08-14 12:00:21 +0800592 return true;
593 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700594
595 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Chris Ye6c4243b2020-07-22 12:07:12 -0700596 mInfo.dispatchingTimeoutNanos = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700597 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800598};
599
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800600class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800601public:
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500602 explicit FakeInputReceiver(const std::shared_ptr<InputChannel>& clientChannel,
603 const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800604 : mName(name) {
605 mConsumer = std::make_unique<InputConsumer>(clientChannel);
606 }
607
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800608 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700609 InputEvent* event;
610 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
611 if (!consumeSeq) {
612 return nullptr;
613 }
614 finishEvent(*consumeSeq);
615 return event;
616 }
617
618 /**
619 * Receive an event without acknowledging it.
620 * Return the sequence number that could later be used to send finished signal.
621 */
622 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800623 uint32_t consumeSeq;
624 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800625
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800626 std::chrono::time_point start = std::chrono::steady_clock::now();
627 status_t status = WOULD_BLOCK;
628 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800629 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800630 &event);
631 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
632 if (elapsed > 100ms) {
633 break;
634 }
635 }
636
637 if (status == WOULD_BLOCK) {
638 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700639 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800640 }
641
642 if (status != OK) {
643 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700644 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800645 }
646 if (event == nullptr) {
647 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700648 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800649 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700650 if (outEvent != nullptr) {
651 *outEvent = event;
652 }
653 return consumeSeq;
654 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800655
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700656 /**
657 * To be used together with "receiveEvent" to complete the consumption of an event.
658 */
659 void finishEvent(uint32_t consumeSeq) {
660 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
661 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800662 }
663
664 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
665 int32_t expectedFlags) {
666 InputEvent* event = consume();
667
668 ASSERT_NE(nullptr, event) << mName.c_str()
669 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800670 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700671 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800672 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800673
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800674 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800675
Tiger Huang8664f8c2018-10-11 19:14:35 +0800676 switch (expectedEventType) {
677 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800678 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
679 EXPECT_EQ(expectedAction, keyEvent.getAction());
680 EXPECT_EQ(expectedFlags, keyEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800681 break;
682 }
683 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800684 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
685 EXPECT_EQ(expectedAction, motionEvent.getAction());
686 EXPECT_EQ(expectedFlags, motionEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800687 break;
688 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100689 case AINPUT_EVENT_TYPE_FOCUS: {
690 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
691 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800692 default: {
693 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
694 }
695 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800696 }
697
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100698 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
699 InputEvent* event = consume();
700 ASSERT_NE(nullptr, event) << mName.c_str()
701 << ": consumer should have returned non-NULL event.";
702 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
703 << "Got " << inputEventTypeToString(event->getType())
704 << " event instead of FOCUS event";
705
706 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
707 << mName.c_str() << ": event displayId should always be NONE.";
708
709 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
710 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
711 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
712 }
713
chaviwd1c23182019-12-20 18:44:56 -0800714 void assertNoEvents() {
715 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700716 if (event == nullptr) {
717 return;
718 }
719 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
720 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
721 ADD_FAILURE() << "Received key event "
722 << KeyEvent::actionToString(keyEvent.getAction());
723 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
724 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
725 ADD_FAILURE() << "Received motion event "
726 << MotionEvent::actionToString(motionEvent.getAction());
727 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
728 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
729 ADD_FAILURE() << "Received focus event, hasFocus = "
730 << (focusEvent.getHasFocus() ? "true" : "false");
731 }
732 FAIL() << mName.c_str()
733 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800734 }
735
736 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
737
738protected:
739 std::unique_ptr<InputConsumer> mConsumer;
740 PreallocatedInputEventFactory mEventFactory;
741
742 std::string mName;
743};
744
745class FakeWindowHandle : public InputWindowHandle {
746public:
747 static const int32_t WIDTH = 600;
748 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800749
Chris Yea209fde2020-07-22 13:54:51 -0700750 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800751 const sp<InputDispatcher>& dispatcher, const std::string name,
752 int32_t displayId, sp<IBinder> token = nullptr)
753 : mName(name) {
754 if (token == nullptr) {
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500755 std::unique_ptr<InputChannel> serverChannel, clientChannel;
chaviwd1c23182019-12-20 18:44:56 -0800756 InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500757 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(clientChannel), name);
chaviwd1c23182019-12-20 18:44:56 -0800758 token = serverChannel->getConnectionToken();
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500759 dispatcher->registerInputChannel(std::move(serverChannel));
chaviwd1c23182019-12-20 18:44:56 -0800760 }
761
762 inputApplicationHandle->updateInfo();
763 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
764
765 mInfo.token = token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700766 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800767 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100768 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500769 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
chaviwd1c23182019-12-20 18:44:56 -0800770 mInfo.frameLeft = 0;
771 mInfo.frameTop = 0;
772 mInfo.frameRight = WIDTH;
773 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700774 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800775 mInfo.globalScaleFactor = 1.0;
776 mInfo.touchableRegion.clear();
777 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
778 mInfo.visible = true;
779 mInfo.canReceiveKeys = true;
780 mInfo.hasFocus = false;
781 mInfo.hasWallpaper = false;
782 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800783 mInfo.ownerPid = INJECTOR_PID;
784 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800785 mInfo.displayId = displayId;
786 }
787
788 virtual bool updateInfo() { return true; }
789
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100790 void setFocus(bool hasFocus) { mInfo.hasFocus = hasFocus; }
chaviwd1c23182019-12-20 18:44:56 -0800791
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700792 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500793 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700794 }
795
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700796 void setPaused(bool paused) { mInfo.paused = paused; }
797
chaviwd1c23182019-12-20 18:44:56 -0800798 void setFrame(const Rect& frame) {
799 mInfo.frameLeft = frame.left;
800 mInfo.frameTop = frame.top;
801 mInfo.frameRight = frame.right;
802 mInfo.frameBottom = frame.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -0700803 mInfo.transform.set(frame.left, frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800804 mInfo.touchableRegion.clear();
805 mInfo.addTouchableRegion(frame);
806 }
807
Michael Wright44753b12020-07-08 13:48:11 +0100808 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800809
chaviw9eaa22c2020-07-01 16:21:27 -0700810 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
811 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
812 }
813
814 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700815
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800816 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
817 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
818 expectedFlags);
819 }
820
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700821 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
822 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
823 }
824
Svet Ganov5d3bc372020-01-26 23:11:07 -0800825 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
826 int32_t expectedFlags = 0) {
827 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
828 expectedFlags);
829 }
830
831 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
832 int32_t expectedFlags = 0) {
833 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
834 expectedFlags);
835 }
836
837 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
838 int32_t expectedFlags = 0) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800839 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
840 expectedFlags);
841 }
842
Svet Ganov5d3bc372020-01-26 23:11:07 -0800843 void consumeMotionPointerDown(int32_t pointerIdx,
844 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT, int32_t expectedFlags = 0) {
845 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN
846 | (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
847 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
848 }
849
850 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
851 int32_t expectedFlags = 0) {
852 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP
853 | (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
854 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
855 }
856
857 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
858 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +0000859 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
860 expectedFlags);
861 }
862
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100863 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
864 ASSERT_NE(mInputReceiver, nullptr)
865 << "Cannot consume events from a window with no receiver";
866 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
867 }
868
chaviwd1c23182019-12-20 18:44:56 -0800869 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
870 int32_t expectedFlags) {
871 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
872 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
873 expectedFlags);
874 }
875
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700876 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700877 if (mInputReceiver == nullptr) {
878 ADD_FAILURE() << "Invalid receive event on window with no receiver";
879 return std::nullopt;
880 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700881 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700882 }
883
884 void finishEvent(uint32_t sequenceNum) {
885 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
886 mInputReceiver->finishEvent(sequenceNum);
887 }
888
chaviwaf87b3e2019-10-01 16:59:28 -0700889 InputEvent* consume() {
890 if (mInputReceiver == nullptr) {
891 return nullptr;
892 }
893 return mInputReceiver->consume();
894 }
895
Arthur Hungb92218b2018-08-14 12:00:21 +0800896 void assertNoEvents() {
chaviwd1c23182019-12-20 18:44:56 -0800897 ASSERT_NE(mInputReceiver, nullptr)
898 << "Call 'assertNoEvents' on a window with an InputReceiver";
899 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +0800900 }
901
chaviwaf87b3e2019-10-01 16:59:28 -0700902 sp<IBinder> getToken() { return mInfo.token; }
903
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100904 const std::string& getName() { return mName; }
905
chaviwd1c23182019-12-20 18:44:56 -0800906private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100907 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -0800908 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700909 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800910};
911
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700912std::atomic<int32_t> FakeWindowHandle::sId{1};
913
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700914static int32_t injectKey(const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700915 int32_t displayId = ADISPLAY_ID_NONE,
916 int32_t syncMode = INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT,
917 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800918 KeyEvent event;
919 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
920
921 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800922 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700923 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
924 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +0800925
926 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700927 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
928 injectionTimeout,
929 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
Arthur Hungb92218b2018-08-14 12:00:21 +0800930}
931
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700932static int32_t injectKeyDown(const sp<InputDispatcher>& dispatcher,
933 int32_t displayId = ADISPLAY_ID_NONE) {
934 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
935}
936
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700937static int32_t injectKeyUp(const sp<InputDispatcher>& dispatcher,
938 int32_t displayId = ADISPLAY_ID_NONE) {
939 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
940}
941
Garfield Tandf26e862020-07-01 20:18:19 -0700942class PointerBuilder {
943public:
944 PointerBuilder(int32_t id, int32_t toolType) {
945 mProperties.clear();
946 mProperties.id = id;
947 mProperties.toolType = toolType;
948 mCoords.clear();
949 }
950
951 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
952
953 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
954
955 PointerBuilder& axis(int32_t axis, float value) {
956 mCoords.setAxisValue(axis, value);
957 return *this;
958 }
959
960 PointerProperties buildProperties() const { return mProperties; }
961
962 PointerCoords buildCoords() const { return mCoords; }
963
964private:
965 PointerProperties mProperties;
966 PointerCoords mCoords;
967};
968
969class MotionEventBuilder {
970public:
971 MotionEventBuilder(int32_t action, int32_t source) {
972 mAction = action;
973 mSource = source;
974 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
975 }
976
977 MotionEventBuilder& eventTime(nsecs_t eventTime) {
978 mEventTime = eventTime;
979 return *this;
980 }
981
982 MotionEventBuilder& displayId(int32_t displayId) {
983 mDisplayId = displayId;
984 return *this;
985 }
986
987 MotionEventBuilder& actionButton(int32_t actionButton) {
988 mActionButton = actionButton;
989 return *this;
990 }
991
992 MotionEventBuilder& buttonState(int32_t actionButton) {
993 mActionButton = actionButton;
994 return *this;
995 }
996
997 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
998 mRawXCursorPosition = rawXCursorPosition;
999 return *this;
1000 }
1001
1002 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1003 mRawYCursorPosition = rawYCursorPosition;
1004 return *this;
1005 }
1006
1007 MotionEventBuilder& pointer(PointerBuilder pointer) {
1008 mPointers.push_back(pointer);
1009 return *this;
1010 }
1011
1012 MotionEvent build() {
1013 std::vector<PointerProperties> pointerProperties;
1014 std::vector<PointerCoords> pointerCoords;
1015 for (const PointerBuilder& pointer : mPointers) {
1016 pointerProperties.push_back(pointer.buildProperties());
1017 pointerCoords.push_back(pointer.buildCoords());
1018 }
1019
1020 // Set mouse cursor position for the most common cases to avoid boilerplate.
1021 if (mSource == AINPUT_SOURCE_MOUSE &&
1022 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1023 mPointers.size() == 1) {
1024 mRawXCursorPosition = pointerCoords[0].getX();
1025 mRawYCursorPosition = pointerCoords[0].getY();
1026 }
1027
1028 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001029 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001030 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
1031 mAction, mActionButton, /* flags */ 0, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001032 mButtonState, MotionClassification::NONE, identityTransform,
1033 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
1034 mRawYCursorPosition, mEventTime, mEventTime, mPointers.size(),
1035 pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001036
1037 return event;
1038 }
1039
1040private:
1041 int32_t mAction;
1042 int32_t mSource;
1043 nsecs_t mEventTime;
1044 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1045 int32_t mActionButton{0};
1046 int32_t mButtonState{0};
1047 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1048 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1049
1050 std::vector<PointerBuilder> mPointers;
1051};
1052
1053static int32_t injectMotionEvent(
1054 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1055 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1056 int32_t injectionMode = INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT) {
1057 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1058 injectionTimeout,
1059 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1060}
1061
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001062static int32_t injectMotionEvent(
1063 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1064 const PointF& position,
1065 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001066 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1067 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1068 int32_t injectionMode = INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT,
1069 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001070 MotionEvent event = MotionEventBuilder(action, source)
1071 .displayId(displayId)
1072 .eventTime(eventTime)
1073 .rawXCursorPosition(cursorPosition.x)
1074 .rawYCursorPosition(cursorPosition.y)
1075 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1076 .x(position.x)
1077 .y(position.y))
1078 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001079
1080 // Inject event until dispatch out.
Garfield Tandf26e862020-07-01 20:18:19 -07001081 return injectMotionEvent(dispatcher, event);
Arthur Hungb92218b2018-08-14 12:00:21 +08001082}
1083
Garfield Tan00f511d2019-06-12 16:55:40 -07001084static int32_t injectMotionDown(const sp<InputDispatcher>& dispatcher, int32_t source,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001085 int32_t displayId, const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001086 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001087}
1088
Michael Wright3a240c42019-12-10 20:53:41 +00001089static int32_t injectMotionUp(const sp<InputDispatcher>& dispatcher, int32_t source,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001090 int32_t displayId, const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001091 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001092}
1093
Jackal Guof9696682018-10-05 12:23:23 +08001094static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1095 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1096 // Define a valid key event.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001097 NotifyKeyArgs args(/* id */ 0, currentTime, DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
1098 POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A, KEY_A,
1099 AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001100
1101 return args;
1102}
1103
chaviwd1c23182019-12-20 18:44:56 -08001104static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1105 const std::vector<PointF>& points) {
1106 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001107 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1108 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1109 }
1110
chaviwd1c23182019-12-20 18:44:56 -08001111 PointerProperties pointerProperties[pointerCount];
1112 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001113
chaviwd1c23182019-12-20 18:44:56 -08001114 for (size_t i = 0; i < pointerCount; i++) {
1115 pointerProperties[i].clear();
1116 pointerProperties[i].id = i;
1117 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001118
chaviwd1c23182019-12-20 18:44:56 -08001119 pointerCoords[i].clear();
1120 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1121 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1122 }
Jackal Guof9696682018-10-05 12:23:23 +08001123
1124 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1125 // Define a valid motion event.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001126 NotifyMotionArgs args(/* id */ 0, currentTime, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001127 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1128 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001129 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1130 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001131 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1132 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001133
1134 return args;
1135}
1136
chaviwd1c23182019-12-20 18:44:56 -08001137static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1138 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1139}
1140
Arthur Hungb92218b2018-08-14 12:00:21 +08001141TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001142 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001143 sp<FakeWindowHandle> window = new FakeWindowHandle(application, mDispatcher, "Fake Window",
1144 ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001145
Arthur Hung72d8dc32020-03-28 00:48:39 +00001146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001147 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
1148 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Arthur Hungb92218b2018-08-14 12:00:21 +08001149 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1150
1151 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001152 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001153}
1154
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001155/**
1156 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1157 * To ensure that window receives only events that were directly inside of it, add
1158 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1159 * when finding touched windows.
1160 * This test serves as a sanity check for the next test, where setInputWindows is
1161 * called twice.
1162 */
1163TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001164 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001165 sp<FakeWindowHandle> window =
1166 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1167 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001168 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001169
1170 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1171 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1172 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1173 {50, 50}))
1174 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1175
1176 // Window should receive motion event.
1177 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1178}
1179
1180/**
1181 * Calling setInputWindows twice, with the same info, should not cause any issues.
1182 * To ensure that window receives only events that were directly inside of it, add
1183 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1184 * when finding touched windows.
1185 */
1186TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001187 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001188 sp<FakeWindowHandle> window =
1189 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1190 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001191 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001192
1193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1195 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1196 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1197 {50, 50}))
1198 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1199
1200 // Window should receive motion event.
1201 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1202}
1203
Arthur Hungb92218b2018-08-14 12:00:21 +08001204// The foreground window should receive the first touch down event.
1205TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001206 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001207 sp<FakeWindowHandle> windowTop = new FakeWindowHandle(application, mDispatcher, "Top",
1208 ADISPLAY_ID_DEFAULT);
1209 sp<FakeWindowHandle> windowSecond = new FakeWindowHandle(application, mDispatcher, "Second",
1210 ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001211
Arthur Hung72d8dc32020-03-28 00:48:39 +00001212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001213 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
1214 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Arthur Hungb92218b2018-08-14 12:00:21 +08001215 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1216
1217 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001218 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001219 windowSecond->assertNoEvents();
1220}
1221
1222TEST_F(InputDispatcherTest, SetInputWindow_FocusedWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001223 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001224 sp<FakeWindowHandle> windowTop = new FakeWindowHandle(application, mDispatcher, "Top",
1225 ADISPLAY_ID_DEFAULT);
1226 sp<FakeWindowHandle> windowSecond = new FakeWindowHandle(application, mDispatcher, "Second",
1227 ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001228
Arthur Hung7ab76b12019-01-09 19:17:20 +08001229 // Set focused application.
Tiger Huang721e26f2018-07-24 22:26:19 +08001230 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Arthur Hungb92218b2018-08-14 12:00:21 +08001231
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001232 // Display should have only one focused window
1233 windowSecond->setFocus(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001235
1236 windowSecond->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08001237 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher))
1238 << "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1239
1240 // Focused window should receive event.
1241 windowTop->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001242 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08001243}
1244
Arthur Hung7ab76b12019-01-09 19:17:20 +08001245TEST_F(InputDispatcherTest, SetInputWindow_FocusPriority) {
Chris Yea209fde2020-07-22 13:54:51 -07001246 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hung7ab76b12019-01-09 19:17:20 +08001247 sp<FakeWindowHandle> windowTop = new FakeWindowHandle(application, mDispatcher, "Top",
1248 ADISPLAY_ID_DEFAULT);
1249 sp<FakeWindowHandle> windowSecond = new FakeWindowHandle(application, mDispatcher, "Second",
1250 ADISPLAY_ID_DEFAULT);
1251
1252 // Set focused application.
1253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1254
1255 // Display has two focused windows. Add them to inputWindowsHandles in z-order (top most first)
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001256 windowTop->setFocus(true);
1257 windowSecond->setFocus(true);
Arthur Hung7ab76b12019-01-09 19:17:20 +08001258
Arthur Hung72d8dc32020-03-28 00:48:39 +00001259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001260 windowTop->consumeFocusEvent(true);
Arthur Hung7ab76b12019-01-09 19:17:20 +08001261 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher))
1262 << "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1263
1264 // Top focused window should receive event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001265 windowTop->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung7ab76b12019-01-09 19:17:20 +08001266 windowSecond->assertNoEvents();
1267}
1268
Arthur Hung3b413f22018-10-26 18:05:34 +08001269TEST_F(InputDispatcherTest, SetInputWindow_InputWindowInfo) {
Chris Yea209fde2020-07-22 13:54:51 -07001270 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hung3b413f22018-10-26 18:05:34 +08001271
1272 sp<FakeWindowHandle> windowTop = new FakeWindowHandle(application, mDispatcher, "Top",
1273 ADISPLAY_ID_DEFAULT);
1274 sp<FakeWindowHandle> windowSecond = new FakeWindowHandle(application, mDispatcher, "Second",
1275 ADISPLAY_ID_DEFAULT);
1276
Arthur Hung832bc4a2019-01-28 11:43:17 +08001277 // Set focused application.
1278 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Arthur Hung3b413f22018-10-26 18:05:34 +08001279
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001280 windowTop->setFocus(true);
1281 windowSecond->setFocus(true);
Arthur Hung3b413f22018-10-26 18:05:34 +08001282 // Release channel for window is no longer valid.
1283 windowTop->releaseChannel();
Arthur Hung72d8dc32020-03-28 00:48:39 +00001284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001285 windowSecond->consumeFocusEvent(true);
Arthur Hung3b413f22018-10-26 18:05:34 +08001286
Arthur Hung832bc4a2019-01-28 11:43:17 +08001287 // Test inject a key down, should dispatch to a valid window.
1288 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher))
1289 << "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
Arthur Hung3b413f22018-10-26 18:05:34 +08001290
1291 // Top window is invalid, so it should not receive any input event.
1292 windowTop->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001293 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung3b413f22018-10-26 18:05:34 +08001294}
1295
Garfield Tandf26e862020-07-01 20:18:19 -07001296TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001297 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001298 sp<FakeWindowHandle> windowLeft =
1299 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1300 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001301 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001302 sp<FakeWindowHandle> windowRight =
1303 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1304 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001305 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001306
1307 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1308
1309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1310
1311 // Start cursor position in right window so that we can move the cursor to left window.
1312 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1313 injectMotionEvent(mDispatcher,
1314 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1315 AINPUT_SOURCE_MOUSE)
1316 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1317 .x(900)
1318 .y(400))
1319 .build()));
1320 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1321 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1322 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1323 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1324
1325 // Move cursor into left window
1326 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1327 injectMotionEvent(mDispatcher,
1328 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1329 AINPUT_SOURCE_MOUSE)
1330 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1331 .x(300)
1332 .y(400))
1333 .build()));
1334 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1335 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1336 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1337 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1338 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1339 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1340
1341 // Inject a series of mouse events for a mouse click
1342 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1343 injectMotionEvent(mDispatcher,
1344 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1345 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1346 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1347 .x(300)
1348 .y(400))
1349 .build()));
1350 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1351
1352 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1353 injectMotionEvent(mDispatcher,
1354 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1355 AINPUT_SOURCE_MOUSE)
1356 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1357 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1358 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1359 .x(300)
1360 .y(400))
1361 .build()));
1362 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1363 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1364
1365 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1366 injectMotionEvent(mDispatcher,
1367 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1368 AINPUT_SOURCE_MOUSE)
1369 .buttonState(0)
1370 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1371 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1372 .x(300)
1373 .y(400))
1374 .build()));
1375 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1376 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1377
1378 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1379 injectMotionEvent(mDispatcher,
1380 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1381 .buttonState(0)
1382 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1383 .x(300)
1384 .y(400))
1385 .build()));
1386 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1387
1388 // Move mouse cursor back to right window
1389 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1390 injectMotionEvent(mDispatcher,
1391 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1392 AINPUT_SOURCE_MOUSE)
1393 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1394 .x(900)
1395 .y(400))
1396 .build()));
1397 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1398 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1399 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1400 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1401 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1402 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1403}
1404
1405// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1406// directly in this test.
1407TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001408 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001409 sp<FakeWindowHandle> window =
1410 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1411 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001412 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001413
1414 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1415
1416 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1417
1418 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1419 injectMotionEvent(mDispatcher,
1420 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1421 AINPUT_SOURCE_MOUSE)
1422 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1423 .x(300)
1424 .y(400))
1425 .build()));
1426 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1427 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1428
1429 // Inject a series of mouse events for a mouse click
1430 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1431 injectMotionEvent(mDispatcher,
1432 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1433 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1434 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1435 .x(300)
1436 .y(400))
1437 .build()));
1438 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1439
1440 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1441 injectMotionEvent(mDispatcher,
1442 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1443 AINPUT_SOURCE_MOUSE)
1444 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1445 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1446 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1447 .x(300)
1448 .y(400))
1449 .build()));
1450 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1451 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1452
1453 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1454 injectMotionEvent(mDispatcher,
1455 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1456 AINPUT_SOURCE_MOUSE)
1457 .buttonState(0)
1458 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1459 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1460 .x(300)
1461 .y(400))
1462 .build()));
1463 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1464 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1465
1466 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1467 injectMotionEvent(mDispatcher,
1468 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1469 .buttonState(0)
1470 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1471 .x(300)
1472 .y(400))
1473 .build()));
1474 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1475
1476 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1477 injectMotionEvent(mDispatcher,
1478 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1479 AINPUT_SOURCE_MOUSE)
1480 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1481 .x(300)
1482 .y(400))
1483 .build()));
1484 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1485 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1486}
1487
Garfield Tan00f511d2019-06-12 16:55:40 -07001488TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001489 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001490
1491 sp<FakeWindowHandle> windowLeft =
1492 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1493 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001494 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001495 sp<FakeWindowHandle> windowRight =
1496 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1497 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001498 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001499
1500 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1501
Arthur Hung72d8dc32020-03-28 00:48:39 +00001502 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001503
1504 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1505 // left window. This event should be dispatched to the left window.
1506 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1507 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001508 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001509 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001510 windowRight->assertNoEvents();
1511}
1512
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001513TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001514 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001515 sp<FakeWindowHandle> window =
1516 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001517 window->setFocus(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001518
Arthur Hung72d8dc32020-03-28 00:48:39 +00001519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001520 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001521
1522 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1523 mDispatcher->notifyKey(&keyArgs);
1524
1525 // Window should receive key down event.
1526 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1527
1528 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1529 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001530 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001531 mDispatcher->notifyDeviceReset(&args);
1532 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1533 AKEY_EVENT_FLAG_CANCELED);
1534}
1535
1536TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001537 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001538 sp<FakeWindowHandle> window =
1539 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1540
Arthur Hung72d8dc32020-03-28 00:48:39 +00001541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001542
1543 NotifyMotionArgs motionArgs =
1544 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1545 ADISPLAY_ID_DEFAULT);
1546 mDispatcher->notifyMotion(&motionArgs);
1547
1548 // Window should receive motion down event.
1549 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1550
1551 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1552 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001553 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001554 mDispatcher->notifyDeviceReset(&args);
1555 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1556 0 /*expectedFlags*/);
1557}
1558
Svet Ganov5d3bc372020-01-26 23:11:07 -08001559TEST_F(InputDispatcherTest, TransferTouchFocus_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001560 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001561
1562 // Create a couple of windows
1563 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1564 "First Window", ADISPLAY_ID_DEFAULT);
1565 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1566 "Second Window", ADISPLAY_ID_DEFAULT);
1567
1568 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001570
1571 // Send down to the first window
1572 NotifyMotionArgs downMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1573 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1574 mDispatcher->notifyMotion(&downMotionArgs);
1575 // Only the first window should get the down event
1576 firstWindow->consumeMotionDown();
1577 secondWindow->assertNoEvents();
1578
1579 // Transfer touch focus to the second window
1580 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1581 // The first window gets cancel and the second gets down
1582 firstWindow->consumeMotionCancel();
1583 secondWindow->consumeMotionDown();
1584
1585 // Send up event to the second window
1586 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1587 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1588 mDispatcher->notifyMotion(&upMotionArgs);
1589 // The first window gets no events and the second gets up
1590 firstWindow->assertNoEvents();
1591 secondWindow->consumeMotionUp();
1592}
1593
1594TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointerNoSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001595 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001596
1597 PointF touchPoint = {10, 10};
1598
1599 // Create a couple of windows
1600 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1601 "First Window", ADISPLAY_ID_DEFAULT);
1602 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1603 "Second Window", ADISPLAY_ID_DEFAULT);
1604
1605 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001607
1608 // Send down to the first window
1609 NotifyMotionArgs downMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1610 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint});
1611 mDispatcher->notifyMotion(&downMotionArgs);
1612 // Only the first window should get the down event
1613 firstWindow->consumeMotionDown();
1614 secondWindow->assertNoEvents();
1615
1616 // Send pointer down to the first window
1617 NotifyMotionArgs pointerDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN
1618 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1619 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint, touchPoint});
1620 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1621 // Only the first window should get the pointer down event
1622 firstWindow->consumeMotionPointerDown(1);
1623 secondWindow->assertNoEvents();
1624
1625 // Transfer touch focus to the second window
1626 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1627 // The first window gets cancel and the second gets down and pointer down
1628 firstWindow->consumeMotionCancel();
1629 secondWindow->consumeMotionDown();
1630 secondWindow->consumeMotionPointerDown(1);
1631
1632 // Send pointer up to the second window
1633 NotifyMotionArgs pointerUpMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP
1634 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1635 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint, touchPoint});
1636 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1637 // The first window gets nothing and the second gets pointer up
1638 firstWindow->assertNoEvents();
1639 secondWindow->consumeMotionPointerUp(1);
1640
1641 // Send up event to the second window
1642 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1643 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1644 mDispatcher->notifyMotion(&upMotionArgs);
1645 // The first window gets nothing and the second gets up
1646 firstWindow->assertNoEvents();
1647 secondWindow->consumeMotionUp();
1648}
1649
1650TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001651 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001652
1653 // Create a non touch modal window that supports split touch
1654 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1655 "First Window", ADISPLAY_ID_DEFAULT);
1656 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001657 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1658 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001659
1660 // Create a non touch modal window that supports split touch
1661 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1662 "Second Window", ADISPLAY_ID_DEFAULT);
1663 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001664 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1665 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001666
1667 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001669
1670 PointF pointInFirst = {300, 200};
1671 PointF pointInSecond = {300, 600};
1672
1673 // Send down to the first window
1674 NotifyMotionArgs firstDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1675 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst});
1676 mDispatcher->notifyMotion(&firstDownMotionArgs);
1677 // Only the first window should get the down event
1678 firstWindow->consumeMotionDown();
1679 secondWindow->assertNoEvents();
1680
1681 // Send down to the second window
1682 NotifyMotionArgs secondDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN
1683 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1684 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst, pointInSecond});
1685 mDispatcher->notifyMotion(&secondDownMotionArgs);
1686 // The first window gets a move and the second a down
1687 firstWindow->consumeMotionMove();
1688 secondWindow->consumeMotionDown();
1689
1690 // Transfer touch focus to the second window
1691 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1692 // The first window gets cancel and the new gets pointer down (it already saw down)
1693 firstWindow->consumeMotionCancel();
1694 secondWindow->consumeMotionPointerDown(1);
1695
1696 // Send pointer up to the second window
1697 NotifyMotionArgs pointerUpMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP
1698 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1699 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst, pointInSecond});
1700 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1701 // The first window gets nothing and the second gets pointer up
1702 firstWindow->assertNoEvents();
1703 secondWindow->consumeMotionPointerUp(1);
1704
1705 // Send up event to the second window
1706 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1707 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1708 mDispatcher->notifyMotion(&upMotionArgs);
1709 // The first window gets nothing and the second gets up
1710 firstWindow->assertNoEvents();
1711 secondWindow->consumeMotionUp();
1712}
1713
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001714TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001715 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001716 sp<FakeWindowHandle> window =
1717 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1718
1719 window->setFocus(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001721
1722 window->consumeFocusEvent(true);
1723
1724 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1725 mDispatcher->notifyKey(&keyArgs);
1726
1727 // Window should receive key down event.
1728 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1729}
1730
1731TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001732 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001733 sp<FakeWindowHandle> window =
1734 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1735
Arthur Hung72d8dc32020-03-28 00:48:39 +00001736 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001737
1738 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1739 mDispatcher->notifyKey(&keyArgs);
1740 mDispatcher->waitForIdle();
1741
1742 window->assertNoEvents();
1743}
1744
1745// If a window is touchable, but does not have focus, it should receive motion events, but not keys
1746TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07001747 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001748 sp<FakeWindowHandle> window =
1749 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1750
Arthur Hung72d8dc32020-03-28 00:48:39 +00001751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001752
1753 // Send key
1754 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1755 mDispatcher->notifyKey(&keyArgs);
1756 // Send motion
1757 NotifyMotionArgs motionArgs =
1758 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1759 ADISPLAY_ID_DEFAULT);
1760 mDispatcher->notifyMotion(&motionArgs);
1761
1762 // Window should receive only the motion event
1763 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1764 window->assertNoEvents(); // Key event or focus event will not be received
1765}
1766
chaviwd1c23182019-12-20 18:44:56 -08001767class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00001768public:
1769 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08001770 int32_t displayId, bool isGestureMonitor = false) {
Siarhei Vishniakoud2588272020-07-10 11:15:40 -05001771 std::unique_ptr<InputChannel> serverChannel, clientChannel;
chaviwd1c23182019-12-20 18:44:56 -08001772 InputChannel::openInputChannelPair(name, serverChannel, clientChannel);
Siarhei Vishniakoud2588272020-07-10 11:15:40 -05001773 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(clientChannel), name);
1774 dispatcher->registerInputMonitor(std::move(serverChannel), displayId, isGestureMonitor);
Michael Wright3a240c42019-12-10 20:53:41 +00001775 }
1776
chaviwd1c23182019-12-20 18:44:56 -08001777 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
1778
1779 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1780 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
1781 expectedDisplayId, expectedFlags);
1782 }
1783
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001784 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
1785
1786 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
1787
chaviwd1c23182019-12-20 18:44:56 -08001788 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1789 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
1790 expectedDisplayId, expectedFlags);
1791 }
1792
1793 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1794 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
1795 expectedDisplayId, expectedFlags);
1796 }
1797
1798 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
1799
1800private:
1801 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00001802};
1803
1804// Tests for gesture monitors
1805TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001806 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001807 sp<FakeWindowHandle> window =
1808 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001810
chaviwd1c23182019-12-20 18:44:56 -08001811 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1812 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001813
1814 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1815 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1816 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1817 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001818 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001819}
1820
1821TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001822 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001823 sp<FakeWindowHandle> window =
1824 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1825
1826 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001827 window->setFocus(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001828
Arthur Hung72d8dc32020-03-28 00:48:39 +00001829 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001830 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001831
chaviwd1c23182019-12-20 18:44:56 -08001832 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1833 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001834
1835 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
1836 << "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1837 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001838 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00001839}
1840
1841TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001842 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001843 sp<FakeWindowHandle> window =
1844 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001846
chaviwd1c23182019-12-20 18:44:56 -08001847 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1848 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001849
1850 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1851 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1852 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
1853 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001854 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001855
1856 window->releaseChannel();
1857
chaviwd1c23182019-12-20 18:44:56 -08001858 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00001859
1860 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1861 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1862 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08001863 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001864}
1865
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001866TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
1867 FakeMonitorReceiver monitor =
1868 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
1869 true /*isGestureMonitor*/);
1870
1871 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
1872 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
1873 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
1874 ASSERT_TRUE(consumeSeq);
1875
1876 mFakePolicy->assertNotifyAnrWasCalled(DISPATCHING_TIMEOUT, nullptr, monitor.getToken());
1877 monitor.finishEvent(*consumeSeq);
1878 ASSERT_TRUE(mDispatcher->waitForIdle());
1879}
1880
chaviw81e2bb92019-12-18 15:03:51 -08001881TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001882 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08001883 sp<FakeWindowHandle> window =
1884 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1885
Arthur Hung72d8dc32020-03-28 00:48:39 +00001886 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08001887
1888 NotifyMotionArgs motionArgs =
1889 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1890 ADISPLAY_ID_DEFAULT);
1891
1892 mDispatcher->notifyMotion(&motionArgs);
1893 // Window should receive motion down event.
1894 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1895
1896 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001897 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08001898 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1899 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
1900 motionArgs.pointerCoords[0].getX() - 10);
1901
1902 mDispatcher->notifyMotion(&motionArgs);
1903 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
1904 0 /*expectedFlags*/);
1905}
1906
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001907/**
1908 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
1909 * the device default right away. In the test scenario, we check both the default value,
1910 * and the action of enabling / disabling.
1911 */
1912TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07001913 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001914 sp<FakeWindowHandle> window =
1915 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1916
1917 // Set focused application.
1918 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1919 window->setFocus(true);
1920
1921 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00001922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001923 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1924
1925 SCOPED_TRACE("Remove the window to trigger focus loss");
1926 window->setFocus(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001928 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
1929
1930 SCOPED_TRACE("Disable touch mode");
1931 mDispatcher->setInTouchMode(false);
1932 window->setFocus(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001934 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
1935
1936 SCOPED_TRACE("Remove the window to trigger focus loss");
1937 window->setFocus(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001939 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
1940
1941 SCOPED_TRACE("Enable touch mode again");
1942 mDispatcher->setInTouchMode(true);
1943 window->setFocus(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001944 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001945 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1946
1947 window->assertNoEvents();
1948}
1949
Gang Wange9087892020-01-07 12:17:14 -05001950TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001951 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05001952 sp<FakeWindowHandle> window =
1953 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1954
1955 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1956 window->setFocus(true);
1957
Arthur Hung72d8dc32020-03-28 00:48:39 +00001958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Gang Wange9087892020-01-07 12:17:14 -05001959 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1960
1961 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
1962 mDispatcher->notifyKey(&keyArgs);
1963
1964 InputEvent* event = window->consume();
1965 ASSERT_NE(event, nullptr);
1966
1967 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
1968 ASSERT_NE(verified, nullptr);
1969 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
1970
1971 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
1972 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
1973 ASSERT_EQ(keyArgs.source, verified->source);
1974 ASSERT_EQ(keyArgs.displayId, verified->displayId);
1975
1976 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
1977
1978 ASSERT_EQ(keyArgs.action, verifiedKey.action);
1979 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05001980 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
1981 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
1982 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
1983 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
1984 ASSERT_EQ(0, verifiedKey.repeatCount);
1985}
1986
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08001987TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001988 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08001989 sp<FakeWindowHandle> window =
1990 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1991
1992 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1993
Arthur Hung72d8dc32020-03-28 00:48:39 +00001994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08001995
1996 NotifyMotionArgs motionArgs =
1997 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1998 ADISPLAY_ID_DEFAULT);
1999 mDispatcher->notifyMotion(&motionArgs);
2000
2001 InputEvent* event = window->consume();
2002 ASSERT_NE(event, nullptr);
2003
2004 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2005 ASSERT_NE(verified, nullptr);
2006 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2007
2008 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2009 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2010 EXPECT_EQ(motionArgs.source, verified->source);
2011 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2012
2013 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2014
2015 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2016 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2017 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2018 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2019 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2020 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2021 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2022}
2023
Garfield Tan1c7bc862020-01-28 13:24:04 -08002024class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2025protected:
2026 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2027 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2028
Chris Yea209fde2020-07-22 13:54:51 -07002029 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002030 sp<FakeWindowHandle> mWindow;
2031
2032 virtual void SetUp() override {
2033 mFakePolicy = new FakeInputDispatcherPolicy();
2034 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2035 mDispatcher = new InputDispatcher(mFakePolicy);
2036 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2037 ASSERT_EQ(OK, mDispatcher->start());
2038
2039 setUpWindow();
2040 }
2041
2042 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002043 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002044 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2045
2046 mWindow->setFocus(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002047 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Garfield Tan1c7bc862020-01-28 13:24:04 -08002048
2049 mWindow->consumeFocusEvent(true);
2050 }
2051
2052 void sendAndConsumeKeyDown() {
2053 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2054 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2055 mDispatcher->notifyKey(&keyArgs);
2056
2057 // Window should receive key down event.
2058 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2059 }
2060
2061 void expectKeyRepeatOnce(int32_t repeatCount) {
2062 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2063 InputEvent* repeatEvent = mWindow->consume();
2064 ASSERT_NE(nullptr, repeatEvent);
2065
2066 uint32_t eventType = repeatEvent->getType();
2067 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2068
2069 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2070 uint32_t eventAction = repeatKeyEvent->getAction();
2071 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2072 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2073 }
2074
2075 void sendAndConsumeKeyUp() {
2076 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2077 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2078 mDispatcher->notifyKey(&keyArgs);
2079
2080 // Window should receive key down event.
2081 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2082 0 /*expectedFlags*/);
2083 }
2084};
2085
2086TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
2087 sendAndConsumeKeyDown();
2088 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2089 expectKeyRepeatOnce(repeatCount);
2090 }
2091}
2092
2093TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
2094 sendAndConsumeKeyDown();
2095 expectKeyRepeatOnce(1 /*repeatCount*/);
2096 sendAndConsumeKeyUp();
2097 mWindow->assertNoEvents();
2098}
2099
2100TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
2101 sendAndConsumeKeyDown();
2102 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2103 InputEvent* repeatEvent = mWindow->consume();
2104 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2105 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2106 IdGenerator::getSource(repeatEvent->getId()));
2107 }
2108}
2109
2110TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
2111 sendAndConsumeKeyDown();
2112
2113 std::unordered_set<int32_t> idSet;
2114 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2115 InputEvent* repeatEvent = mWindow->consume();
2116 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2117 int32_t id = repeatEvent->getId();
2118 EXPECT_EQ(idSet.end(), idSet.find(id));
2119 idSet.insert(id);
2120 }
2121}
2122
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002123/* Test InputDispatcher for MultiDisplay */
2124class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2125public:
2126 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002127 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002128 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002129
Chris Yea209fde2020-07-22 13:54:51 -07002130 application1 = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002131 windowInPrimary = new FakeWindowHandle(application1, mDispatcher, "D_1",
2132 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002133
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002134 // Set focus window for primary display, but focused display would be second one.
2135 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002136 windowInPrimary->setFocus(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002138 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002139
Chris Yea209fde2020-07-22 13:54:51 -07002140 application2 = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002141 windowInSecondary = new FakeWindowHandle(application2, mDispatcher, "D_2",
2142 SECOND_DISPLAY_ID);
2143 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002144 // Set focus display to second one.
2145 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2146 // Set focus window for second display.
2147 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002148 windowInSecondary->setFocus(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002149 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002150 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002151 }
2152
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002153 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002154 InputDispatcherTest::TearDown();
2155
Chris Yea209fde2020-07-22 13:54:51 -07002156 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002157 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002158 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002159 windowInSecondary.clear();
2160 }
2161
2162protected:
Chris Yea209fde2020-07-22 13:54:51 -07002163 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002164 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002165 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002166 sp<FakeWindowHandle> windowInSecondary;
2167};
2168
2169TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2170 // Test touch down on primary display.
2171 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
2172 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Arthur Hungb92218b2018-08-14 12:00:21 +08002173 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002174 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002175 windowInSecondary->assertNoEvents();
2176
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002177 // Test touch down on second display.
2178 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
2179 AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
Arthur Hungb92218b2018-08-14 12:00:21 +08002180 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
2181 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002182 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002183}
2184
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002185TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002186 // Test inject a key down with display id specified.
2187 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2188 << "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002189 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002190 windowInSecondary->assertNoEvents();
2191
2192 // Test inject a key down without display id specified.
Arthur Hungb92218b2018-08-14 12:00:21 +08002193 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher))
2194 << "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
2195 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002196 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002197
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002198 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002199 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002200
2201 // Expect old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002202 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2203 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002204
2205 // Test inject a key down, should timeout because of no target window.
2206 ASSERT_EQ(INPUT_EVENT_INJECTION_TIMED_OUT, injectKeyDown(mDispatcher))
2207 << "Inject key event should return INPUT_EVENT_INJECTION_TIMED_OUT";
2208 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002209 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002210 windowInSecondary->assertNoEvents();
2211}
2212
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002213// Test per-display input monitors for motion event.
2214TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002215 FakeMonitorReceiver monitorInPrimary =
2216 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2217 FakeMonitorReceiver monitorInSecondary =
2218 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002219
2220 // Test touch down on primary display.
2221 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
2222 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2223 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002224 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002225 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002226 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002227 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002228
2229 // Test touch down on second display.
2230 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
2231 AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2232 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
2233 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002234 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002235 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08002236 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002237
2238 // Test inject a non-pointer motion event.
2239 // If specific a display, it will dispatch to the focused window of particular display,
2240 // or it will dispatch to the focused window of focused display.
2241 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
2242 AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
2243 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
2244 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002245 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002246 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002247 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002248}
2249
2250// Test per-display input monitors for key event.
2251TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
2252 //Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08002253 FakeMonitorReceiver monitorInPrimary =
2254 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2255 FakeMonitorReceiver monitorInSecondary =
2256 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002257
2258 // Test inject a key down.
2259 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher))
2260 << "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
2261 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002262 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002263 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002264 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002265}
2266
Jackal Guof9696682018-10-05 12:23:23 +08002267class InputFilterTest : public InputDispatcherTest {
2268protected:
2269 static constexpr int32_t SECOND_DISPLAY_ID = 1;
2270
2271 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
2272 NotifyMotionArgs motionArgs;
2273
2274 motionArgs = generateMotionArgs(
2275 AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
2276 mDispatcher->notifyMotion(&motionArgs);
2277 motionArgs = generateMotionArgs(
2278 AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
2279 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002280 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002281 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002282 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002283 } else {
2284 mFakePolicy->assertFilterInputEventWasNotCalled();
2285 }
2286 }
2287
2288 void testNotifyKey(bool expectToBeFiltered) {
2289 NotifyKeyArgs keyArgs;
2290
2291 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2292 mDispatcher->notifyKey(&keyArgs);
2293 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
2294 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002295 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002296
2297 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002298 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002299 } else {
2300 mFakePolicy->assertFilterInputEventWasNotCalled();
2301 }
2302 }
2303};
2304
2305// Test InputFilter for MotionEvent
2306TEST_F(InputFilterTest, MotionEvent_InputFilter) {
2307 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
2308 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2309 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2310
2311 // Enable InputFilter
2312 mDispatcher->setInputFilterEnabled(true);
2313 // Test touch on both primary and second display, and check if both events are filtered.
2314 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
2315 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
2316
2317 // Disable InputFilter
2318 mDispatcher->setInputFilterEnabled(false);
2319 // Test touch on both primary and second display, and check if both events aren't filtered.
2320 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2321 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2322}
2323
2324// Test InputFilter for KeyEvent
2325TEST_F(InputFilterTest, KeyEvent_InputFilter) {
2326 // Since the InputFilter is disabled by default, check if key event aren't filtered.
2327 testNotifyKey(/*expectToBeFiltered*/ false);
2328
2329 // Enable InputFilter
2330 mDispatcher->setInputFilterEnabled(true);
2331 // Send a key event, and check if it is filtered.
2332 testNotifyKey(/*expectToBeFiltered*/ true);
2333
2334 // Disable InputFilter
2335 mDispatcher->setInputFilterEnabled(false);
2336 // Send a key event, and check if it isn't filtered.
2337 testNotifyKey(/*expectToBeFiltered*/ false);
2338}
2339
chaviwfd6d3512019-03-25 13:23:49 -07002340class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002341 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07002342 InputDispatcherTest::SetUp();
2343
Chris Yea209fde2020-07-22 13:54:51 -07002344 std::shared_ptr<FakeApplicationHandle> application =
2345 std::make_shared<FakeApplicationHandle>();
chaviwfd6d3512019-03-25 13:23:49 -07002346 mUnfocusedWindow = new FakeWindowHandle(application, mDispatcher, "Top",
2347 ADISPLAY_ID_DEFAULT);
2348 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
2349 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2350 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002351 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002352
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002353 mFocusedWindow =
2354 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2355 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01002356 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002357
2358 // Set focused application.
2359 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002360 mFocusedWindow->setFocus(true);
chaviwfd6d3512019-03-25 13:23:49 -07002361
2362 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002364 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07002365 }
2366
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002367 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07002368 InputDispatcherTest::TearDown();
2369
2370 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002371 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07002372 }
2373
2374protected:
2375 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002376 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002377 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07002378};
2379
2380// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2381// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
2382// the onPointerDownOutsideFocus callback.
2383TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002384 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
2385 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2386 {20, 20}))
chaviwfd6d3512019-03-25 13:23:49 -07002387 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002388 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002389
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002390 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07002391 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
2392}
2393
2394// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
2395// DOWN on the window that doesn't have focus. Ensure no window received the
2396// onPointerDownOutsideFocus callback.
2397TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002398 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
2399 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
chaviwfd6d3512019-03-25 13:23:49 -07002400 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002401 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002402
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002403 ASSERT_TRUE(mDispatcher->waitForIdle());
2404 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002405}
2406
2407// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
2408// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
2409TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
2410 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2411 << "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002412 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002413
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002414 ASSERT_TRUE(mDispatcher->waitForIdle());
2415 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002416}
2417
2418// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2419// DOWN on the window that already has focus. Ensure no window received the
2420// onPointerDownOutsideFocus callback.
2421TEST_F(InputDispatcherOnPointerDownOutsideFocus,
2422 OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002423 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
2424 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002425 FOCUSED_WINDOW_TOUCH_POINT))
chaviwfd6d3512019-03-25 13:23:49 -07002426 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002427 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002428
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002429 ASSERT_TRUE(mDispatcher->waitForIdle());
2430 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002431}
2432
chaviwaf87b3e2019-10-01 16:59:28 -07002433// These tests ensures we can send touch events to a single client when there are multiple input
2434// windows that point to the same client token.
2435class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
2436 virtual void SetUp() override {
2437 InputDispatcherTest::SetUp();
2438
Chris Yea209fde2020-07-22 13:54:51 -07002439 std::shared_ptr<FakeApplicationHandle> application =
2440 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07002441 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
2442 ADISPLAY_ID_DEFAULT);
2443 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
2444 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
Michael Wright44753b12020-07-08 13:48:11 +01002445 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2446 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002447 mWindow1->setFrame(Rect(0, 0, 100, 100));
2448
2449 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
2450 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01002451 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2452 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002453 mWindow2->setFrame(Rect(100, 100, 200, 200));
2454
Arthur Hung72d8dc32020-03-28 00:48:39 +00002455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07002456 }
2457
2458protected:
2459 sp<FakeWindowHandle> mWindow1;
2460 sp<FakeWindowHandle> mWindow2;
2461
2462 // Helper function to convert the point from screen coordinates into the window's space
2463 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07002464 vec2 vals = windowInfo->transform.transform(point.x, point.y);
2465 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07002466 }
2467
2468 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
2469 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002470 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07002471 InputEvent* event = window->consume();
2472
2473 ASSERT_NE(nullptr, event) << name.c_str()
2474 << ": consumer should have returned non-NULL event.";
2475
2476 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2477 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2478 << " event, got " << inputEventTypeToString(event->getType()) << " event";
2479
2480 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2481 EXPECT_EQ(expectedAction, motionEvent.getAction());
2482
2483 for (size_t i = 0; i < points.size(); i++) {
2484 float expectedX = points[i].x;
2485 float expectedY = points[i].y;
2486
2487 EXPECT_EQ(expectedX, motionEvent.getX(i))
2488 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
2489 << ", got " << motionEvent.getX(i);
2490 EXPECT_EQ(expectedY, motionEvent.getY(i))
2491 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
2492 << ", got " << motionEvent.getY(i);
2493 }
2494 }
chaviw9eaa22c2020-07-01 16:21:27 -07002495
2496 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
2497 std::vector<PointF> expectedPoints) {
2498 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
2499 ADISPLAY_ID_DEFAULT, touchedPoints);
2500 mDispatcher->notifyMotion(&motionArgs);
2501
2502 // Always consume from window1 since it's the window that has the InputReceiver
2503 consumeMotionEvent(mWindow1, action, expectedPoints);
2504 }
chaviwaf87b3e2019-10-01 16:59:28 -07002505};
2506
2507TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
2508 // Touch Window 1
2509 PointF touchedPoint = {10, 10};
2510 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002511 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002512
2513 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07002514 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002515
2516 // Touch Window 2
2517 touchedPoint = {150, 150};
2518 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002519 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002520}
2521
chaviw9eaa22c2020-07-01 16:21:27 -07002522TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
2523 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07002524 mWindow2->setWindowScale(0.5f, 0.5f);
2525
2526 // Touch Window 1
2527 PointF touchedPoint = {10, 10};
2528 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002529 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002530 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07002531 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002532
2533 // Touch Window 2
2534 touchedPoint = {150, 150};
2535 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002536 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
2537 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002538
chaviw9eaa22c2020-07-01 16:21:27 -07002539 // Update the transform so rotation is set
2540 mWindow2->setWindowTransform(0, -1, 1, 0);
2541 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
2542 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002543}
2544
chaviw9eaa22c2020-07-01 16:21:27 -07002545TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002546 mWindow2->setWindowScale(0.5f, 0.5f);
2547
2548 // Touch Window 1
2549 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2550 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002551 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002552
2553 // Touch Window 2
2554 int32_t actionPointerDown =
2555 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002556 touchedPoints.push_back(PointF{150, 150});
2557 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2558 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002559
chaviw9eaa22c2020-07-01 16:21:27 -07002560 // Release Window 2
2561 int32_t actionPointerUp =
2562 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2563 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
2564 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002565
chaviw9eaa22c2020-07-01 16:21:27 -07002566 // Update the transform so rotation is set for Window 2
2567 mWindow2->setWindowTransform(0, -1, 1, 0);
2568 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2569 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002570}
2571
chaviw9eaa22c2020-07-01 16:21:27 -07002572TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002573 mWindow2->setWindowScale(0.5f, 0.5f);
2574
2575 // Touch Window 1
2576 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2577 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002578 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002579
2580 // Touch Window 2
2581 int32_t actionPointerDown =
2582 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002583 touchedPoints.push_back(PointF{150, 150});
2584 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002585
chaviw9eaa22c2020-07-01 16:21:27 -07002586 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002587
2588 // Move both windows
2589 touchedPoints = {{20, 20}, {175, 175}};
2590 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2591 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2592
chaviw9eaa22c2020-07-01 16:21:27 -07002593 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002594
chaviw9eaa22c2020-07-01 16:21:27 -07002595 // Release Window 2
2596 int32_t actionPointerUp =
2597 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2598 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
2599 expectedPoints.pop_back();
2600
2601 // Touch Window 2
2602 mWindow2->setWindowTransform(0, -1, 1, 0);
2603 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2604 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
2605
2606 // Move both windows
2607 touchedPoints = {{20, 20}, {175, 175}};
2608 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2609 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2610
2611 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002612}
2613
2614TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
2615 mWindow1->setWindowScale(0.5f, 0.5f);
2616
2617 // Touch Window 1
2618 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2619 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002620 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002621
2622 // Touch Window 2
2623 int32_t actionPointerDown =
2624 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002625 touchedPoints.push_back(PointF{150, 150});
2626 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002627
chaviw9eaa22c2020-07-01 16:21:27 -07002628 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002629
2630 // Move both windows
2631 touchedPoints = {{20, 20}, {175, 175}};
2632 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2633 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2634
chaviw9eaa22c2020-07-01 16:21:27 -07002635 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002636}
2637
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002638class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
2639 virtual void SetUp() override {
2640 InputDispatcherTest::SetUp();
2641
Chris Yea209fde2020-07-22 13:54:51 -07002642 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002643 mApplication->setDispatchingTimeout(20ms);
2644 mWindow =
2645 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2646 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05002647 mWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002648 mWindow->setFocus(true);
2649 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2650 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002651 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002652
2653 // Set focused application.
2654 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
2655
2656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2657 mWindow->consumeFocusEvent(true);
2658 }
2659
2660 virtual void TearDown() override {
2661 InputDispatcherTest::TearDown();
2662 mWindow.clear();
2663 }
2664
2665protected:
Chris Yea209fde2020-07-22 13:54:51 -07002666 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002667 sp<FakeWindowHandle> mWindow;
2668 static constexpr PointF WINDOW_LOCATION = {20, 20};
2669
2670 void tapOnWindow() {
2671 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
2672 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2673 WINDOW_LOCATION));
2674 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
2675 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2676 WINDOW_LOCATION));
2677 }
2678};
2679
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002680// Send a tap and respond, which should not cause an ANR.
2681TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
2682 tapOnWindow();
2683 mWindow->consumeMotionDown();
2684 mWindow->consumeMotionUp();
2685 ASSERT_TRUE(mDispatcher->waitForIdle());
2686 mFakePolicy->assertNotifyAnrWasNotCalled();
2687}
2688
2689// Send a regular key and respond, which should not cause an ANR.
2690TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
2691 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher));
2692 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
2693 ASSERT_TRUE(mDispatcher->waitForIdle());
2694 mFakePolicy->assertNotifyAnrWasNotCalled();
2695}
2696
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002697// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002698// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
2699// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002700TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
2701 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
2702 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2703 WINDOW_LOCATION));
2704
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002705 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
2706 ASSERT_TRUE(sequenceNum);
2707 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2708 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002709
2710 // The remaining lines are not really needed for the test, but kept as a sanity check
2711 mWindow->finishEvent(*sequenceNum);
2712 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2713 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002714 ASSERT_TRUE(mDispatcher->waitForIdle());
2715}
2716
2717// Send a key to the app and have the app not respond right away.
2718TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
2719 // Inject a key, and don't respond - expect that ANR is called.
2720 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher));
2721 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
2722 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002723 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002724 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002725 ASSERT_TRUE(mDispatcher->waitForIdle());
2726}
2727
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002728// We have a focused application, but no focused window
2729TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
2730 mWindow->setFocus(false);
2731 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2732 mWindow->consumeFocusEvent(false);
2733
2734 // taps on the window work as normal
2735 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
2736 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2737 WINDOW_LOCATION));
2738 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
2739 mDispatcher->waitForIdle();
2740 mFakePolicy->assertNotifyAnrWasNotCalled();
2741
2742 // Once a focused event arrives, we get an ANR for this application
2743 // We specify the injection timeout to be smaller than the application timeout, to ensure that
2744 // injection times out (instead of failing).
2745 const int32_t result =
2746 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
2747 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT, 10ms);
2748 ASSERT_EQ(INPUT_EVENT_INJECTION_TIMED_OUT, result);
2749 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2750 mFakePolicy->assertNotifyAnrWasCalled(timeout, mApplication, nullptr /*windowToken*/);
2751 ASSERT_TRUE(mDispatcher->waitForIdle());
2752}
2753
2754// We have a focused application, but no focused window
2755// If the policy wants to keep waiting on the focused window to be added, make sure
2756// that this timeout extension is honored and ANR is raised again.
2757TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_ExtendsAnr) {
2758 mWindow->setFocus(false);
2759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2760 mWindow->consumeFocusEvent(false);
2761 const std::chrono::duration timeout = 5ms;
2762 mFakePolicy->setAnrTimeout(timeout);
2763
2764 // Once a focused event arrives, we get an ANR for this application
2765 // We specify the injection timeout to be smaller than the application timeout, to ensure that
2766 // injection times out (instead of failing).
2767 const int32_t result =
2768 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
2769 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT, 10ms);
2770 ASSERT_EQ(INPUT_EVENT_INJECTION_TIMED_OUT, result);
2771 const std::chrono::duration appTimeout =
2772 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2773 mFakePolicy->assertNotifyAnrWasCalled(appTimeout, mApplication, nullptr /*windowToken*/);
2774
2775 // After the extended time has passed, ANR should be raised again
2776 mFakePolicy->assertNotifyAnrWasCalled(timeout, mApplication, nullptr /*windowToken*/);
2777
2778 // If we stop extending the timeout, dispatcher should go to idle.
2779 // Another ANR may be raised during this time
2780 mFakePolicy->setAnrTimeout(0ms);
2781 ASSERT_TRUE(mDispatcher->waitForIdle());
2782}
2783
2784// We have a focused application, but no focused window
2785TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
2786 mWindow->setFocus(false);
2787 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2788 mWindow->consumeFocusEvent(false);
2789
2790 // Once a focused event arrives, we get an ANR for this application
2791 const int32_t result =
2792 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
2793 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT, 10ms);
2794 ASSERT_EQ(INPUT_EVENT_INJECTION_TIMED_OUT, result);
2795
2796 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2797 mFakePolicy->assertNotifyAnrWasCalled(timeout, mApplication, nullptr /*windowToken*/);
2798
2799 // Future focused events get dropped right away
2800 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED, injectKeyDown(mDispatcher));
2801 ASSERT_TRUE(mDispatcher->waitForIdle());
2802 mWindow->assertNoEvents();
2803}
2804
2805/**
2806 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
2807 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
2808 * If we process 1 of the events, but ANR on the second event with the same timestamp,
2809 * the ANR mechanism should still work.
2810 *
2811 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
2812 * DOWN event, while not responding on the second one.
2813 */
2814TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
2815 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
2816 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2817 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
2818 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
2819 AMOTION_EVENT_INVALID_CURSOR_POSITION},
2820 500ms, INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT, currentTime);
2821
2822 // Now send ACTION_UP, with identical timestamp
2823 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2824 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
2825 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
2826 AMOTION_EVENT_INVALID_CURSOR_POSITION},
2827 500ms, INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT, currentTime);
2828
2829 // We have now sent down and up. Let's consume first event and then ANR on the second.
2830 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2831 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2832 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/, mWindow->getToken());
2833}
2834
2835// If an app is not responding to a key event, gesture monitors should continue to receive
2836// new motion events
2837TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
2838 FakeMonitorReceiver monitor =
2839 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2840 true /*isGestureMonitor*/);
2841
2842 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
2843 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2844 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
2845
2846 // Stuck on the ACTION_UP
2847 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2848 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr, mWindow->getToken());
2849
2850 // New tap will go to the gesture monitor, but not to the window
2851 tapOnWindow();
2852 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2853 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
2854
2855 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
2856 mDispatcher->waitForIdle();
2857 mWindow->assertNoEvents();
2858 monitor.assertNoEvents();
2859}
2860
2861// If an app is not responding to a motion event, gesture monitors should continue to receive
2862// new motion events
2863TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
2864 FakeMonitorReceiver monitor =
2865 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2866 true /*isGestureMonitor*/);
2867
2868 tapOnWindow();
2869 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2870 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
2871
2872 mWindow->consumeMotionDown();
2873 // Stuck on the ACTION_UP
2874 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2875 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr, mWindow->getToken());
2876
2877 // New tap will go to the gesture monitor, but not to the window
2878 tapOnWindow();
2879 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2880 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
2881
2882 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
2883 mDispatcher->waitForIdle();
2884 mWindow->assertNoEvents();
2885 monitor.assertNoEvents();
2886}
2887
2888// If a window is unresponsive, then you get anr. if the window later catches up and starts to
2889// process events, you don't get an anr. When the window later becomes unresponsive again, you
2890// get an ANR again.
2891// 1. tap -> block on ACTION_UP -> receive ANR
2892// 2. consume all pending events (= queue becomes healthy again)
2893// 3. tap again -> block on ACTION_UP again -> receive ANR second time
2894TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
2895 tapOnWindow();
2896
2897 mWindow->consumeMotionDown();
2898 // Block on ACTION_UP
2899 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2900 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/, mWindow->getToken());
2901 mWindow->consumeMotionUp(); // Now the connection should be healthy again
2902 mDispatcher->waitForIdle();
2903 mWindow->assertNoEvents();
2904
2905 tapOnWindow();
2906 mWindow->consumeMotionDown();
2907 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/, mWindow->getToken());
2908 mWindow->consumeMotionUp();
2909
2910 mDispatcher->waitForIdle();
2911 mWindow->assertNoEvents();
2912}
2913
2914// If the policy tells us to raise ANR again after some time, ensure that the timeout extension
2915// is honored
2916TEST_F(InputDispatcherSingleWindowAnr, Policy_CanExtendTimeout) {
2917 const std::chrono::duration timeout = 5ms;
2918 mFakePolicy->setAnrTimeout(timeout);
2919
2920 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
2921 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2922 WINDOW_LOCATION));
2923
2924 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
2925 mFakePolicy->assertNotifyAnrWasCalled(windowTimeout, nullptr /*application*/,
2926 mWindow->getToken());
2927
2928 // Since the policy wanted to extend ANR, make sure it is called again after the extension
2929 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/, mWindow->getToken());
2930 mFakePolicy->setAnrTimeout(0ms);
2931 std::this_thread::sleep_for(windowTimeout);
2932 // We are not checking if ANR has been called, because it may have been called again by the
2933 // time we set the timeout to 0
2934
2935 // When the policy finally says stop, we should get ACTION_CANCEL
2936 mWindow->consumeMotionDown();
2937 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2938 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
2939 mWindow->assertNoEvents();
2940}
2941
2942/**
2943 * If a window is processing a motion event, and then a key event comes in, the key event should
2944 * not to to the focused window until the motion is processed.
2945 *
2946 * Warning!!!
2947 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
2948 * and the injection timeout that we specify when injecting the key.
2949 * We must have the injection timeout (10ms) be smaller than
2950 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
2951 *
2952 * If that value changes, this test should also change.
2953 */
2954TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
2955 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
2956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2957
2958 tapOnWindow();
2959 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
2960 ASSERT_TRUE(downSequenceNum);
2961 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
2962 ASSERT_TRUE(upSequenceNum);
2963 // Don't finish the events yet, and send a key
2964 // Injection will "succeed" because we will eventually give up and send the key to the focused
2965 // window even if motions are still being processed. But because the injection timeout is short,
2966 // we will receive INJECTION_TIMED_OUT as the result.
2967
2968 int32_t result =
2969 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
2970 INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT, 10ms);
2971 ASSERT_EQ(INPUT_EVENT_INJECTION_TIMED_OUT, result);
2972 // Key will not be sent to the window, yet, because the window is still processing events
2973 // and the key remains pending, waiting for the touch events to be processed
2974 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
2975 ASSERT_FALSE(keySequenceNum);
2976
2977 std::this_thread::sleep_for(500ms);
2978 // if we wait long enough though, dispatcher will give up, and still send the key
2979 // to the focused window, even though we have not yet finished the motion event
2980 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2981 mWindow->finishEvent(*downSequenceNum);
2982 mWindow->finishEvent(*upSequenceNum);
2983}
2984
2985/**
2986 * If a window is processing a motion event, and then a key event comes in, the key event should
2987 * not go to the focused window until the motion is processed.
2988 * If then a new motion comes in, then the pending key event should be going to the currently
2989 * focused window right away.
2990 */
2991TEST_F(InputDispatcherSingleWindowAnr,
2992 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
2993 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
2994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2995
2996 tapOnWindow();
2997 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
2998 ASSERT_TRUE(downSequenceNum);
2999 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3000 ASSERT_TRUE(upSequenceNum);
3001 // Don't finish the events yet, and send a key
3002 // Injection is async, so it will succeed
3003 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
3004 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
3005 ADISPLAY_ID_DEFAULT, INPUT_EVENT_INJECTION_SYNC_NONE));
3006 // At this point, key is still pending, and should not be sent to the application yet.
3007 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3008 ASSERT_FALSE(keySequenceNum);
3009
3010 // Now tap down again. It should cause the pending key to go to the focused window right away.
3011 tapOnWindow();
3012 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3013 // the other events yet. We can finish events in any order.
3014 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3015 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3016 mWindow->consumeMotionDown();
3017 mWindow->consumeMotionUp();
3018 mWindow->assertNoEvents();
3019}
3020
3021class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3022 virtual void SetUp() override {
3023 InputDispatcherTest::SetUp();
3024
Chris Yea209fde2020-07-22 13:54:51 -07003025 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003026 mApplication->setDispatchingTimeout(10ms);
3027 mUnfocusedWindow =
3028 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3029 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3030 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3031 // window.
3032 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003033 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3034 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3035 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003036
3037 mFocusedWindow =
3038 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003039 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003040 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003041 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3042 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003043
3044 // Set focused application.
3045 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3046 mFocusedWindow->setFocus(true);
3047
3048 // Expect one focus window exist in display.
3049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3050 mFocusedWindow->consumeFocusEvent(true);
3051 }
3052
3053 virtual void TearDown() override {
3054 InputDispatcherTest::TearDown();
3055
3056 mUnfocusedWindow.clear();
3057 mFocusedWindow.clear();
3058 }
3059
3060protected:
Chris Yea209fde2020-07-22 13:54:51 -07003061 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003062 sp<FakeWindowHandle> mUnfocusedWindow;
3063 sp<FakeWindowHandle> mFocusedWindow;
3064 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3065 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3066 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3067
3068 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3069
3070 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3071
3072private:
3073 void tap(const PointF& location) {
3074 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
3075 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3076 location));
3077 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
3078 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3079 location));
3080 }
3081};
3082
3083// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3084// should be ANR'd first.
3085TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
3086 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
3087 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3088 FOCUSED_WINDOW_LOCATION))
3089 << "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
3090 mFocusedWindow->consumeMotionDown();
3091 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3092 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3093 // We consumed all events, so no ANR
3094 ASSERT_TRUE(mDispatcher->waitForIdle());
3095 mFakePolicy->assertNotifyAnrWasNotCalled();
3096
3097 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED,
3098 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3099 FOCUSED_WINDOW_LOCATION));
3100 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
3101 ASSERT_TRUE(unfocusedSequenceNum);
3102 std::optional<uint32_t> focusedSequenceNum = mFocusedWindow->receiveEvent();
3103 ASSERT_TRUE(focusedSequenceNum);
3104
3105 const std::chrono::duration timeout =
3106 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
3107 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/,
3108 mFocusedWindow->getToken());
3109
3110 mFocusedWindow->finishEvent(*focusedSequenceNum);
3111 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
3112 ASSERT_TRUE(mDispatcher->waitForIdle());
3113}
3114
3115// If we have 2 windows with identical timeouts that are both unresponsive,
3116// it doesn't matter which order they should have ANR.
3117// But we should receive ANR for both.
3118TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
3119 // Set the timeout for unfocused window to match the focused window
3120 mUnfocusedWindow->setDispatchingTimeout(10ms);
3121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3122
3123 tapOnFocusedWindow();
3124 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Chris Yea209fde2020-07-22 13:54:51 -07003125 std::pair<std::shared_ptr<InputApplicationHandle>, sp<IBinder>> anrData1 =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003126 mFakePolicy->getNotifyAnrData(10ms);
Chris Yea209fde2020-07-22 13:54:51 -07003127 std::pair<std::shared_ptr<InputApplicationHandle>, sp<IBinder>> anrData2 =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003128 mFakePolicy->getNotifyAnrData(0ms);
3129
3130 // We don't know which window will ANR first. But both of them should happen eventually.
3131 ASSERT_TRUE(mFocusedWindow->getToken() == anrData1.second ||
3132 mFocusedWindow->getToken() == anrData2.second);
3133 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrData1.second ||
3134 mUnfocusedWindow->getToken() == anrData2.second);
3135
3136 ASSERT_TRUE(mDispatcher->waitForIdle());
3137 mFakePolicy->assertNotifyAnrWasNotCalled();
3138}
3139
3140// If a window is already not responding, the second tap on the same window should be ignored.
3141// We should also log an error to account for the dropped event (not tested here).
3142// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
3143TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
3144 tapOnFocusedWindow();
3145 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3146 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3147 // Receive the events, but don't respond
3148 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
3149 ASSERT_TRUE(downEventSequenceNum);
3150 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
3151 ASSERT_TRUE(upEventSequenceNum);
3152 const std::chrono::duration timeout =
3153 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
3154 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/,
3155 mFocusedWindow->getToken());
3156
3157 // Tap once again
3158 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
3159 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
3160 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3161 FOCUSED_WINDOW_LOCATION));
3162 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
3163 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3164 FOCUSED_WINDOW_LOCATION));
3165 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
3166 // valid touch target
3167 mUnfocusedWindow->assertNoEvents();
3168
3169 // Consume the first tap
3170 mFocusedWindow->finishEvent(*downEventSequenceNum);
3171 mFocusedWindow->finishEvent(*upEventSequenceNum);
3172 ASSERT_TRUE(mDispatcher->waitForIdle());
3173 // The second tap did not go to the focused window
3174 mFocusedWindow->assertNoEvents();
3175 // should not have another ANR after the window just became healthy again
3176 mFakePolicy->assertNotifyAnrWasNotCalled();
3177}
3178
3179// If you tap outside of all windows, there will not be ANR
3180TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
3181 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
3182 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3183 LOCATION_OUTSIDE_ALL_WINDOWS));
3184 ASSERT_TRUE(mDispatcher->waitForIdle());
3185 mFakePolicy->assertNotifyAnrWasNotCalled();
3186}
3187
3188// Since the focused window is paused, tapping on it should not produce any events
3189TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
3190 mFocusedWindow->setPaused(true);
3191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3192
3193 ASSERT_EQ(INPUT_EVENT_INJECTION_FAILED,
3194 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3195 FOCUSED_WINDOW_LOCATION));
3196
3197 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
3198 ASSERT_TRUE(mDispatcher->waitForIdle());
3199 // Should not ANR because the window is paused, and touches shouldn't go to it
3200 mFakePolicy->assertNotifyAnrWasNotCalled();
3201
3202 mFocusedWindow->assertNoEvents();
3203 mUnfocusedWindow->assertNoEvents();
3204}
3205
3206/**
3207 * If a window is processing a motion event, and then a key event comes in, the key event should
3208 * not to to the focused window until the motion is processed.
3209 * If a different window becomes focused at this time, the key should go to that window instead.
3210 *
3211 * Warning!!!
3212 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3213 * and the injection timeout that we specify when injecting the key.
3214 * We must have the injection timeout (10ms) be smaller than
3215 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3216 *
3217 * If that value changes, this test should also change.
3218 */
3219TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
3220 // Set a long ANR timeout to prevent it from triggering
3221 mFocusedWindow->setDispatchingTimeout(2s);
3222 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3223
3224 tapOnUnfocusedWindow();
3225 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
3226 ASSERT_TRUE(downSequenceNum);
3227 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
3228 ASSERT_TRUE(upSequenceNum);
3229 // Don't finish the events yet, and send a key
3230 // Injection will succeed because we will eventually give up and send the key to the focused
3231 // window even if motions are still being processed.
3232
3233 int32_t result =
3234 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
3235 INPUT_EVENT_INJECTION_SYNC_NONE, 10ms /*injectionTimeout*/);
3236 ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, result);
3237 // Key will not be sent to the window, yet, because the window is still processing events
3238 // and the key remains pending, waiting for the touch events to be processed
3239 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
3240 ASSERT_FALSE(keySequenceNum);
3241
3242 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
3243 mFocusedWindow->setFocus(false);
3244 mUnfocusedWindow->setFocus(true);
3245 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3246
3247 // Focus events should precede the key events
3248 mUnfocusedWindow->consumeFocusEvent(true);
3249 mFocusedWindow->consumeFocusEvent(false);
3250
3251 // Finish the tap events, which should unblock dispatcher
3252 mUnfocusedWindow->finishEvent(*downSequenceNum);
3253 mUnfocusedWindow->finishEvent(*upSequenceNum);
3254
3255 // Now that all queues are cleared and no backlog in the connections, the key event
3256 // can finally go to the newly focused "mUnfocusedWindow".
3257 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3258 mFocusedWindow->assertNoEvents();
3259 mUnfocusedWindow->assertNoEvents();
3260}
3261
3262// When the touch stream is split across 2 windows, and one of them does not respond,
3263// then ANR should be raised and the touch should be canceled for the unresponsive window.
3264// The other window should not be affected by that.
3265TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
3266 // Touch Window 1
3267 NotifyMotionArgs motionArgs =
3268 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3269 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
3270 mDispatcher->notifyMotion(&motionArgs);
3271 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3272 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3273
3274 // Touch Window 2
3275 int32_t actionPointerDown =
3276 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3277
3278 motionArgs =
3279 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3280 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
3281 mDispatcher->notifyMotion(&motionArgs);
3282
3283 const std::chrono::duration timeout =
3284 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
3285 mFakePolicy->assertNotifyAnrWasCalled(timeout, nullptr /*application*/,
3286 mFocusedWindow->getToken());
3287
3288 mUnfocusedWindow->consumeMotionDown();
3289 mFocusedWindow->consumeMotionDown();
3290 // Focused window may or may not receive ACTION_MOVE
3291 // But it should definitely receive ACTION_CANCEL due to the ANR
3292 InputEvent* event;
3293 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
3294 ASSERT_TRUE(moveOrCancelSequenceNum);
3295 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
3296 ASSERT_NE(nullptr, event);
3297 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
3298 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
3299 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
3300 mFocusedWindow->consumeMotionCancel();
3301 } else {
3302 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
3303 }
3304
3305 ASSERT_TRUE(mDispatcher->waitForIdle());
3306 mUnfocusedWindow->assertNoEvents();
3307 mFocusedWindow->assertNoEvents();
3308}
3309
Garfield Tane84e6f92019-08-29 17:28:41 -07003310} // namespace android::inputdispatcher