blob: 5ab2ae3f418538d994eb9f9041e8af8a7911aac4 [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;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080032using android::os::InputEventInjectionResult;
33using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010034using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080035
Garfield Tane84e6f92019-08-29 17:28:41 -070036namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080037
38// An arbitrary time value.
39static const nsecs_t ARBITRARY_TIME = 1234;
40
41// An arbitrary device id.
42static const int32_t DEVICE_ID = 1;
43
Jeff Brownf086ddb2014-02-11 14:28:48 -080044// An arbitrary display id.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -080045static const int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
Jeff Brownf086ddb2014-02-11 14:28:48 -080046
Michael Wrightd02c5b62014-02-10 15:10:22 -080047// An arbitrary injector pid / uid pair that has permission to inject events.
48static const int32_t INJECTOR_PID = 999;
49static const int32_t INJECTOR_UID = 1001;
50
chaviwd1c23182019-12-20 18:44:56 -080051struct PointF {
52 float x;
53 float y;
54};
Michael Wrightd02c5b62014-02-10 15:10:22 -080055
Gang Wang342c9272020-01-13 13:15:04 -050056/**
57 * Return a DOWN key event with KEYCODE_A.
58 */
59static KeyEvent getTestKeyEvent() {
60 KeyEvent event;
61
Garfield Tanfbe732e2020-01-24 11:26:14 -080062 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
63 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
64 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050065 return event;
66}
67
Michael Wrightd02c5b62014-02-10 15:10:22 -080068// --- FakeInputDispatcherPolicy ---
69
70class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
71 InputDispatcherConfiguration mConfig;
72
73protected:
74 virtual ~FakeInputDispatcherPolicy() {
75 }
76
77public:
78 FakeInputDispatcherPolicy() {
Jackal Guof9696682018-10-05 12:23:23 +080079 }
80
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080081 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080082 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
83 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080084 }
85
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080086 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080087 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
88 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080089 }
90
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070091 void assertFilterInputEventWasNotCalled() {
92 std::scoped_lock lock(mLock);
93 ASSERT_EQ(nullptr, mFilteredEvent);
94 }
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080096 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070097 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080098 ASSERT_TRUE(mConfigurationChangedTime)
99 << "Timed out waiting for configuration changed call";
100 ASSERT_EQ(*mConfigurationChangedTime, when);
101 mConfigurationChangedTime = std::nullopt;
102 }
103
104 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700105 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800106 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800107 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800108 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
109 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
110 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
111 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
112 mLastNotifySwitch = std::nullopt;
113 }
114
chaviwfd6d3512019-03-25 13:23:49 -0700115 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700116 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800117 ASSERT_EQ(touchedToken, mOnPointerDownToken);
118 mOnPointerDownToken.clear();
119 }
120
121 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700122 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800123 ASSERT_TRUE(mOnPointerDownToken == nullptr)
124 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700125 }
126
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700127 // This function must be called soon after the expected ANR timer starts,
128 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500129 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700130 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500131 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
132 std::shared_ptr<InputApplicationHandle> application;
133 { // acquire lock
134 std::unique_lock lock(mLock);
135 android::base::ScopedLockAssertion assumeLocked(mLock);
136 ASSERT_NO_FATAL_FAILURE(
137 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
138 } // release lock
139 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700140 }
141
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500142 void assertNotifyConnectionUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
143 const sp<IBinder>& expectedConnectionToken) {
144 sp<IBinder> connectionToken = getUnresponsiveConnectionToken(timeout);
145 ASSERT_EQ(expectedConnectionToken, connectionToken);
146 }
147
148 void assertNotifyConnectionResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
149 sp<IBinder> connectionToken = getResponsiveConnectionToken();
150 ASSERT_EQ(expectedConnectionToken, connectionToken);
151 }
152
153 sp<IBinder> getUnresponsiveConnectionToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700154 std::unique_lock lock(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700155 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500156 return getAnrTokenLockedInterruptible(timeout, mAnrConnectionTokens, lock);
157 }
158
159 sp<IBinder> getResponsiveConnectionToken() {
160 std::unique_lock lock(mLock);
161 android::base::ScopedLockAssertion assumeLocked(mLock);
162 return getAnrTokenLockedInterruptible(0s, mResponsiveConnectionTokens, lock);
163 }
164
165 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
166 // for a specific container to become non-empty. When the container is non-empty, return the
167 // first entry from the container and erase it.
168 template <class T>
169 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
170 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
171 const std::chrono::time_point start = std::chrono::steady_clock::now();
172 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700173
174 // If there is an ANR, Dispatcher won't be idle because there are still events
175 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
176 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500177 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
178 // to provide it some time to act. 100ms seems reasonable.
179 mNotifyAnr.wait_for(lock, timeToWait,
180 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700181 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500182 if (storage.empty()) {
183 ADD_FAILURE() << "Did not receive the ANR callback";
184 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700185 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700186 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
187 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700188 if (std::chrono::abs(timeout - waited) > 100ms) {
189 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
190 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
191 << "ms, but waited "
192 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
193 << "ms instead";
194 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500195 T token = storage.front();
196 storage.pop();
197 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700198 }
199
200 void assertNotifyAnrWasNotCalled() {
201 std::scoped_lock lock(mLock);
202 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500203 ASSERT_TRUE(mAnrConnectionTokens.empty());
204 ASSERT_TRUE(mResponsiveConnectionTokens.empty())
205 << "ANR was not called, but please also consume the 'connection is responsive' "
206 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700207 }
208
Garfield Tan1c7bc862020-01-28 13:24:04 -0800209 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
210 mConfig.keyRepeatTimeout = timeout;
211 mConfig.keyRepeatDelay = delay;
212 }
213
Michael Wrightd02c5b62014-02-10 15:10:22 -0800214private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700215 std::mutex mLock;
216 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
217 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
218 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
219 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800220
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700221 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700222 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500223 std::queue<sp<IBinder>> mAnrConnectionTokens GUARDED_BY(mLock);
224 std::queue<sp<IBinder>> mResponsiveConnectionTokens GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700225 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700226
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600227 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700228 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800229 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 }
231
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500232 void notifyConnectionUnresponsive(const sp<IBinder>& connectionToken,
233 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700234 std::scoped_lock lock(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500235 mAnrConnectionTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700236 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500237 }
238
239 void notifyConnectionResponsive(const sp<IBinder>& connectionToken) override {
240 std::scoped_lock lock(mLock);
241 mResponsiveConnectionTokens.push(connectionToken);
242 mNotifyAnr.notify_all();
243 }
244
245 void notifyNoFocusedWindowAnr(
246 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
247 std::scoped_lock lock(mLock);
248 mAnrApplications.push(applicationHandle);
249 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800250 }
251
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600252 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600254 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700255
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600256 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000257
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600258 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259 *outConfig = mConfig;
260 }
261
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600262 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700263 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800264 switch (inputEvent->getType()) {
265 case AINPUT_EVENT_TYPE_KEY: {
266 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800267 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800268 break;
269 }
270
271 case AINPUT_EVENT_TYPE_MOTION: {
272 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800273 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800274 break;
275 }
276 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277 return true;
278 }
279
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600280 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800281
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600282 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600284 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285 return 0;
286 }
287
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600288 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289 return false;
290 }
291
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600292 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
293 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700294 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800295 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
296 * essentially a passthrough for notifySwitch.
297 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800298 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299 }
300
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600301 void pokeUserActivity(nsecs_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800302
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600303 bool checkInjectEventsPermissionNonReentrant(int32_t, int32_t) override { return false; }
Jackal Guof9696682018-10-05 12:23:23 +0800304
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600305 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700306 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700307 mOnPointerDownToken = newToken;
308 }
309
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800310 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
311 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700312 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800313 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
314 ASSERT_EQ(mFilteredEvent->getType(), type);
315
316 if (type == AINPUT_EVENT_TYPE_KEY) {
317 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
318 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
319 EXPECT_EQ(keyEvent.getAction(), action);
320 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
321 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
322 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
323 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
324 EXPECT_EQ(motionEvent.getAction(), action);
325 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
326 } else {
327 FAIL() << "Unknown type: " << type;
328 }
329
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800330 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800332};
333
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334// --- InputDispatcherTest ---
335
336class InputDispatcherTest : public testing::Test {
337protected:
338 sp<FakeInputDispatcherPolicy> mFakePolicy;
339 sp<InputDispatcher> mDispatcher;
340
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700341 virtual void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800342 mFakePolicy = new FakeInputDispatcherPolicy();
343 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800344 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
345 //Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700346 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800347 }
348
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700349 virtual void TearDown() override {
350 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800351 mFakePolicy.clear();
352 mDispatcher.clear();
353 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700354
355 /**
356 * Used for debugging when writing the test
357 */
358 void dumpDispatcherState() {
359 std::string dump;
360 mDispatcher->dump(dump);
361 std::stringstream ss(dump);
362 std::string to;
363
364 while (std::getline(ss, to, '\n')) {
365 ALOGE("%s", to.c_str());
366 }
367 }
Vishnu Nair958da932020-08-21 17:12:37 -0700368
369 void setFocusedWindow(const sp<InputWindowHandle>& window,
370 const sp<InputWindowHandle>& focusedWindow = nullptr) {
371 FocusRequest request;
372 request.token = window->getToken();
373 if (focusedWindow) {
374 request.focusedToken = focusedWindow->getToken();
375 }
376 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
377 request.displayId = window->getInfo()->displayId;
378 mDispatcher->setFocusedWindow(request);
379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380};
381
382
383TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
384 KeyEvent event;
385
386 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800387 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
388 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600389 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
390 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800391 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700392 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800393 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394 << "Should reject key events with undefined action.";
395
396 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800397 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
398 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600399 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800400 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700401 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800402 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 << "Should reject key events with ACTION_MULTIPLE.";
404}
405
406TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
407 MotionEvent event;
408 PointerProperties pointerProperties[MAX_POINTERS + 1];
409 PointerCoords pointerCoords[MAX_POINTERS + 1];
410 for (int i = 0; i <= MAX_POINTERS; i++) {
411 pointerProperties[i].clear();
412 pointerProperties[i].id = i;
413 pointerCoords[i].clear();
414 }
415
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800416 // Some constants commonly used below
417 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
418 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
419 constexpr int32_t metaState = AMETA_NONE;
420 constexpr MotionClassification classification = MotionClassification::NONE;
421
chaviw9eaa22c2020-07-01 16:21:27 -0700422 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800423 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800424 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700425 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
426 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600427 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700428 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800429 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700430 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800431 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432 << "Should reject motion events with undefined action.";
433
434 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800435 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700436 AMOTION_EVENT_ACTION_POINTER_DOWN |
437 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700438 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
439 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
440 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
441 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800442 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700443 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800444 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445 << "Should reject motion events with pointer down index too large.";
446
Garfield Tanfbe732e2020-01-24 11:26:14 -0800447 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700448 AMOTION_EVENT_ACTION_POINTER_DOWN |
449 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700450 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
451 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
452 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
453 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800454 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700455 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800456 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457 << "Should reject motion events with pointer down index too small.";
458
459 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800460 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700461 AMOTION_EVENT_ACTION_POINTER_UP |
462 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700463 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
464 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
465 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
466 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800467 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700468 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800469 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 << "Should reject motion events with pointer up index too large.";
471
Garfield Tanfbe732e2020-01-24 11:26:14 -0800472 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700473 AMOTION_EVENT_ACTION_POINTER_UP |
474 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700475 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
476 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
477 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
478 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800479 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700480 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800481 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482 << "Should reject motion events with pointer up index too small.";
483
484 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800485 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
486 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700487 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
488 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700489 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800490 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700491 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800492 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 << "Should reject motion events with 0 pointers.";
494
Garfield Tanfbe732e2020-01-24 11:26:14 -0800495 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
496 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700497 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
498 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700499 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800500 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700501 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800502 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 << "Should reject motion events with more than MAX_POINTERS pointers.";
504
505 // Rejects motion events with invalid pointer ids.
506 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800507 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
508 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700509 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
510 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700511 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800512 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700513 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800514 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 << "Should reject motion events with pointer ids less than 0.";
516
517 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800518 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
519 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700520 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
521 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700522 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800523 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700524 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800525 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
527
528 // Rejects motion events with duplicate pointer ids.
529 pointerProperties[0].id = 1;
530 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800531 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
532 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700533 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
534 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700535 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800536 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700537 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800538 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 << "Should reject motion events with duplicate pointer ids.";
540}
541
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800542/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
543
544TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
545 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800546 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800547 mDispatcher->notifyConfigurationChanged(&args);
548 ASSERT_TRUE(mDispatcher->waitForIdle());
549
550 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
551}
552
553TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800554 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
555 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800556 mDispatcher->notifySwitch(&args);
557
558 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
559 args.policyFlags |= POLICY_FLAG_TRUSTED;
560 mFakePolicy->assertNotifySwitchWasCalled(args);
561}
562
Arthur Hungb92218b2018-08-14 12:00:21 +0800563// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700564static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700565static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800566
567class FakeApplicationHandle : public InputApplicationHandle {
568public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700569 FakeApplicationHandle() {
570 mInfo.name = "Fake Application";
571 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500572 mInfo.dispatchingTimeoutMillis =
573 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700574 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800575 virtual ~FakeApplicationHandle() {}
576
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700577 virtual bool updateInfo() override {
Arthur Hungb92218b2018-08-14 12:00:21 +0800578 return true;
579 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700580
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500581 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
582 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700583 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800584};
585
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800586class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800587public:
Garfield Tan15601662020-09-22 15:32:38 -0700588 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800589 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700590 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800591 }
592
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800593 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700594 InputEvent* event;
595 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
596 if (!consumeSeq) {
597 return nullptr;
598 }
599 finishEvent(*consumeSeq);
600 return event;
601 }
602
603 /**
604 * Receive an event without acknowledging it.
605 * Return the sequence number that could later be used to send finished signal.
606 */
607 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800608 uint32_t consumeSeq;
609 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800610
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800611 std::chrono::time_point start = std::chrono::steady_clock::now();
612 status_t status = WOULD_BLOCK;
613 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800614 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800615 &event);
616 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
617 if (elapsed > 100ms) {
618 break;
619 }
620 }
621
622 if (status == WOULD_BLOCK) {
623 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700624 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800625 }
626
627 if (status != OK) {
628 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700629 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800630 }
631 if (event == nullptr) {
632 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700633 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800634 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700635 if (outEvent != nullptr) {
636 *outEvent = event;
637 }
638 return consumeSeq;
639 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800640
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700641 /**
642 * To be used together with "receiveEvent" to complete the consumption of an event.
643 */
644 void finishEvent(uint32_t consumeSeq) {
645 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
646 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800647 }
648
649 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
650 int32_t expectedFlags) {
651 InputEvent* event = consume();
652
653 ASSERT_NE(nullptr, event) << mName.c_str()
654 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800655 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700656 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800657 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800658
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800659 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800660
Tiger Huang8664f8c2018-10-11 19:14:35 +0800661 switch (expectedEventType) {
662 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800663 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
664 EXPECT_EQ(expectedAction, keyEvent.getAction());
665 EXPECT_EQ(expectedFlags, keyEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800666 break;
667 }
668 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800669 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
670 EXPECT_EQ(expectedAction, motionEvent.getAction());
671 EXPECT_EQ(expectedFlags, motionEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800672 break;
673 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100674 case AINPUT_EVENT_TYPE_FOCUS: {
675 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
676 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800677 default: {
678 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
679 }
680 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800681 }
682
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100683 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
684 InputEvent* event = consume();
685 ASSERT_NE(nullptr, event) << mName.c_str()
686 << ": consumer should have returned non-NULL event.";
687 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
688 << "Got " << inputEventTypeToString(event->getType())
689 << " event instead of FOCUS event";
690
691 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
692 << mName.c_str() << ": event displayId should always be NONE.";
693
694 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
695 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
696 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
697 }
698
chaviwd1c23182019-12-20 18:44:56 -0800699 void assertNoEvents() {
700 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700701 if (event == nullptr) {
702 return;
703 }
704 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
705 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
706 ADD_FAILURE() << "Received key event "
707 << KeyEvent::actionToString(keyEvent.getAction());
708 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
709 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
710 ADD_FAILURE() << "Received motion event "
711 << MotionEvent::actionToString(motionEvent.getAction());
712 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
713 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
714 ADD_FAILURE() << "Received focus event, hasFocus = "
715 << (focusEvent.getHasFocus() ? "true" : "false");
716 }
717 FAIL() << mName.c_str()
718 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800719 }
720
721 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
722
723protected:
724 std::unique_ptr<InputConsumer> mConsumer;
725 PreallocatedInputEventFactory mEventFactory;
726
727 std::string mName;
728};
729
730class FakeWindowHandle : public InputWindowHandle {
731public:
732 static const int32_t WIDTH = 600;
733 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800734
Chris Yea209fde2020-07-22 13:54:51 -0700735 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800736 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500737 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800738 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500739 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700740 base::Result<std::unique_ptr<InputChannel>> channel =
741 dispatcher->createInputChannel(name);
742 token = (*channel)->getConnectionToken();
743 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800744 }
745
746 inputApplicationHandle->updateInfo();
747 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
748
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500749 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700750 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800751 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100752 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500753 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
chaviwd1c23182019-12-20 18:44:56 -0800754 mInfo.frameLeft = 0;
755 mInfo.frameTop = 0;
756 mInfo.frameRight = WIDTH;
757 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700758 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800759 mInfo.globalScaleFactor = 1.0;
760 mInfo.touchableRegion.clear();
761 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
762 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700763 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800764 mInfo.hasWallpaper = false;
765 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800766 mInfo.ownerPid = INJECTOR_PID;
767 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800768 mInfo.displayId = displayId;
769 }
770
771 virtual bool updateInfo() { return true; }
772
Vishnu Nair47074b82020-08-14 11:54:47 -0700773 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800774
Vishnu Nair958da932020-08-21 17:12:37 -0700775 void setVisible(bool visible) { mInfo.visible = visible; }
776
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700777 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500778 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700779 }
780
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700781 void setPaused(bool paused) { mInfo.paused = paused; }
782
chaviwd1c23182019-12-20 18:44:56 -0800783 void setFrame(const Rect& frame) {
784 mInfo.frameLeft = frame.left;
785 mInfo.frameTop = frame.top;
786 mInfo.frameRight = frame.right;
787 mInfo.frameBottom = frame.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -0700788 mInfo.transform.set(frame.left, frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800789 mInfo.touchableRegion.clear();
790 mInfo.addTouchableRegion(frame);
791 }
792
Michael Wright44753b12020-07-08 13:48:11 +0100793 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800794
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500795 void setInputFeatures(InputWindowInfo::Feature features) { mInfo.inputFeatures = features; }
796
chaviw9eaa22c2020-07-01 16:21:27 -0700797 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
798 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
799 }
800
801 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700802
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800803 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
804 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
805 expectedFlags);
806 }
807
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700808 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
809 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
810 }
811
Svet Ganov5d3bc372020-01-26 23:11:07 -0800812 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
813 int32_t expectedFlags = 0) {
814 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
815 expectedFlags);
816 }
817
818 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
819 int32_t expectedFlags = 0) {
820 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
821 expectedFlags);
822 }
823
824 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
825 int32_t expectedFlags = 0) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800826 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
827 expectedFlags);
828 }
829
Svet Ganov5d3bc372020-01-26 23:11:07 -0800830 void consumeMotionPointerDown(int32_t pointerIdx,
831 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT, int32_t expectedFlags = 0) {
832 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN
833 | (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
834 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
835 }
836
837 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
838 int32_t expectedFlags = 0) {
839 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP
840 | (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
841 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
842 }
843
844 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
845 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +0000846 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
847 expectedFlags);
848 }
849
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500850 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
851 int32_t expectedFlags = 0) {
852 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
853 expectedFlags);
854 }
855
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100856 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
857 ASSERT_NE(mInputReceiver, nullptr)
858 << "Cannot consume events from a window with no receiver";
859 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
860 }
861
chaviwd1c23182019-12-20 18:44:56 -0800862 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
863 int32_t expectedFlags) {
864 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
865 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
866 expectedFlags);
867 }
868
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700869 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700870 if (mInputReceiver == nullptr) {
871 ADD_FAILURE() << "Invalid receive event on window with no receiver";
872 return std::nullopt;
873 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700874 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700875 }
876
877 void finishEvent(uint32_t sequenceNum) {
878 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
879 mInputReceiver->finishEvent(sequenceNum);
880 }
881
chaviwaf87b3e2019-10-01 16:59:28 -0700882 InputEvent* consume() {
883 if (mInputReceiver == nullptr) {
884 return nullptr;
885 }
886 return mInputReceiver->consume();
887 }
888
Arthur Hungb92218b2018-08-14 12:00:21 +0800889 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500890 if (mInputReceiver == nullptr &&
891 mInfo.inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL)) {
892 return; // Can't receive events if the window does not have input channel
893 }
894 ASSERT_NE(nullptr, mInputReceiver)
895 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -0800896 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +0800897 }
898
chaviwaf87b3e2019-10-01 16:59:28 -0700899 sp<IBinder> getToken() { return mInfo.token; }
900
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100901 const std::string& getName() { return mName; }
902
chaviwd1c23182019-12-20 18:44:56 -0800903private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100904 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -0800905 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700906 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800907};
908
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700909std::atomic<int32_t> FakeWindowHandle::sId{1};
910
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800911static InputEventInjectionResult injectKey(
912 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
913 int32_t displayId = ADISPLAY_ID_NONE,
914 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
915 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800916 KeyEvent event;
917 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
918
919 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800920 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700921 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
922 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +0800923
924 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700925 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
926 injectionTimeout,
927 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
Arthur Hungb92218b2018-08-14 12:00:21 +0800928}
929
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800930static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
931 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700932 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
933}
934
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800935static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
936 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700937 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
938}
939
Garfield Tandf26e862020-07-01 20:18:19 -0700940class PointerBuilder {
941public:
942 PointerBuilder(int32_t id, int32_t toolType) {
943 mProperties.clear();
944 mProperties.id = id;
945 mProperties.toolType = toolType;
946 mCoords.clear();
947 }
948
949 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
950
951 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
952
953 PointerBuilder& axis(int32_t axis, float value) {
954 mCoords.setAxisValue(axis, value);
955 return *this;
956 }
957
958 PointerProperties buildProperties() const { return mProperties; }
959
960 PointerCoords buildCoords() const { return mCoords; }
961
962private:
963 PointerProperties mProperties;
964 PointerCoords mCoords;
965};
966
967class MotionEventBuilder {
968public:
969 MotionEventBuilder(int32_t action, int32_t source) {
970 mAction = action;
971 mSource = source;
972 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
973 }
974
975 MotionEventBuilder& eventTime(nsecs_t eventTime) {
976 mEventTime = eventTime;
977 return *this;
978 }
979
980 MotionEventBuilder& displayId(int32_t displayId) {
981 mDisplayId = displayId;
982 return *this;
983 }
984
985 MotionEventBuilder& actionButton(int32_t actionButton) {
986 mActionButton = actionButton;
987 return *this;
988 }
989
990 MotionEventBuilder& buttonState(int32_t actionButton) {
991 mActionButton = actionButton;
992 return *this;
993 }
994
995 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
996 mRawXCursorPosition = rawXCursorPosition;
997 return *this;
998 }
999
1000 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1001 mRawYCursorPosition = rawYCursorPosition;
1002 return *this;
1003 }
1004
1005 MotionEventBuilder& pointer(PointerBuilder pointer) {
1006 mPointers.push_back(pointer);
1007 return *this;
1008 }
1009
1010 MotionEvent build() {
1011 std::vector<PointerProperties> pointerProperties;
1012 std::vector<PointerCoords> pointerCoords;
1013 for (const PointerBuilder& pointer : mPointers) {
1014 pointerProperties.push_back(pointer.buildProperties());
1015 pointerCoords.push_back(pointer.buildCoords());
1016 }
1017
1018 // Set mouse cursor position for the most common cases to avoid boilerplate.
1019 if (mSource == AINPUT_SOURCE_MOUSE &&
1020 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1021 mPointers.size() == 1) {
1022 mRawXCursorPosition = pointerCoords[0].getX();
1023 mRawYCursorPosition = pointerCoords[0].getY();
1024 }
1025
1026 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001027 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001028 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
1029 mAction, mActionButton, /* flags */ 0, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001030 mButtonState, MotionClassification::NONE, identityTransform,
1031 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
1032 mRawYCursorPosition, mEventTime, mEventTime, mPointers.size(),
1033 pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001034
1035 return event;
1036 }
1037
1038private:
1039 int32_t mAction;
1040 int32_t mSource;
1041 nsecs_t mEventTime;
1042 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1043 int32_t mActionButton{0};
1044 int32_t mButtonState{0};
1045 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1046 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1047
1048 std::vector<PointerBuilder> mPointers;
1049};
1050
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001051static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001052 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1053 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001054 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001055 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1056 injectionTimeout,
1057 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1058}
1059
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001060static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001061 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1062 const PointF& position,
1063 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001064 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1065 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001066 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001068 MotionEvent event = MotionEventBuilder(action, source)
1069 .displayId(displayId)
1070 .eventTime(eventTime)
1071 .rawXCursorPosition(cursorPosition.x)
1072 .rawYCursorPosition(cursorPosition.y)
1073 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1074 .x(position.x)
1075 .y(position.y))
1076 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001077
1078 // Inject event until dispatch out.
Garfield Tandf26e862020-07-01 20:18:19 -07001079 return injectMotionEvent(dispatcher, event);
Arthur Hungb92218b2018-08-14 12:00:21 +08001080}
1081
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001082static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1083 int32_t source, int32_t displayId,
1084 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001085 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001086}
1087
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001088static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1089 int32_t source, int32_t displayId,
1090 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}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001147 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1148 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1149 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001150
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}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001171 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001172 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1173 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001174 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001175
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}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001196 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1197 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001198 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001199
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}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001213 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1214 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1215 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001216
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
Garfield Tandf26e862020-07-01 20:18:19 -07001222TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001223 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001224 sp<FakeWindowHandle> windowLeft =
1225 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1226 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001227 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001228 sp<FakeWindowHandle> windowRight =
1229 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1230 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001231 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001232
1233 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1234
1235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1236
1237 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001238 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001239 injectMotionEvent(mDispatcher,
1240 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1241 AINPUT_SOURCE_MOUSE)
1242 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1243 .x(900)
1244 .y(400))
1245 .build()));
1246 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1247 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1248 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1249 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1250
1251 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001253 injectMotionEvent(mDispatcher,
1254 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1255 AINPUT_SOURCE_MOUSE)
1256 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1257 .x(300)
1258 .y(400))
1259 .build()));
1260 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1261 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1262 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1263 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1264 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1265 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1266
1267 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001268 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001269 injectMotionEvent(mDispatcher,
1270 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1271 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1272 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1273 .x(300)
1274 .y(400))
1275 .build()));
1276 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1277
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001279 injectMotionEvent(mDispatcher,
1280 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1281 AINPUT_SOURCE_MOUSE)
1282 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1283 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1284 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1285 .x(300)
1286 .y(400))
1287 .build()));
1288 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1289 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1290
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001292 injectMotionEvent(mDispatcher,
1293 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1294 AINPUT_SOURCE_MOUSE)
1295 .buttonState(0)
1296 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1297 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1298 .x(300)
1299 .y(400))
1300 .build()));
1301 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1302 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1303
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001305 injectMotionEvent(mDispatcher,
1306 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1307 .buttonState(0)
1308 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1309 .x(300)
1310 .y(400))
1311 .build()));
1312 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1313
1314 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001315 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001316 injectMotionEvent(mDispatcher,
1317 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1318 AINPUT_SOURCE_MOUSE)
1319 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1320 .x(900)
1321 .y(400))
1322 .build()));
1323 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1324 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1325 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1326 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1327 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1328 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1329}
1330
1331// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1332// directly in this test.
1333TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001334 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001335 sp<FakeWindowHandle> window =
1336 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1337 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001338 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001339
1340 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1341
1342 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1343
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001345 injectMotionEvent(mDispatcher,
1346 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1347 AINPUT_SOURCE_MOUSE)
1348 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1349 .x(300)
1350 .y(400))
1351 .build()));
1352 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1353 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1354
1355 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001357 injectMotionEvent(mDispatcher,
1358 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1359 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1360 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1361 .x(300)
1362 .y(400))
1363 .build()));
1364 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1365
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001367 injectMotionEvent(mDispatcher,
1368 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1369 AINPUT_SOURCE_MOUSE)
1370 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1371 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1372 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1373 .x(300)
1374 .y(400))
1375 .build()));
1376 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1377 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1378
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001380 injectMotionEvent(mDispatcher,
1381 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1382 AINPUT_SOURCE_MOUSE)
1383 .buttonState(0)
1384 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1385 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1386 .x(300)
1387 .y(400))
1388 .build()));
1389 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1390 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1391
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001393 injectMotionEvent(mDispatcher,
1394 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1395 .buttonState(0)
1396 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1397 .x(300)
1398 .y(400))
1399 .build()));
1400 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1401
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001402 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001403 injectMotionEvent(mDispatcher,
1404 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1405 AINPUT_SOURCE_MOUSE)
1406 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1407 .x(300)
1408 .y(400))
1409 .build()));
1410 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1411 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1412}
1413
Garfield Tan00f511d2019-06-12 16:55:40 -07001414TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001415 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001416
1417 sp<FakeWindowHandle> windowLeft =
1418 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1419 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001420 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001421 sp<FakeWindowHandle> windowRight =
1422 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1423 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001424 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001425
1426 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1427
Arthur Hung72d8dc32020-03-28 00:48:39 +00001428 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001429
1430 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1431 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001433 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001434 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001435 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001436 windowRight->assertNoEvents();
1437}
1438
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001439TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001440 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001441 sp<FakeWindowHandle> window =
1442 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001443 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001444
Arthur Hung72d8dc32020-03-28 00:48:39 +00001445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001446 setFocusedWindow(window);
1447
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001448 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001449
1450 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1451 mDispatcher->notifyKey(&keyArgs);
1452
1453 // Window should receive key down event.
1454 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1455
1456 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1457 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001458 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001459 mDispatcher->notifyDeviceReset(&args);
1460 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1461 AKEY_EVENT_FLAG_CANCELED);
1462}
1463
1464TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001465 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001466 sp<FakeWindowHandle> window =
1467 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1468
Arthur Hung72d8dc32020-03-28 00:48:39 +00001469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001470
1471 NotifyMotionArgs motionArgs =
1472 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1473 ADISPLAY_ID_DEFAULT);
1474 mDispatcher->notifyMotion(&motionArgs);
1475
1476 // Window should receive motion down event.
1477 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1478
1479 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1480 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001481 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001482 mDispatcher->notifyDeviceReset(&args);
1483 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1484 0 /*expectedFlags*/);
1485}
1486
Svet Ganov5d3bc372020-01-26 23:11:07 -08001487TEST_F(InputDispatcherTest, TransferTouchFocus_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001488 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001489
1490 // Create a couple of windows
1491 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1492 "First Window", ADISPLAY_ID_DEFAULT);
1493 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1494 "Second Window", ADISPLAY_ID_DEFAULT);
1495
1496 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001498
1499 // Send down to the first window
1500 NotifyMotionArgs downMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1501 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1502 mDispatcher->notifyMotion(&downMotionArgs);
1503 // Only the first window should get the down event
1504 firstWindow->consumeMotionDown();
1505 secondWindow->assertNoEvents();
1506
1507 // Transfer touch focus to the second window
1508 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1509 // The first window gets cancel and the second gets down
1510 firstWindow->consumeMotionCancel();
1511 secondWindow->consumeMotionDown();
1512
1513 // Send up event to the second window
1514 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1515 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1516 mDispatcher->notifyMotion(&upMotionArgs);
1517 // The first window gets no events and the second gets up
1518 firstWindow->assertNoEvents();
1519 secondWindow->consumeMotionUp();
1520}
1521
1522TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointerNoSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001523 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001524
1525 PointF touchPoint = {10, 10};
1526
1527 // Create a couple of windows
1528 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1529 "First Window", ADISPLAY_ID_DEFAULT);
1530 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1531 "Second Window", ADISPLAY_ID_DEFAULT);
1532
1533 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001534 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001535
1536 // Send down to the first window
1537 NotifyMotionArgs downMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1538 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint});
1539 mDispatcher->notifyMotion(&downMotionArgs);
1540 // Only the first window should get the down event
1541 firstWindow->consumeMotionDown();
1542 secondWindow->assertNoEvents();
1543
1544 // Send pointer down to the first window
1545 NotifyMotionArgs pointerDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN
1546 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1547 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint, touchPoint});
1548 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1549 // Only the first window should get the pointer down event
1550 firstWindow->consumeMotionPointerDown(1);
1551 secondWindow->assertNoEvents();
1552
1553 // Transfer touch focus to the second window
1554 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1555 // The first window gets cancel and the second gets down and pointer down
1556 firstWindow->consumeMotionCancel();
1557 secondWindow->consumeMotionDown();
1558 secondWindow->consumeMotionPointerDown(1);
1559
1560 // Send pointer up to the second window
1561 NotifyMotionArgs pointerUpMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP
1562 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1563 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint, touchPoint});
1564 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1565 // The first window gets nothing and the second gets pointer up
1566 firstWindow->assertNoEvents();
1567 secondWindow->consumeMotionPointerUp(1);
1568
1569 // Send up event to the second window
1570 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1571 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1572 mDispatcher->notifyMotion(&upMotionArgs);
1573 // The first window gets nothing and the second gets up
1574 firstWindow->assertNoEvents();
1575 secondWindow->consumeMotionUp();
1576}
1577
1578TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001579 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001580
1581 // Create a non touch modal window that supports split touch
1582 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1583 "First Window", ADISPLAY_ID_DEFAULT);
1584 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001585 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1586 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001587
1588 // Create a non touch modal window that supports split touch
1589 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1590 "Second Window", ADISPLAY_ID_DEFAULT);
1591 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001592 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1593 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001594
1595 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001597
1598 PointF pointInFirst = {300, 200};
1599 PointF pointInSecond = {300, 600};
1600
1601 // Send down to the first window
1602 NotifyMotionArgs firstDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1603 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst});
1604 mDispatcher->notifyMotion(&firstDownMotionArgs);
1605 // Only the first window should get the down event
1606 firstWindow->consumeMotionDown();
1607 secondWindow->assertNoEvents();
1608
1609 // Send down to the second window
1610 NotifyMotionArgs secondDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN
1611 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1612 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst, pointInSecond});
1613 mDispatcher->notifyMotion(&secondDownMotionArgs);
1614 // The first window gets a move and the second a down
1615 firstWindow->consumeMotionMove();
1616 secondWindow->consumeMotionDown();
1617
1618 // Transfer touch focus to the second window
1619 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1620 // The first window gets cancel and the new gets pointer down (it already saw down)
1621 firstWindow->consumeMotionCancel();
1622 secondWindow->consumeMotionPointerDown(1);
1623
1624 // Send pointer up to the second window
1625 NotifyMotionArgs pointerUpMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP
1626 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1627 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst, pointInSecond});
1628 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1629 // The first window gets nothing and the second gets pointer up
1630 firstWindow->assertNoEvents();
1631 secondWindow->consumeMotionPointerUp(1);
1632
1633 // Send up event to the second window
1634 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1635 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1636 mDispatcher->notifyMotion(&upMotionArgs);
1637 // The first window gets nothing and the second gets up
1638 firstWindow->assertNoEvents();
1639 secondWindow->consumeMotionUp();
1640}
1641
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001642TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001643 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001644 sp<FakeWindowHandle> window =
1645 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1646
Vishnu Nair47074b82020-08-14 11:54:47 -07001647 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001649 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001650
1651 window->consumeFocusEvent(true);
1652
1653 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1654 mDispatcher->notifyKey(&keyArgs);
1655
1656 // Window should receive key down event.
1657 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1658}
1659
1660TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001661 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001662 sp<FakeWindowHandle> window =
1663 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1664
Arthur Hung72d8dc32020-03-28 00:48:39 +00001665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001666
1667 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1668 mDispatcher->notifyKey(&keyArgs);
1669 mDispatcher->waitForIdle();
1670
1671 window->assertNoEvents();
1672}
1673
1674// If a window is touchable, but does not have focus, it should receive motion events, but not keys
1675TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07001676 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001677 sp<FakeWindowHandle> window =
1678 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1679
Arthur Hung72d8dc32020-03-28 00:48:39 +00001680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001681
1682 // Send key
1683 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1684 mDispatcher->notifyKey(&keyArgs);
1685 // Send motion
1686 NotifyMotionArgs motionArgs =
1687 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1688 ADISPLAY_ID_DEFAULT);
1689 mDispatcher->notifyMotion(&motionArgs);
1690
1691 // Window should receive only the motion event
1692 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1693 window->assertNoEvents(); // Key event or focus event will not be received
1694}
1695
chaviwd1c23182019-12-20 18:44:56 -08001696class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00001697public:
1698 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08001699 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07001700 base::Result<std::unique_ptr<InputChannel>> channel =
1701 dispatcher->createInputMonitor(displayId, isGestureMonitor, name);
1702 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00001703 }
1704
chaviwd1c23182019-12-20 18:44:56 -08001705 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
1706
1707 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1708 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
1709 expectedDisplayId, expectedFlags);
1710 }
1711
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001712 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
1713
1714 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
1715
chaviwd1c23182019-12-20 18:44:56 -08001716 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1717 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
1718 expectedDisplayId, expectedFlags);
1719 }
1720
1721 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1722 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
1723 expectedDisplayId, expectedFlags);
1724 }
1725
1726 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
1727
1728private:
1729 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00001730};
1731
1732// Tests for gesture monitors
1733TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001734 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001735 sp<FakeWindowHandle> window =
1736 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001737 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001738
chaviwd1c23182019-12-20 18:44:56 -08001739 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1740 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001741
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001742 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001743 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001744 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001745 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001746 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001747}
1748
1749TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001750 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001751 sp<FakeWindowHandle> window =
1752 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1753
1754 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001755 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001756
Arthur Hung72d8dc32020-03-28 00:48:39 +00001757 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001758 setFocusedWindow(window);
1759
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001760 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001761
chaviwd1c23182019-12-20 18:44:56 -08001762 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1763 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001764
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
1766 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001767 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001768 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00001769}
1770
1771TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001772 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001773 sp<FakeWindowHandle> window =
1774 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001775 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001776
chaviwd1c23182019-12-20 18:44:56 -08001777 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1778 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001779
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001781 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001782 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001783 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001784 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001785
1786 window->releaseChannel();
1787
chaviwd1c23182019-12-20 18:44:56 -08001788 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00001789
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001791 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001792 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08001793 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001794}
1795
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001796TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
1797 FakeMonitorReceiver monitor =
1798 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
1799 true /*isGestureMonitor*/);
1800
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001801 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001802 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
1803 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
1804 ASSERT_TRUE(consumeSeq);
1805
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001806 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(DISPATCHING_TIMEOUT,
1807 monitor.getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001808 monitor.finishEvent(*consumeSeq);
1809 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001810 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(monitor.getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001811}
1812
chaviw81e2bb92019-12-18 15:03:51 -08001813TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001814 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08001815 sp<FakeWindowHandle> window =
1816 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1817
Arthur Hung72d8dc32020-03-28 00:48:39 +00001818 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08001819
1820 NotifyMotionArgs motionArgs =
1821 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1822 ADISPLAY_ID_DEFAULT);
1823
1824 mDispatcher->notifyMotion(&motionArgs);
1825 // Window should receive motion down event.
1826 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1827
1828 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001829 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08001830 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1831 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
1832 motionArgs.pointerCoords[0].getX() - 10);
1833
1834 mDispatcher->notifyMotion(&motionArgs);
1835 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
1836 0 /*expectedFlags*/);
1837}
1838
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001839/**
1840 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
1841 * the device default right away. In the test scenario, we check both the default value,
1842 * and the action of enabling / disabling.
1843 */
1844TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07001845 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001846 sp<FakeWindowHandle> window =
1847 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1848
1849 // Set focused application.
1850 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001851 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001852
1853 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00001854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001855 setFocusedWindow(window);
1856
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001857 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1858
1859 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07001860 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001862 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
1863
1864 SCOPED_TRACE("Disable touch mode");
1865 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07001866 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001867 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001868 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001869 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
1870
1871 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07001872 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001873 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001874 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
1875
1876 SCOPED_TRACE("Enable touch mode again");
1877 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07001878 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001880 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001881 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1882
1883 window->assertNoEvents();
1884}
1885
Gang Wange9087892020-01-07 12:17:14 -05001886TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001887 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05001888 sp<FakeWindowHandle> window =
1889 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1890
1891 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001892 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05001893
Arthur Hung72d8dc32020-03-28 00:48:39 +00001894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001895 setFocusedWindow(window);
1896
Gang Wange9087892020-01-07 12:17:14 -05001897 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1898
1899 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
1900 mDispatcher->notifyKey(&keyArgs);
1901
1902 InputEvent* event = window->consume();
1903 ASSERT_NE(event, nullptr);
1904
1905 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
1906 ASSERT_NE(verified, nullptr);
1907 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
1908
1909 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
1910 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
1911 ASSERT_EQ(keyArgs.source, verified->source);
1912 ASSERT_EQ(keyArgs.displayId, verified->displayId);
1913
1914 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
1915
1916 ASSERT_EQ(keyArgs.action, verifiedKey.action);
1917 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05001918 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
1919 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
1920 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
1921 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
1922 ASSERT_EQ(0, verifiedKey.repeatCount);
1923}
1924
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08001925TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001926 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08001927 sp<FakeWindowHandle> window =
1928 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1929
1930 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1931
Arthur Hung72d8dc32020-03-28 00:48:39 +00001932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08001933
1934 NotifyMotionArgs motionArgs =
1935 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1936 ADISPLAY_ID_DEFAULT);
1937 mDispatcher->notifyMotion(&motionArgs);
1938
1939 InputEvent* event = window->consume();
1940 ASSERT_NE(event, nullptr);
1941
1942 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
1943 ASSERT_NE(verified, nullptr);
1944 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
1945
1946 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
1947 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
1948 EXPECT_EQ(motionArgs.source, verified->source);
1949 EXPECT_EQ(motionArgs.displayId, verified->displayId);
1950
1951 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
1952
1953 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
1954 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
1955 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
1956 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
1957 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
1958 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
1959 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
1960}
1961
chaviw09c8d2d2020-08-24 15:48:26 -07001962/**
1963 * Ensure that separate calls to sign the same data are generating the same key.
1964 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
1965 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
1966 * tests.
1967 */
1968TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
1969 KeyEvent event = getTestKeyEvent();
1970 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
1971
1972 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
1973 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
1974 ASSERT_EQ(hmac1, hmac2);
1975}
1976
1977/**
1978 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
1979 */
1980TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
1981 KeyEvent event = getTestKeyEvent();
1982 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
1983 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
1984
1985 verifiedEvent.deviceId += 1;
1986 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
1987
1988 verifiedEvent.source += 1;
1989 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
1990
1991 verifiedEvent.eventTimeNanos += 1;
1992 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
1993
1994 verifiedEvent.displayId += 1;
1995 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
1996
1997 verifiedEvent.action += 1;
1998 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
1999
2000 verifiedEvent.downTimeNanos += 1;
2001 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2002
2003 verifiedEvent.flags += 1;
2004 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2005
2006 verifiedEvent.keyCode += 1;
2007 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2008
2009 verifiedEvent.scanCode += 1;
2010 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2011
2012 verifiedEvent.metaState += 1;
2013 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2014
2015 verifiedEvent.repeatCount += 1;
2016 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2017}
2018
Vishnu Nair958da932020-08-21 17:12:37 -07002019TEST_F(InputDispatcherTest, SetFocusedWindow) {
2020 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2021 sp<FakeWindowHandle> windowTop =
2022 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2023 sp<FakeWindowHandle> windowSecond =
2024 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2025 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2026
2027 // Top window is also focusable but is not granted focus.
2028 windowTop->setFocusable(true);
2029 windowSecond->setFocusable(true);
2030 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2031 setFocusedWindow(windowSecond);
2032
2033 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002034 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2035 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002036
2037 // Focused window should receive event.
2038 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2039 windowTop->assertNoEvents();
2040}
2041
2042TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2043 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2044 sp<FakeWindowHandle> window =
2045 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2046 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2047
2048 window->setFocusable(true);
2049 // Release channel for window is no longer valid.
2050 window->releaseChannel();
2051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2052 setFocusedWindow(window);
2053
2054 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002055 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2056 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002057
2058 // window channel is invalid, so it should not receive any input event.
2059 window->assertNoEvents();
2060}
2061
2062TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2063 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2064 sp<FakeWindowHandle> window =
2065 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2066 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2067
2068 // Window is not focusable.
2069 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2070 setFocusedWindow(window);
2071
2072 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002073 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2074 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002075
2076 // window is invalid, so it should not receive any input event.
2077 window->assertNoEvents();
2078}
2079
2080TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2081 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2082 sp<FakeWindowHandle> windowTop =
2083 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2084 sp<FakeWindowHandle> windowSecond =
2085 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2086 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2087
2088 windowTop->setFocusable(true);
2089 windowSecond->setFocusable(true);
2090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2091 setFocusedWindow(windowTop);
2092 windowTop->consumeFocusEvent(true);
2093
2094 setFocusedWindow(windowSecond, windowTop);
2095 windowSecond->consumeFocusEvent(true);
2096 windowTop->consumeFocusEvent(false);
2097
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2099 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002100
2101 // Focused window should receive event.
2102 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2103}
2104
2105TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2106 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2107 sp<FakeWindowHandle> windowTop =
2108 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2109 sp<FakeWindowHandle> windowSecond =
2110 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2111 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2112
2113 windowTop->setFocusable(true);
2114 windowSecond->setFocusable(true);
2115 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2116 setFocusedWindow(windowSecond, windowTop);
2117
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002118 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2119 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002120
2121 // Event should be dropped.
2122 windowTop->assertNoEvents();
2123 windowSecond->assertNoEvents();
2124}
2125
2126TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2127 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2128 sp<FakeWindowHandle> window =
2129 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2130 sp<FakeWindowHandle> previousFocusedWindow =
2131 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2132 ADISPLAY_ID_DEFAULT);
2133 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2134
2135 window->setFocusable(true);
2136 previousFocusedWindow->setFocusable(true);
2137 window->setVisible(false);
2138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2139 setFocusedWindow(previousFocusedWindow);
2140 previousFocusedWindow->consumeFocusEvent(true);
2141
2142 // Requesting focus on invisible window takes focus from currently focused window.
2143 setFocusedWindow(window);
2144 previousFocusedWindow->consumeFocusEvent(false);
2145
2146 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002147 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002148 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002149 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002150
2151 // Window does not get focus event or key down.
2152 window->assertNoEvents();
2153
2154 // Window becomes visible.
2155 window->setVisible(true);
2156 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2157
2158 // Window receives focus event.
2159 window->consumeFocusEvent(true);
2160 // Focused window receives key down.
2161 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2162}
2163
Garfield Tan1c7bc862020-01-28 13:24:04 -08002164class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2165protected:
2166 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2167 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2168
Chris Yea209fde2020-07-22 13:54:51 -07002169 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002170 sp<FakeWindowHandle> mWindow;
2171
2172 virtual void SetUp() override {
2173 mFakePolicy = new FakeInputDispatcherPolicy();
2174 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2175 mDispatcher = new InputDispatcher(mFakePolicy);
2176 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2177 ASSERT_EQ(OK, mDispatcher->start());
2178
2179 setUpWindow();
2180 }
2181
2182 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002183 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002184 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2185
Vishnu Nair47074b82020-08-14 11:54:47 -07002186 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002187 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002188 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002189 mWindow->consumeFocusEvent(true);
2190 }
2191
Chris Ye2ad95392020-09-01 13:44:44 -07002192 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002193 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002194 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002195 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2196 mDispatcher->notifyKey(&keyArgs);
2197
2198 // Window should receive key down event.
2199 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2200 }
2201
2202 void expectKeyRepeatOnce(int32_t repeatCount) {
2203 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2204 InputEvent* repeatEvent = mWindow->consume();
2205 ASSERT_NE(nullptr, repeatEvent);
2206
2207 uint32_t eventType = repeatEvent->getType();
2208 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2209
2210 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2211 uint32_t eventAction = repeatKeyEvent->getAction();
2212 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2213 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2214 }
2215
Chris Ye2ad95392020-09-01 13:44:44 -07002216 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002217 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002218 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002219 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2220 mDispatcher->notifyKey(&keyArgs);
2221
2222 // Window should receive key down event.
2223 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2224 0 /*expectedFlags*/);
2225 }
2226};
2227
2228TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002229 sendAndConsumeKeyDown(1 /* deviceId */);
2230 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2231 expectKeyRepeatOnce(repeatCount);
2232 }
2233}
2234
2235TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2236 sendAndConsumeKeyDown(1 /* deviceId */);
2237 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2238 expectKeyRepeatOnce(repeatCount);
2239 }
2240 sendAndConsumeKeyDown(2 /* deviceId */);
2241 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002242 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2243 expectKeyRepeatOnce(repeatCount);
2244 }
2245}
2246
2247TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002248 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002249 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002250 sendAndConsumeKeyUp(1 /* deviceId */);
2251 mWindow->assertNoEvents();
2252}
2253
2254TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2255 sendAndConsumeKeyDown(1 /* deviceId */);
2256 expectKeyRepeatOnce(1 /*repeatCount*/);
2257 sendAndConsumeKeyDown(2 /* deviceId */);
2258 expectKeyRepeatOnce(1 /*repeatCount*/);
2259 // Stale key up from device 1.
2260 sendAndConsumeKeyUp(1 /* deviceId */);
2261 // Device 2 is still down, keep repeating
2262 expectKeyRepeatOnce(2 /*repeatCount*/);
2263 expectKeyRepeatOnce(3 /*repeatCount*/);
2264 // Device 2 key up
2265 sendAndConsumeKeyUp(2 /* deviceId */);
2266 mWindow->assertNoEvents();
2267}
2268
2269TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2270 sendAndConsumeKeyDown(1 /* deviceId */);
2271 expectKeyRepeatOnce(1 /*repeatCount*/);
2272 sendAndConsumeKeyDown(2 /* deviceId */);
2273 expectKeyRepeatOnce(1 /*repeatCount*/);
2274 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2275 sendAndConsumeKeyUp(2 /* deviceId */);
2276 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002277 mWindow->assertNoEvents();
2278}
2279
2280TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002281 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002282 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2283 InputEvent* repeatEvent = mWindow->consume();
2284 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2285 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2286 IdGenerator::getSource(repeatEvent->getId()));
2287 }
2288}
2289
2290TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002291 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002292
2293 std::unordered_set<int32_t> idSet;
2294 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2295 InputEvent* repeatEvent = mWindow->consume();
2296 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2297 int32_t id = repeatEvent->getId();
2298 EXPECT_EQ(idSet.end(), idSet.find(id));
2299 idSet.insert(id);
2300 }
2301}
2302
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002303/* Test InputDispatcher for MultiDisplay */
2304class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2305public:
2306 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002307 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002308 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002309
Chris Yea209fde2020-07-22 13:54:51 -07002310 application1 = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002311 windowInPrimary = new FakeWindowHandle(application1, mDispatcher, "D_1",
2312 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002313
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002314 // Set focus window for primary display, but focused display would be second one.
2315 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002316 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002318 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002319 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002320
Chris Yea209fde2020-07-22 13:54:51 -07002321 application2 = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002322 windowInSecondary = new FakeWindowHandle(application2, mDispatcher, "D_2",
2323 SECOND_DISPLAY_ID);
2324 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002325 // Set focus display to second one.
2326 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2327 // Set focus window for second display.
2328 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002329 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002330 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002331 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002332 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002333 }
2334
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002335 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002336 InputDispatcherTest::TearDown();
2337
Chris Yea209fde2020-07-22 13:54:51 -07002338 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002339 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002340 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002341 windowInSecondary.clear();
2342 }
2343
2344protected:
Chris Yea209fde2020-07-22 13:54:51 -07002345 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002346 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002347 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002348 sp<FakeWindowHandle> windowInSecondary;
2349};
2350
2351TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2352 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2354 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2355 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002356 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002357 windowInSecondary->assertNoEvents();
2358
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002359 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2361 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2362 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002363 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002364 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002365}
2366
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002367TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002368 // Test inject a key down with display id specified.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2370 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002371 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002372 windowInSecondary->assertNoEvents();
2373
2374 // Test inject a key down without display id specified.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002375 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2376 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002377 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002378 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002379
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002380 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002381 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002382
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002383 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002384 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2385 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002386
2387 // Test inject a key down, should timeout because of no target window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002388 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2389 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08002390 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002391 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002392 windowInSecondary->assertNoEvents();
2393}
2394
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002395// Test per-display input monitors for motion event.
2396TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002397 FakeMonitorReceiver monitorInPrimary =
2398 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2399 FakeMonitorReceiver monitorInSecondary =
2400 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002401
2402 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2404 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2405 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002406 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002407 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002408 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002409 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002410
2411 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2413 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2414 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002415 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002416 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002417 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08002418 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002419
2420 // Test inject a non-pointer motion event.
2421 // If specific a display, it will dispatch to the focused window of particular display,
2422 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002423 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2424 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
2425 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002426 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002427 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002428 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002429 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002430}
2431
2432// Test per-display input monitors for key event.
2433TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
2434 //Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08002435 FakeMonitorReceiver monitorInPrimary =
2436 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2437 FakeMonitorReceiver monitorInSecondary =
2438 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002439
2440 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2442 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002443 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002444 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002445 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002446 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002447}
2448
Vishnu Nair958da932020-08-21 17:12:37 -07002449TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
2450 sp<FakeWindowHandle> secondWindowInPrimary =
2451 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2452 secondWindowInPrimary->setFocusable(true);
2453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
2454 setFocusedWindow(secondWindowInPrimary);
2455 windowInPrimary->consumeFocusEvent(false);
2456 secondWindowInPrimary->consumeFocusEvent(true);
2457
2458 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002459 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2460 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002461 windowInPrimary->assertNoEvents();
2462 windowInSecondary->assertNoEvents();
2463 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2464}
2465
Jackal Guof9696682018-10-05 12:23:23 +08002466class InputFilterTest : public InputDispatcherTest {
2467protected:
2468 static constexpr int32_t SECOND_DISPLAY_ID = 1;
2469
2470 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
2471 NotifyMotionArgs motionArgs;
2472
2473 motionArgs = generateMotionArgs(
2474 AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
2475 mDispatcher->notifyMotion(&motionArgs);
2476 motionArgs = generateMotionArgs(
2477 AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
2478 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002479 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002480 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002481 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002482 } else {
2483 mFakePolicy->assertFilterInputEventWasNotCalled();
2484 }
2485 }
2486
2487 void testNotifyKey(bool expectToBeFiltered) {
2488 NotifyKeyArgs keyArgs;
2489
2490 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2491 mDispatcher->notifyKey(&keyArgs);
2492 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
2493 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002494 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002495
2496 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002497 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002498 } else {
2499 mFakePolicy->assertFilterInputEventWasNotCalled();
2500 }
2501 }
2502};
2503
2504// Test InputFilter for MotionEvent
2505TEST_F(InputFilterTest, MotionEvent_InputFilter) {
2506 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
2507 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2508 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2509
2510 // Enable InputFilter
2511 mDispatcher->setInputFilterEnabled(true);
2512 // Test touch on both primary and second display, and check if both events are filtered.
2513 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
2514 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
2515
2516 // Disable InputFilter
2517 mDispatcher->setInputFilterEnabled(false);
2518 // Test touch on both primary and second display, and check if both events aren't filtered.
2519 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2520 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2521}
2522
2523// Test InputFilter for KeyEvent
2524TEST_F(InputFilterTest, KeyEvent_InputFilter) {
2525 // Since the InputFilter is disabled by default, check if key event aren't filtered.
2526 testNotifyKey(/*expectToBeFiltered*/ false);
2527
2528 // Enable InputFilter
2529 mDispatcher->setInputFilterEnabled(true);
2530 // Send a key event, and check if it is filtered.
2531 testNotifyKey(/*expectToBeFiltered*/ true);
2532
2533 // Disable InputFilter
2534 mDispatcher->setInputFilterEnabled(false);
2535 // Send a key event, and check if it isn't filtered.
2536 testNotifyKey(/*expectToBeFiltered*/ false);
2537}
2538
chaviwfd6d3512019-03-25 13:23:49 -07002539class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002540 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07002541 InputDispatcherTest::SetUp();
2542
Chris Yea209fde2020-07-22 13:54:51 -07002543 std::shared_ptr<FakeApplicationHandle> application =
2544 std::make_shared<FakeApplicationHandle>();
chaviwfd6d3512019-03-25 13:23:49 -07002545 mUnfocusedWindow = new FakeWindowHandle(application, mDispatcher, "Top",
2546 ADISPLAY_ID_DEFAULT);
2547 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
2548 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2549 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002550 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002551
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002552 mFocusedWindow =
2553 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2554 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01002555 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002556
2557 // Set focused application.
2558 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002559 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07002560
2561 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002562 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002563 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002564 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07002565 }
2566
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002567 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07002568 InputDispatcherTest::TearDown();
2569
2570 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002571 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07002572 }
2573
2574protected:
2575 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002576 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002577 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07002578};
2579
2580// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2581// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
2582// the onPointerDownOutsideFocus callback.
2583TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002585 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2586 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002587 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002588 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002589
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002590 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07002591 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
2592}
2593
2594// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
2595// DOWN on the window that doesn't have focus. Ensure no window received the
2596// onPointerDownOutsideFocus callback.
2597TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002599 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002600 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002601 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002602
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002603 ASSERT_TRUE(mDispatcher->waitForIdle());
2604 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002605}
2606
2607// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
2608// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
2609TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2611 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002612 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002613
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002614 ASSERT_TRUE(mDispatcher->waitForIdle());
2615 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002616}
2617
2618// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2619// DOWN on the window that already has focus. Ensure no window received the
2620// onPointerDownOutsideFocus callback.
2621TEST_F(InputDispatcherOnPointerDownOutsideFocus,
2622 OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002624 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002625 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002626 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002627 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002628
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002629 ASSERT_TRUE(mDispatcher->waitForIdle());
2630 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002631}
2632
chaviwaf87b3e2019-10-01 16:59:28 -07002633// These tests ensures we can send touch events to a single client when there are multiple input
2634// windows that point to the same client token.
2635class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
2636 virtual void SetUp() override {
2637 InputDispatcherTest::SetUp();
2638
Chris Yea209fde2020-07-22 13:54:51 -07002639 std::shared_ptr<FakeApplicationHandle> application =
2640 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07002641 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
2642 ADISPLAY_ID_DEFAULT);
2643 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
2644 // 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 +01002645 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2646 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002647 mWindow1->setFrame(Rect(0, 0, 100, 100));
2648
2649 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
2650 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01002651 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2652 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002653 mWindow2->setFrame(Rect(100, 100, 200, 200));
2654
Arthur Hung72d8dc32020-03-28 00:48:39 +00002655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07002656 }
2657
2658protected:
2659 sp<FakeWindowHandle> mWindow1;
2660 sp<FakeWindowHandle> mWindow2;
2661
2662 // Helper function to convert the point from screen coordinates into the window's space
2663 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07002664 vec2 vals = windowInfo->transform.transform(point.x, point.y);
2665 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07002666 }
2667
2668 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
2669 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002670 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07002671 InputEvent* event = window->consume();
2672
2673 ASSERT_NE(nullptr, event) << name.c_str()
2674 << ": consumer should have returned non-NULL event.";
2675
2676 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2677 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2678 << " event, got " << inputEventTypeToString(event->getType()) << " event";
2679
2680 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2681 EXPECT_EQ(expectedAction, motionEvent.getAction());
2682
2683 for (size_t i = 0; i < points.size(); i++) {
2684 float expectedX = points[i].x;
2685 float expectedY = points[i].y;
2686
2687 EXPECT_EQ(expectedX, motionEvent.getX(i))
2688 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
2689 << ", got " << motionEvent.getX(i);
2690 EXPECT_EQ(expectedY, motionEvent.getY(i))
2691 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
2692 << ", got " << motionEvent.getY(i);
2693 }
2694 }
chaviw9eaa22c2020-07-01 16:21:27 -07002695
2696 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
2697 std::vector<PointF> expectedPoints) {
2698 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
2699 ADISPLAY_ID_DEFAULT, touchedPoints);
2700 mDispatcher->notifyMotion(&motionArgs);
2701
2702 // Always consume from window1 since it's the window that has the InputReceiver
2703 consumeMotionEvent(mWindow1, action, expectedPoints);
2704 }
chaviwaf87b3e2019-10-01 16:59:28 -07002705};
2706
2707TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
2708 // Touch Window 1
2709 PointF touchedPoint = {10, 10};
2710 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002711 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002712
2713 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07002714 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002715
2716 // Touch Window 2
2717 touchedPoint = {150, 150};
2718 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002719 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002720}
2721
chaviw9eaa22c2020-07-01 16:21:27 -07002722TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
2723 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07002724 mWindow2->setWindowScale(0.5f, 0.5f);
2725
2726 // Touch Window 1
2727 PointF touchedPoint = {10, 10};
2728 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002729 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002730 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07002731 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002732
2733 // Touch Window 2
2734 touchedPoint = {150, 150};
2735 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002736 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
2737 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002738
chaviw9eaa22c2020-07-01 16:21:27 -07002739 // Update the transform so rotation is set
2740 mWindow2->setWindowTransform(0, -1, 1, 0);
2741 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
2742 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002743}
2744
chaviw9eaa22c2020-07-01 16:21:27 -07002745TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002746 mWindow2->setWindowScale(0.5f, 0.5f);
2747
2748 // Touch Window 1
2749 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2750 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002751 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002752
2753 // Touch Window 2
2754 int32_t actionPointerDown =
2755 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002756 touchedPoints.push_back(PointF{150, 150});
2757 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2758 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002759
chaviw9eaa22c2020-07-01 16:21:27 -07002760 // Release Window 2
2761 int32_t actionPointerUp =
2762 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2763 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
2764 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002765
chaviw9eaa22c2020-07-01 16:21:27 -07002766 // Update the transform so rotation is set for Window 2
2767 mWindow2->setWindowTransform(0, -1, 1, 0);
2768 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2769 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002770}
2771
chaviw9eaa22c2020-07-01 16:21:27 -07002772TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002773 mWindow2->setWindowScale(0.5f, 0.5f);
2774
2775 // Touch Window 1
2776 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2777 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002778 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002779
2780 // Touch Window 2
2781 int32_t actionPointerDown =
2782 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002783 touchedPoints.push_back(PointF{150, 150});
2784 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002785
chaviw9eaa22c2020-07-01 16:21:27 -07002786 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002787
2788 // Move both windows
2789 touchedPoints = {{20, 20}, {175, 175}};
2790 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2791 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2792
chaviw9eaa22c2020-07-01 16:21:27 -07002793 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002794
chaviw9eaa22c2020-07-01 16:21:27 -07002795 // Release Window 2
2796 int32_t actionPointerUp =
2797 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2798 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
2799 expectedPoints.pop_back();
2800
2801 // Touch Window 2
2802 mWindow2->setWindowTransform(0, -1, 1, 0);
2803 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2804 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
2805
2806 // Move both windows
2807 touchedPoints = {{20, 20}, {175, 175}};
2808 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2809 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2810
2811 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002812}
2813
2814TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
2815 mWindow1->setWindowScale(0.5f, 0.5f);
2816
2817 // Touch Window 1
2818 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2819 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002820 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002821
2822 // Touch Window 2
2823 int32_t actionPointerDown =
2824 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002825 touchedPoints.push_back(PointF{150, 150});
2826 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002827
chaviw9eaa22c2020-07-01 16:21:27 -07002828 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002829
2830 // Move both windows
2831 touchedPoints = {{20, 20}, {175, 175}};
2832 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2833 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2834
chaviw9eaa22c2020-07-01 16:21:27 -07002835 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002836}
2837
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002838class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
2839 virtual void SetUp() override {
2840 InputDispatcherTest::SetUp();
2841
Chris Yea209fde2020-07-22 13:54:51 -07002842 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002843 mApplication->setDispatchingTimeout(20ms);
2844 mWindow =
2845 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2846 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05002847 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07002848 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002849 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2850 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002851 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002852
2853 // Set focused application.
2854 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
2855
2856 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002857 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002858 mWindow->consumeFocusEvent(true);
2859 }
2860
2861 virtual void TearDown() override {
2862 InputDispatcherTest::TearDown();
2863 mWindow.clear();
2864 }
2865
2866protected:
Chris Yea209fde2020-07-22 13:54:51 -07002867 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002868 sp<FakeWindowHandle> mWindow;
2869 static constexpr PointF WINDOW_LOCATION = {20, 20};
2870
2871 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002872 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002873 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2874 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002876 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2877 WINDOW_LOCATION));
2878 }
2879};
2880
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002881// Send a tap and respond, which should not cause an ANR.
2882TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
2883 tapOnWindow();
2884 mWindow->consumeMotionDown();
2885 mWindow->consumeMotionUp();
2886 ASSERT_TRUE(mDispatcher->waitForIdle());
2887 mFakePolicy->assertNotifyAnrWasNotCalled();
2888}
2889
2890// Send a regular key and respond, which should not cause an ANR.
2891TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002892 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002893 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
2894 ASSERT_TRUE(mDispatcher->waitForIdle());
2895 mFakePolicy->assertNotifyAnrWasNotCalled();
2896}
2897
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05002898TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
2899 mWindow->setFocusable(false);
2900 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2901 mWindow->consumeFocusEvent(false);
2902
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002903 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05002904 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002905 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
2906 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05002907 // Key will not go to window because we have no focused window.
2908 // The 'no focused window' ANR timer should start instead.
2909
2910 // Now, the focused application goes away.
2911 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
2912 // The key should get dropped and there should be no ANR.
2913
2914 ASSERT_TRUE(mDispatcher->waitForIdle());
2915 mFakePolicy->assertNotifyAnrWasNotCalled();
2916}
2917
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002918// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002919// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
2920// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002921TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002923 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2924 WINDOW_LOCATION));
2925
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002926 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
2927 ASSERT_TRUE(sequenceNum);
2928 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002929 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002930
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002931 mWindow->finishEvent(*sequenceNum);
2932 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2933 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002934 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002935 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002936}
2937
2938// Send a key to the app and have the app not respond right away.
2939TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
2940 // Inject a key, and don't respond - expect that ANR is called.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002941 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002942 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
2943 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002944 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002945 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002946 ASSERT_TRUE(mDispatcher->waitForIdle());
2947}
2948
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002949// We have a focused application, but no focused window
2950TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07002951 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2953 mWindow->consumeFocusEvent(false);
2954
2955 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002956 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002957 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2958 WINDOW_LOCATION));
2959 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
2960 mDispatcher->waitForIdle();
2961 mFakePolicy->assertNotifyAnrWasNotCalled();
2962
2963 // Once a focused event arrives, we get an ANR for this application
2964 // We specify the injection timeout to be smaller than the application timeout, to ensure that
2965 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002966 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002967 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002968 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
2969 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002970 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002971 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002972 ASSERT_TRUE(mDispatcher->waitForIdle());
2973}
2974
2975// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002976// Make sure that we don't notify policy twice about the same ANR.
2977TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07002978 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002979 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2980 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002981
2982 // Once a focused event arrives, we get an ANR for this application
2983 // We specify the injection timeout to be smaller than the application timeout, to ensure that
2984 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002985 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002986 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002987 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
2988 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002989 const std::chrono::duration appTimeout =
2990 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002991 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002992
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002993 std::this_thread::sleep_for(appTimeout);
2994 // ANR should not be raised again. It is up to policy to do that if it desires.
2995 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002996
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05002997 // If we now get a focused window, the ANR should stop, but the policy handles that via
2998 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002999 ASSERT_TRUE(mDispatcher->waitForIdle());
3000}
3001
3002// We have a focused application, but no focused window
3003TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003004 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3006 mWindow->consumeFocusEvent(false);
3007
3008 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003009 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003010 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003011 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3012 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003013
3014 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003015 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003016
3017 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003018 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003019 ASSERT_TRUE(mDispatcher->waitForIdle());
3020 mWindow->assertNoEvents();
3021}
3022
3023/**
3024 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3025 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3026 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3027 * the ANR mechanism should still work.
3028 *
3029 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3030 * DOWN event, while not responding on the second one.
3031 */
3032TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3033 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3034 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3035 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3036 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3037 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003038 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003039
3040 // Now send ACTION_UP, with identical timestamp
3041 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3042 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3043 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3044 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003045 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003046
3047 // We have now sent down and up. Let's consume first event and then ANR on the second.
3048 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3049 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003050 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003051}
3052
3053// If an app is not responding to a key event, gesture monitors should continue to receive
3054// new motion events
3055TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3056 FakeMonitorReceiver monitor =
3057 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3058 true /*isGestureMonitor*/);
3059
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3061 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003062 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003064
3065 // Stuck on the ACTION_UP
3066 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003067 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003068
3069 // New tap will go to the gesture monitor, but not to the window
3070 tapOnWindow();
3071 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3072 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3073
3074 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3075 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003076 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003077 mWindow->assertNoEvents();
3078 monitor.assertNoEvents();
3079}
3080
3081// If an app is not responding to a motion event, gesture monitors should continue to receive
3082// new motion events
3083TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3084 FakeMonitorReceiver monitor =
3085 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3086 true /*isGestureMonitor*/);
3087
3088 tapOnWindow();
3089 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3090 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3091
3092 mWindow->consumeMotionDown();
3093 // Stuck on the ACTION_UP
3094 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003095 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003096
3097 // New tap will go to the gesture monitor, but not to the window
3098 tapOnWindow();
3099 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3100 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3101
3102 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3103 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003104 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003105 mWindow->assertNoEvents();
3106 monitor.assertNoEvents();
3107}
3108
3109// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3110// process events, you don't get an anr. When the window later becomes unresponsive again, you
3111// get an ANR again.
3112// 1. tap -> block on ACTION_UP -> receive ANR
3113// 2. consume all pending events (= queue becomes healthy again)
3114// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3115TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3116 tapOnWindow();
3117
3118 mWindow->consumeMotionDown();
3119 // Block on ACTION_UP
3120 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003121 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003122 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3123 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003124 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003125 mWindow->assertNoEvents();
3126
3127 tapOnWindow();
3128 mWindow->consumeMotionDown();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003129 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003130 mWindow->consumeMotionUp();
3131
3132 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003133 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
3134 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003135 mWindow->assertNoEvents();
3136}
3137
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003138// If a connection remains unresponsive for a while, make sure policy is only notified once about
3139// it.
3140TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003142 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3143 WINDOW_LOCATION));
3144
3145 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003146 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003147 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003148 // 'notifyConnectionUnresponsive' should only be called once per connection
3149 mFakePolicy->assertNotifyAnrWasNotCalled();
3150 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003151 mWindow->consumeMotionDown();
3152 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3153 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3154 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003155 mDispatcher->waitForIdle();
3156 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
3157 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003158}
3159
3160/**
3161 * If a window is processing a motion event, and then a key event comes in, the key event should
3162 * not to to the focused window until the motion is processed.
3163 *
3164 * Warning!!!
3165 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3166 * and the injection timeout that we specify when injecting the key.
3167 * We must have the injection timeout (10ms) be smaller than
3168 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3169 *
3170 * If that value changes, this test should also change.
3171 */
3172TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3173 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3174 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3175
3176 tapOnWindow();
3177 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3178 ASSERT_TRUE(downSequenceNum);
3179 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3180 ASSERT_TRUE(upSequenceNum);
3181 // Don't finish the events yet, and send a key
3182 // Injection will "succeed" because we will eventually give up and send the key to the focused
3183 // window even if motions are still being processed. But because the injection timeout is short,
3184 // we will receive INJECTION_TIMED_OUT as the result.
3185
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003186 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003187 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003188 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3189 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003190 // Key will not be sent to the window, yet, because the window is still processing events
3191 // and the key remains pending, waiting for the touch events to be processed
3192 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3193 ASSERT_FALSE(keySequenceNum);
3194
3195 std::this_thread::sleep_for(500ms);
3196 // if we wait long enough though, dispatcher will give up, and still send the key
3197 // to the focused window, even though we have not yet finished the motion event
3198 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3199 mWindow->finishEvent(*downSequenceNum);
3200 mWindow->finishEvent(*upSequenceNum);
3201}
3202
3203/**
3204 * If a window is processing a motion event, and then a key event comes in, the key event should
3205 * not go to the focused window until the motion is processed.
3206 * If then a new motion comes in, then the pending key event should be going to the currently
3207 * focused window right away.
3208 */
3209TEST_F(InputDispatcherSingleWindowAnr,
3210 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3211 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3213
3214 tapOnWindow();
3215 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3216 ASSERT_TRUE(downSequenceNum);
3217 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3218 ASSERT_TRUE(upSequenceNum);
3219 // Don't finish the events yet, and send a key
3220 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003221 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003222 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003223 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003224 // At this point, key is still pending, and should not be sent to the application yet.
3225 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3226 ASSERT_FALSE(keySequenceNum);
3227
3228 // Now tap down again. It should cause the pending key to go to the focused window right away.
3229 tapOnWindow();
3230 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3231 // the other events yet. We can finish events in any order.
3232 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3233 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3234 mWindow->consumeMotionDown();
3235 mWindow->consumeMotionUp();
3236 mWindow->assertNoEvents();
3237}
3238
3239class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3240 virtual void SetUp() override {
3241 InputDispatcherTest::SetUp();
3242
Chris Yea209fde2020-07-22 13:54:51 -07003243 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003244 mApplication->setDispatchingTimeout(10ms);
3245 mUnfocusedWindow =
3246 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3247 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3248 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3249 // window.
3250 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003251 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3252 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3253 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003254
3255 mFocusedWindow =
3256 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003257 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003258 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003259 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3260 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003261
3262 // Set focused application.
3263 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003264 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003265
3266 // Expect one focus window exist in display.
3267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003268 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003269 mFocusedWindow->consumeFocusEvent(true);
3270 }
3271
3272 virtual void TearDown() override {
3273 InputDispatcherTest::TearDown();
3274
3275 mUnfocusedWindow.clear();
3276 mFocusedWindow.clear();
3277 }
3278
3279protected:
Chris Yea209fde2020-07-22 13:54:51 -07003280 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003281 sp<FakeWindowHandle> mUnfocusedWindow;
3282 sp<FakeWindowHandle> mFocusedWindow;
3283 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3284 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3285 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3286
3287 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3288
3289 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3290
3291private:
3292 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003293 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003294 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3295 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003297 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3298 location));
3299 }
3300};
3301
3302// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3303// should be ANR'd first.
3304TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003305 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003306 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3307 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003308 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003309 mFocusedWindow->consumeMotionDown();
3310 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3311 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3312 // We consumed all events, so no ANR
3313 ASSERT_TRUE(mDispatcher->waitForIdle());
3314 mFakePolicy->assertNotifyAnrWasNotCalled();
3315
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003317 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3318 FOCUSED_WINDOW_LOCATION));
3319 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
3320 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003321
3322 const std::chrono::duration timeout =
3323 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003324 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
3325 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
3326 // sequence to make it consistent
3327 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003328 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003329 mFocusedWindow->consumeMotionDown();
3330 // This cancel is generated because the connection was unresponsive
3331 mFocusedWindow->consumeMotionCancel();
3332 mFocusedWindow->assertNoEvents();
3333 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003334 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003335 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
3336 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003337}
3338
3339// If we have 2 windows with identical timeouts that are both unresponsive,
3340// it doesn't matter which order they should have ANR.
3341// But we should receive ANR for both.
3342TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
3343 // Set the timeout for unfocused window to match the focused window
3344 mUnfocusedWindow->setDispatchingTimeout(10ms);
3345 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3346
3347 tapOnFocusedWindow();
3348 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003349 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveConnectionToken(10ms);
3350 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveConnectionToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003351
3352 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003353 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
3354 mFocusedWindow->getToken() == anrConnectionToken2);
3355 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
3356 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003357
3358 ASSERT_TRUE(mDispatcher->waitForIdle());
3359 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003360
3361 mFocusedWindow->consumeMotionDown();
3362 mFocusedWindow->consumeMotionUp();
3363 mUnfocusedWindow->consumeMotionOutside();
3364
3365 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveConnectionToken();
3366 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveConnectionToken();
3367
3368 // Both applications should be marked as responsive, in any order
3369 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
3370 mFocusedWindow->getToken() == responsiveToken2);
3371 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
3372 mUnfocusedWindow->getToken() == responsiveToken2);
3373 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003374}
3375
3376// If a window is already not responding, the second tap on the same window should be ignored.
3377// We should also log an error to account for the dropped event (not tested here).
3378// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
3379TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
3380 tapOnFocusedWindow();
3381 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3382 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3383 // Receive the events, but don't respond
3384 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
3385 ASSERT_TRUE(downEventSequenceNum);
3386 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
3387 ASSERT_TRUE(upEventSequenceNum);
3388 const std::chrono::duration timeout =
3389 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003390 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003391
3392 // Tap once again
3393 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003394 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003395 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3396 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003397 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003398 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3399 FOCUSED_WINDOW_LOCATION));
3400 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
3401 // valid touch target
3402 mUnfocusedWindow->assertNoEvents();
3403
3404 // Consume the first tap
3405 mFocusedWindow->finishEvent(*downEventSequenceNum);
3406 mFocusedWindow->finishEvent(*upEventSequenceNum);
3407 ASSERT_TRUE(mDispatcher->waitForIdle());
3408 // The second tap did not go to the focused window
3409 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003410 // Since all events are finished, connection should be deemed healthy again
3411 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003412 mFakePolicy->assertNotifyAnrWasNotCalled();
3413}
3414
3415// If you tap outside of all windows, there will not be ANR
3416TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003417 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003418 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3419 LOCATION_OUTSIDE_ALL_WINDOWS));
3420 ASSERT_TRUE(mDispatcher->waitForIdle());
3421 mFakePolicy->assertNotifyAnrWasNotCalled();
3422}
3423
3424// Since the focused window is paused, tapping on it should not produce any events
3425TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
3426 mFocusedWindow->setPaused(true);
3427 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3428
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003429 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003430 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3431 FOCUSED_WINDOW_LOCATION));
3432
3433 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
3434 ASSERT_TRUE(mDispatcher->waitForIdle());
3435 // Should not ANR because the window is paused, and touches shouldn't go to it
3436 mFakePolicy->assertNotifyAnrWasNotCalled();
3437
3438 mFocusedWindow->assertNoEvents();
3439 mUnfocusedWindow->assertNoEvents();
3440}
3441
3442/**
3443 * If a window is processing a motion event, and then a key event comes in, the key event should
3444 * not to to the focused window until the motion is processed.
3445 * If a different window becomes focused at this time, the key should go to that window instead.
3446 *
3447 * Warning!!!
3448 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3449 * and the injection timeout that we specify when injecting the key.
3450 * We must have the injection timeout (10ms) be smaller than
3451 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3452 *
3453 * If that value changes, this test should also change.
3454 */
3455TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
3456 // Set a long ANR timeout to prevent it from triggering
3457 mFocusedWindow->setDispatchingTimeout(2s);
3458 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3459
3460 tapOnUnfocusedWindow();
3461 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
3462 ASSERT_TRUE(downSequenceNum);
3463 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
3464 ASSERT_TRUE(upSequenceNum);
3465 // Don't finish the events yet, and send a key
3466 // Injection will succeed because we will eventually give up and send the key to the focused
3467 // window even if motions are still being processed.
3468
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003469 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003470 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003471 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003473 // Key will not be sent to the window, yet, because the window is still processing events
3474 // and the key remains pending, waiting for the touch events to be processed
3475 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
3476 ASSERT_FALSE(keySequenceNum);
3477
3478 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07003479 mFocusedWindow->setFocusable(false);
3480 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003481 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003482 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003483
3484 // Focus events should precede the key events
3485 mUnfocusedWindow->consumeFocusEvent(true);
3486 mFocusedWindow->consumeFocusEvent(false);
3487
3488 // Finish the tap events, which should unblock dispatcher
3489 mUnfocusedWindow->finishEvent(*downSequenceNum);
3490 mUnfocusedWindow->finishEvent(*upSequenceNum);
3491
3492 // Now that all queues are cleared and no backlog in the connections, the key event
3493 // can finally go to the newly focused "mUnfocusedWindow".
3494 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3495 mFocusedWindow->assertNoEvents();
3496 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003497 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003498}
3499
3500// When the touch stream is split across 2 windows, and one of them does not respond,
3501// then ANR should be raised and the touch should be canceled for the unresponsive window.
3502// The other window should not be affected by that.
3503TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
3504 // Touch Window 1
3505 NotifyMotionArgs motionArgs =
3506 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3507 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
3508 mDispatcher->notifyMotion(&motionArgs);
3509 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3510 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3511
3512 // Touch Window 2
3513 int32_t actionPointerDown =
3514 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3515
3516 motionArgs =
3517 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3518 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
3519 mDispatcher->notifyMotion(&motionArgs);
3520
3521 const std::chrono::duration timeout =
3522 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003523 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003524
3525 mUnfocusedWindow->consumeMotionDown();
3526 mFocusedWindow->consumeMotionDown();
3527 // Focused window may or may not receive ACTION_MOVE
3528 // But it should definitely receive ACTION_CANCEL due to the ANR
3529 InputEvent* event;
3530 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
3531 ASSERT_TRUE(moveOrCancelSequenceNum);
3532 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
3533 ASSERT_NE(nullptr, event);
3534 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
3535 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
3536 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
3537 mFocusedWindow->consumeMotionCancel();
3538 } else {
3539 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
3540 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003541 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003542 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
3543
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003544 mUnfocusedWindow->assertNoEvents();
3545 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003546 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003547}
3548
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003549/**
3550 * If we have no focused window, and a key comes in, we start the ANR timer.
3551 * The focused application should add a focused window before the timer runs out to prevent ANR.
3552 *
3553 * If the user touches another application during this time, the key should be dropped.
3554 * Next, if a new focused window comes in, without toggling the focused application,
3555 * then no ANR should occur.
3556 *
3557 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
3558 * but in some cases the policy may not update the focused application.
3559 */
3560TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
3561 std::shared_ptr<FakeApplicationHandle> focusedApplication =
3562 std::make_shared<FakeApplicationHandle>();
3563 focusedApplication->setDispatchingTimeout(60ms);
3564 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
3565 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
3566 mFocusedWindow->setFocusable(false);
3567
3568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3569 mFocusedWindow->consumeFocusEvent(false);
3570
3571 // Send a key. The ANR timer should start because there is no focused window.
3572 // 'focusedApplication' will get blamed if this timer completes.
3573 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003574 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003575 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003576 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3577 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003578
3579 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
3580 // then the injected touches won't cause the focused event to get dropped.
3581 // The dispatcher only checks for whether the queue should be pruned upon queueing.
3582 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
3583 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
3584 // For this test, it means that the key would get delivered to the window once it becomes
3585 // focused.
3586 std::this_thread::sleep_for(10ms);
3587
3588 // Touch unfocused window. This should force the pending key to get dropped.
3589 NotifyMotionArgs motionArgs =
3590 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3591 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
3592 mDispatcher->notifyMotion(&motionArgs);
3593
3594 // We do not consume the motion right away, because that would require dispatcher to first
3595 // process (== drop) the key event, and by that time, ANR will be raised.
3596 // Set the focused window first.
3597 mFocusedWindow->setFocusable(true);
3598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3599 setFocusedWindow(mFocusedWindow);
3600 mFocusedWindow->consumeFocusEvent(true);
3601 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
3602 // to another application. This could be a bug / behaviour in the policy.
3603
3604 mUnfocusedWindow->consumeMotionDown();
3605
3606 ASSERT_TRUE(mDispatcher->waitForIdle());
3607 // Should not ANR because we actually have a focused window. It was just added too slowly.
3608 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
3609}
3610
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003611// These tests ensure we cannot send touch events to a window that's positioned behind a window
3612// that has feature NO_INPUT_CHANNEL.
3613// Layout:
3614// Top (closest to user)
3615// mNoInputWindow (above all windows)
3616// mBottomWindow
3617// Bottom (furthest from user)
3618class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
3619 virtual void SetUp() override {
3620 InputDispatcherTest::SetUp();
3621
3622 mApplication = std::make_shared<FakeApplicationHandle>();
3623 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
3624 "Window without input channel", ADISPLAY_ID_DEFAULT,
3625 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
3626
3627 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3628 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
3629 // It's perfectly valid for this window to not have an associated input channel
3630
3631 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
3632 ADISPLAY_ID_DEFAULT);
3633 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
3634
3635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
3636 }
3637
3638protected:
3639 std::shared_ptr<FakeApplicationHandle> mApplication;
3640 sp<FakeWindowHandle> mNoInputWindow;
3641 sp<FakeWindowHandle> mBottomWindow;
3642};
3643
3644TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
3645 PointF touchedPoint = {10, 10};
3646
3647 NotifyMotionArgs motionArgs =
3648 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3649 ADISPLAY_ID_DEFAULT, {touchedPoint});
3650 mDispatcher->notifyMotion(&motionArgs);
3651
3652 mNoInputWindow->assertNoEvents();
3653 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
3654 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
3655 // and therefore should prevent mBottomWindow from receiving touches
3656 mBottomWindow->assertNoEvents();
3657}
3658
3659/**
3660 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
3661 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
3662 */
3663TEST_F(InputDispatcherMultiWindowOcclusionTests,
3664 NoInputChannelFeature_DropsTouchesWithValidChannel) {
3665 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
3666 "Window with input channel and NO_INPUT_CHANNEL",
3667 ADISPLAY_ID_DEFAULT);
3668
3669 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3670 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
3671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
3672
3673 PointF touchedPoint = {10, 10};
3674
3675 NotifyMotionArgs motionArgs =
3676 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3677 ADISPLAY_ID_DEFAULT, {touchedPoint});
3678 mDispatcher->notifyMotion(&motionArgs);
3679
3680 mNoInputWindow->assertNoEvents();
3681 mBottomWindow->assertNoEvents();
3682}
3683
Vishnu Nair958da932020-08-21 17:12:37 -07003684class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
3685protected:
3686 std::shared_ptr<FakeApplicationHandle> mApp;
3687 sp<FakeWindowHandle> mWindow;
3688 sp<FakeWindowHandle> mMirror;
3689
3690 virtual void SetUp() override {
3691 InputDispatcherTest::SetUp();
3692 mApp = std::make_shared<FakeApplicationHandle>();
3693 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3694 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
3695 mWindow->getToken());
3696 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
3697 mWindow->setFocusable(true);
3698 mMirror->setFocusable(true);
3699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3700 }
3701};
3702
3703TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
3704 // Request focus on a mirrored window
3705 setFocusedWindow(mMirror);
3706
3707 // window gets focused
3708 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3710 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003711 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3712}
3713
3714// A focused & mirrored window remains focused only if the window and its mirror are both
3715// focusable.
3716TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
3717 setFocusedWindow(mMirror);
3718
3719 // window gets focused
3720 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3722 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003723 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003724 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3725 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003726 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3727
3728 mMirror->setFocusable(false);
3729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3730
3731 // window loses focus since one of the windows associated with the token in not focusable
3732 mWindow->consumeFocusEvent(false);
3733
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003734 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3735 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003736 mWindow->assertNoEvents();
3737}
3738
3739// A focused & mirrored window remains focused until the window and its mirror both become
3740// invisible.
3741TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
3742 setFocusedWindow(mMirror);
3743
3744 // window gets focused
3745 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003746 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3747 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003748 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003749 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3750 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003751 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3752
3753 mMirror->setVisible(false);
3754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3755
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3757 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003758 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3760 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003761 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3762
3763 mWindow->setVisible(false);
3764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3765
3766 // window loses focus only after all windows associated with the token become invisible.
3767 mWindow->consumeFocusEvent(false);
3768
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003769 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3770 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003771 mWindow->assertNoEvents();
3772}
3773
3774// A focused & mirrored window remains focused until both windows are removed.
3775TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
3776 setFocusedWindow(mMirror);
3777
3778 // window gets focused
3779 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3781 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003782 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003783 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3784 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003785 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3786
3787 // single window is removed but the window token remains focused
3788 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
3789
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3791 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003792 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3794 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003795 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3796
3797 // Both windows are removed
3798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3799 mWindow->consumeFocusEvent(false);
3800
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003801 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3802 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003803 mWindow->assertNoEvents();
3804}
3805
3806// Focus request can be pending until one window becomes visible.
3807TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
3808 // Request focus on an invisible mirror.
3809 mWindow->setVisible(false);
3810 mMirror->setVisible(false);
3811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3812 setFocusedWindow(mMirror);
3813
3814 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003816 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003817 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003818
3819 mMirror->setVisible(true);
3820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3821
3822 // window gets focused
3823 mWindow->consumeFocusEvent(true);
3824 // window gets the pending key event
3825 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3826}
Garfield Tane84e6f92019-08-29 17:28:41 -07003827} // namespace android::inputdispatcher