blob: 7333290c93c4b2fa2ab842154abeb306875fbd93 [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>
Michael Wrightd02c5b62014-02-10 15:10:22 -080022#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100023#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <linux/input.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100025
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
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000051// An arbitrary pid of the gesture monitor window
52static constexpr int32_t MONITOR_PID = 2001;
53
chaviwd1c23182019-12-20 18:44:56 -080054struct PointF {
55 float x;
56 float y;
57};
Michael Wrightd02c5b62014-02-10 15:10:22 -080058
Gang Wang342c9272020-01-13 13:15:04 -050059/**
60 * Return a DOWN key event with KEYCODE_A.
61 */
62static KeyEvent getTestKeyEvent() {
63 KeyEvent event;
64
Garfield Tanfbe732e2020-01-24 11:26:14 -080065 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
66 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
67 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050068 return event;
69}
70
Michael Wrightd02c5b62014-02-10 15:10:22 -080071// --- FakeInputDispatcherPolicy ---
72
73class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
74 InputDispatcherConfiguration mConfig;
75
76protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100077 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080078
79public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100080 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080081
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080082 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080083 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
84 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080085 }
86
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080087 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080088 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
89 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080090 }
91
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070092 void assertFilterInputEventWasNotCalled() {
93 std::scoped_lock lock(mLock);
94 ASSERT_EQ(nullptr, mFilteredEvent);
95 }
Michael Wrightd02c5b62014-02-10 15:10:22 -080096
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080097 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070098 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080099 ASSERT_TRUE(mConfigurationChangedTime)
100 << "Timed out waiting for configuration changed call";
101 ASSERT_EQ(*mConfigurationChangedTime, when);
102 mConfigurationChangedTime = std::nullopt;
103 }
104
105 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700106 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800107 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800108 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800109 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
110 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
111 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
112 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
113 mLastNotifySwitch = std::nullopt;
114 }
115
chaviwfd6d3512019-03-25 13:23:49 -0700116 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700117 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800118 ASSERT_EQ(touchedToken, mOnPointerDownToken);
119 mOnPointerDownToken.clear();
120 }
121
122 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700123 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800124 ASSERT_TRUE(mOnPointerDownToken == nullptr)
125 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700126 }
127
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700128 // This function must be called soon after the expected ANR timer starts,
129 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500130 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700131 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500132 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
133 std::shared_ptr<InputApplicationHandle> application;
134 { // acquire lock
135 std::unique_lock lock(mLock);
136 android::base::ScopedLockAssertion assumeLocked(mLock);
137 ASSERT_NO_FATAL_FAILURE(
138 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
139 } // release lock
140 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700141 }
142
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500143 void assertNotifyConnectionUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
144 const sp<IBinder>& expectedConnectionToken) {
145 sp<IBinder> connectionToken = getUnresponsiveConnectionToken(timeout);
146 ASSERT_EQ(expectedConnectionToken, connectionToken);
147 }
148
149 void assertNotifyConnectionResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
150 sp<IBinder> connectionToken = getResponsiveConnectionToken();
151 ASSERT_EQ(expectedConnectionToken, connectionToken);
152 }
153
154 sp<IBinder> getUnresponsiveConnectionToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700155 std::unique_lock lock(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700156 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500157 return getAnrTokenLockedInterruptible(timeout, mAnrConnectionTokens, lock);
158 }
159
160 sp<IBinder> getResponsiveConnectionToken() {
161 std::unique_lock lock(mLock);
162 android::base::ScopedLockAssertion assumeLocked(mLock);
163 return getAnrTokenLockedInterruptible(0s, mResponsiveConnectionTokens, lock);
164 }
165
166 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
167 // for a specific container to become non-empty. When the container is non-empty, return the
168 // first entry from the container and erase it.
169 template <class T>
170 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
171 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
172 const std::chrono::time_point start = std::chrono::steady_clock::now();
173 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700174
175 // If there is an ANR, Dispatcher won't be idle because there are still events
176 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
177 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500178 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
179 // to provide it some time to act. 100ms seems reasonable.
180 mNotifyAnr.wait_for(lock, timeToWait,
181 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700182 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500183 if (storage.empty()) {
184 ADD_FAILURE() << "Did not receive the ANR callback";
185 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700186 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700187 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
188 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700189 if (std::chrono::abs(timeout - waited) > 100ms) {
190 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
191 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
192 << "ms, but waited "
193 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
194 << "ms instead";
195 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500196 T token = storage.front();
197 storage.pop();
198 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700199 }
200
201 void assertNotifyAnrWasNotCalled() {
202 std::scoped_lock lock(mLock);
203 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500204 ASSERT_TRUE(mAnrConnectionTokens.empty());
205 ASSERT_TRUE(mResponsiveConnectionTokens.empty())
206 << "ANR was not called, but please also consume the 'connection is responsive' "
207 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700208 }
209
Garfield Tan1c7bc862020-01-28 13:24:04 -0800210 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
211 mConfig.keyRepeatTimeout = timeout;
212 mConfig.keyRepeatDelay = delay;
213 }
214
Prabir Pradhan99987712020-11-10 18:43:05 -0800215 void waitForSetPointerCapture(bool enabled) {
216 std::unique_lock lock(mLock);
217 base::ScopedLockAssertion assumeLocked(mLock);
218
219 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
220 [this, enabled]() REQUIRES(mLock) {
221 return mPointerCaptureEnabled &&
222 *mPointerCaptureEnabled ==
223 enabled;
224 })) {
225 FAIL() << "Timed out waiting for setPointerCapture(" << enabled << ") to be called.";
226 }
227 mPointerCaptureEnabled.reset();
228 }
229
230 void assertSetPointerCaptureNotCalled() {
231 std::unique_lock lock(mLock);
232 base::ScopedLockAssertion assumeLocked(mLock);
233
234 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
235 FAIL() << "Expected setPointerCapture(enabled) to not be called, but was called. "
236 "enabled = "
237 << *mPointerCaptureEnabled;
238 }
239 mPointerCaptureEnabled.reset();
240 }
241
Michael Wrightd02c5b62014-02-10 15:10:22 -0800242private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700243 std::mutex mLock;
244 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
245 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
246 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
247 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800248
Prabir Pradhan99987712020-11-10 18:43:05 -0800249 std::condition_variable mPointerCaptureChangedCondition;
250 std::optional<bool> mPointerCaptureEnabled GUARDED_BY(mLock);
251
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700252 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700253 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500254 std::queue<sp<IBinder>> mAnrConnectionTokens GUARDED_BY(mLock);
255 std::queue<sp<IBinder>> mResponsiveConnectionTokens GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700256 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700257
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600258 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700259 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800260 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261 }
262
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500263 void notifyConnectionUnresponsive(const sp<IBinder>& connectionToken,
264 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700265 std::scoped_lock lock(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500266 mAnrConnectionTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700267 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500268 }
269
270 void notifyConnectionResponsive(const sp<IBinder>& connectionToken) override {
271 std::scoped_lock lock(mLock);
272 mResponsiveConnectionTokens.push(connectionToken);
273 mNotifyAnr.notify_all();
274 }
275
276 void notifyNoFocusedWindowAnr(
277 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
278 std::scoped_lock lock(mLock);
279 mAnrApplications.push(applicationHandle);
280 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800281 }
282
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600283 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600285 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700286
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600287 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000288
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600289 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800290 *outConfig = mConfig;
291 }
292
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600293 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700294 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800295 switch (inputEvent->getType()) {
296 case AINPUT_EVENT_TYPE_KEY: {
297 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800298 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800299 break;
300 }
301
302 case AINPUT_EVENT_TYPE_MOTION: {
303 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800304 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800305 break;
306 }
307 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 return true;
309 }
310
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600311 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800312
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600313 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800314
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600315 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 return 0;
317 }
318
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600319 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800320 return false;
321 }
322
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600323 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
324 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700325 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800326 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
327 * essentially a passthrough for notifySwitch.
328 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800329 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800330 }
331
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600332 void pokeUserActivity(nsecs_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800333
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600334 bool checkInjectEventsPermissionNonReentrant(int32_t, int32_t) override { return false; }
Jackal Guof9696682018-10-05 12:23:23 +0800335
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600336 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700337 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700338 mOnPointerDownToken = newToken;
339 }
340
Prabir Pradhan99987712020-11-10 18:43:05 -0800341 void setPointerCapture(bool enabled) override {
342 std::scoped_lock lock(mLock);
343 mPointerCaptureEnabled = {enabled};
344 mPointerCaptureChangedCondition.notify_all();
345 }
346
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800347 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
348 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700349 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800350 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
351 ASSERT_EQ(mFilteredEvent->getType(), type);
352
353 if (type == AINPUT_EVENT_TYPE_KEY) {
354 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
355 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
356 EXPECT_EQ(keyEvent.getAction(), action);
357 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
358 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
359 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
360 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
361 EXPECT_EQ(motionEvent.getAction(), action);
362 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
363 } else {
364 FAIL() << "Unknown type: " << type;
365 }
366
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800367 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800369};
370
Michael Wrightd02c5b62014-02-10 15:10:22 -0800371// --- InputDispatcherTest ---
372
373class InputDispatcherTest : public testing::Test {
374protected:
375 sp<FakeInputDispatcherPolicy> mFakePolicy;
376 sp<InputDispatcher> mDispatcher;
377
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700378 virtual void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800379 mFakePolicy = new FakeInputDispatcherPolicy();
380 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800381 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000382 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700383 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 }
385
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700386 virtual void TearDown() override {
387 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388 mFakePolicy.clear();
389 mDispatcher.clear();
390 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700391
392 /**
393 * Used for debugging when writing the test
394 */
395 void dumpDispatcherState() {
396 std::string dump;
397 mDispatcher->dump(dump);
398 std::stringstream ss(dump);
399 std::string to;
400
401 while (std::getline(ss, to, '\n')) {
402 ALOGE("%s", to.c_str());
403 }
404 }
Vishnu Nair958da932020-08-21 17:12:37 -0700405
406 void setFocusedWindow(const sp<InputWindowHandle>& window,
407 const sp<InputWindowHandle>& focusedWindow = nullptr) {
408 FocusRequest request;
409 request.token = window->getToken();
410 if (focusedWindow) {
411 request.focusedToken = focusedWindow->getToken();
412 }
413 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
414 request.displayId = window->getInfo()->displayId;
415 mDispatcher->setFocusedWindow(request);
416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417};
418
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
420 KeyEvent event;
421
422 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800423 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
424 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600425 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
426 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800427 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700428 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800429 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 << "Should reject key events with undefined action.";
431
432 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800433 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
434 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600435 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800436 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700437 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800438 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439 << "Should reject key events with ACTION_MULTIPLE.";
440}
441
442TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
443 MotionEvent event;
444 PointerProperties pointerProperties[MAX_POINTERS + 1];
445 PointerCoords pointerCoords[MAX_POINTERS + 1];
446 for (int i = 0; i <= MAX_POINTERS; i++) {
447 pointerProperties[i].clear();
448 pointerProperties[i].id = i;
449 pointerCoords[i].clear();
450 }
451
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800452 // Some constants commonly used below
453 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
454 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
455 constexpr int32_t metaState = AMETA_NONE;
456 constexpr MotionClassification classification = MotionClassification::NONE;
457
chaviw9eaa22c2020-07-01 16:21:27 -0700458 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800460 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700461 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
462 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600463 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700464 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800465 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700466 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800467 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 << "Should reject motion events with undefined action.";
469
470 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800471 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700472 AMOTION_EVENT_ACTION_POINTER_DOWN |
473 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700474 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
475 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
476 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
477 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800478 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700479 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800480 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481 << "Should reject motion events with pointer down index too large.";
482
Garfield Tanfbe732e2020-01-24 11:26:14 -0800483 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700484 AMOTION_EVENT_ACTION_POINTER_DOWN |
485 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700486 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
487 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
488 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
489 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 pointer down index too small.";
494
495 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800496 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700497 AMOTION_EVENT_ACTION_POINTER_UP |
498 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700499 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
500 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
501 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
502 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800503 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700504 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800505 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 << "Should reject motion events with pointer up index too large.";
507
Garfield Tanfbe732e2020-01-24 11:26:14 -0800508 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700509 AMOTION_EVENT_ACTION_POINTER_UP |
510 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700511 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
512 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
513 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
514 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800515 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700516 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800517 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 << "Should reject motion events with pointer up index too small.";
519
520 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800521 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
522 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700523 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
524 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700525 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800526 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700527 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800528 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 << "Should reject motion events with 0 pointers.";
530
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*/ MAX_POINTERS + 1, 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 more than MAX_POINTERS pointers.";
540
541 // Rejects motion events with invalid pointer ids.
542 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800543 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
544 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700545 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
546 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700547 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800548 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700549 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800550 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 << "Should reject motion events with pointer ids less than 0.";
552
553 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800554 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
555 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700556 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
557 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700558 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800559 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700560 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800561 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
563
564 // Rejects motion events with duplicate pointer ids.
565 pointerProperties[0].id = 1;
566 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800567 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
568 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700569 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
570 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700571 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800572 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700573 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800574 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 << "Should reject motion events with duplicate pointer ids.";
576}
577
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800578/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
579
580TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
581 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800582 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800583 mDispatcher->notifyConfigurationChanged(&args);
584 ASSERT_TRUE(mDispatcher->waitForIdle());
585
586 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
587}
588
589TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800590 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
591 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800592 mDispatcher->notifySwitch(&args);
593
594 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
595 args.policyFlags |= POLICY_FLAG_TRUSTED;
596 mFakePolicy->assertNotifySwitchWasCalled(args);
597}
598
Arthur Hungb92218b2018-08-14 12:00:21 +0800599// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700600static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700601static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800602
603class FakeApplicationHandle : public InputApplicationHandle {
604public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700605 FakeApplicationHandle() {
606 mInfo.name = "Fake Application";
607 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500608 mInfo.dispatchingTimeoutMillis =
609 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700610 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800611 virtual ~FakeApplicationHandle() {}
612
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000613 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700614
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500615 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
616 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700617 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800618};
619
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800620class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800621public:
Garfield Tan15601662020-09-22 15:32:38 -0700622 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800623 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700624 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800625 }
626
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800627 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700628 InputEvent* event;
629 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
630 if (!consumeSeq) {
631 return nullptr;
632 }
633 finishEvent(*consumeSeq);
634 return event;
635 }
636
637 /**
638 * Receive an event without acknowledging it.
639 * Return the sequence number that could later be used to send finished signal.
640 */
641 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800642 uint32_t consumeSeq;
643 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800644
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800645 std::chrono::time_point start = std::chrono::steady_clock::now();
646 status_t status = WOULD_BLOCK;
647 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800648 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800649 &event);
650 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
651 if (elapsed > 100ms) {
652 break;
653 }
654 }
655
656 if (status == WOULD_BLOCK) {
657 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700658 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800659 }
660
661 if (status != OK) {
662 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700663 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800664 }
665 if (event == nullptr) {
666 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700667 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800668 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700669 if (outEvent != nullptr) {
670 *outEvent = event;
671 }
672 return consumeSeq;
673 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800674
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700675 /**
676 * To be used together with "receiveEvent" to complete the consumption of an event.
677 */
678 void finishEvent(uint32_t consumeSeq) {
679 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
680 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800681 }
682
683 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
684 int32_t expectedFlags) {
685 InputEvent* event = consume();
686
687 ASSERT_NE(nullptr, event) << mName.c_str()
688 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800689 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700690 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800691 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800692
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800693 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800694
Tiger Huang8664f8c2018-10-11 19:14:35 +0800695 switch (expectedEventType) {
696 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800697 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
698 EXPECT_EQ(expectedAction, keyEvent.getAction());
699 EXPECT_EQ(expectedFlags, keyEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800700 break;
701 }
702 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800703 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
704 EXPECT_EQ(expectedAction, motionEvent.getAction());
705 EXPECT_EQ(expectedFlags, motionEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800706 break;
707 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100708 case AINPUT_EVENT_TYPE_FOCUS: {
709 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
710 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800711 case AINPUT_EVENT_TYPE_CAPTURE: {
712 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
713 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800714 default: {
715 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
716 }
717 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800718 }
719
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100720 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
721 InputEvent* event = consume();
722 ASSERT_NE(nullptr, event) << mName.c_str()
723 << ": consumer should have returned non-NULL event.";
724 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
725 << "Got " << inputEventTypeToString(event->getType())
726 << " event instead of FOCUS event";
727
728 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
729 << mName.c_str() << ": event displayId should always be NONE.";
730
731 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
732 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
733 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
734 }
735
Prabir Pradhan99987712020-11-10 18:43:05 -0800736 void consumeCaptureEvent(bool hasCapture) {
737 const InputEvent* event = consume();
738 ASSERT_NE(nullptr, event) << mName.c_str()
739 << ": consumer should have returned non-NULL event.";
740 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
741 << "Got " << inputEventTypeToString(event->getType())
742 << " event instead of CAPTURE event";
743
744 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
745 << mName.c_str() << ": event displayId should always be NONE.";
746
747 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
748 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
749 }
750
chaviwd1c23182019-12-20 18:44:56 -0800751 void assertNoEvents() {
752 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700753 if (event == nullptr) {
754 return;
755 }
756 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
757 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
758 ADD_FAILURE() << "Received key event "
759 << KeyEvent::actionToString(keyEvent.getAction());
760 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
761 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
762 ADD_FAILURE() << "Received motion event "
763 << MotionEvent::actionToString(motionEvent.getAction());
764 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
765 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
766 ADD_FAILURE() << "Received focus event, hasFocus = "
767 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800768 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
769 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
770 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
771 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700772 }
773 FAIL() << mName.c_str()
774 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800775 }
776
777 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
778
779protected:
780 std::unique_ptr<InputConsumer> mConsumer;
781 PreallocatedInputEventFactory mEventFactory;
782
783 std::string mName;
784};
785
786class FakeWindowHandle : public InputWindowHandle {
787public:
788 static const int32_t WIDTH = 600;
789 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800790
Chris Yea209fde2020-07-22 13:54:51 -0700791 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800792 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500793 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800794 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500795 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700796 base::Result<std::unique_ptr<InputChannel>> channel =
797 dispatcher->createInputChannel(name);
798 token = (*channel)->getConnectionToken();
799 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800800 }
801
802 inputApplicationHandle->updateInfo();
803 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
804
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500805 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700806 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800807 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100808 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500809 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
chaviwd1c23182019-12-20 18:44:56 -0800810 mInfo.frameLeft = 0;
811 mInfo.frameTop = 0;
812 mInfo.frameRight = WIDTH;
813 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700814 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800815 mInfo.globalScaleFactor = 1.0;
816 mInfo.touchableRegion.clear();
817 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
818 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700819 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800820 mInfo.hasWallpaper = false;
821 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800822 mInfo.ownerPid = INJECTOR_PID;
823 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800824 mInfo.displayId = displayId;
825 }
826
827 virtual bool updateInfo() { return true; }
828
Vishnu Nair47074b82020-08-14 11:54:47 -0700829 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800830
Vishnu Nair958da932020-08-21 17:12:37 -0700831 void setVisible(bool visible) { mInfo.visible = visible; }
832
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700833 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500834 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700835 }
836
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700837 void setPaused(bool paused) { mInfo.paused = paused; }
838
chaviwd1c23182019-12-20 18:44:56 -0800839 void setFrame(const Rect& frame) {
840 mInfo.frameLeft = frame.left;
841 mInfo.frameTop = frame.top;
842 mInfo.frameRight = frame.right;
843 mInfo.frameBottom = frame.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -0700844 mInfo.transform.set(frame.left, frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800845 mInfo.touchableRegion.clear();
846 mInfo.addTouchableRegion(frame);
847 }
848
Michael Wright44753b12020-07-08 13:48:11 +0100849 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800850
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500851 void setInputFeatures(InputWindowInfo::Feature features) { mInfo.inputFeatures = features; }
852
chaviw9eaa22c2020-07-01 16:21:27 -0700853 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
854 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
855 }
856
857 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700858
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800859 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
860 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
861 expectedFlags);
862 }
863
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700864 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
865 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
866 }
867
Svet Ganov5d3bc372020-01-26 23:11:07 -0800868 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000869 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800870 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
871 expectedFlags);
872 }
873
874 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000875 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800876 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
877 expectedFlags);
878 }
879
880 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000881 int32_t expectedFlags = 0) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800882 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
883 expectedFlags);
884 }
885
Svet Ganov5d3bc372020-01-26 23:11:07 -0800886 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000887 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
888 int32_t expectedFlags = 0) {
889 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
890 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -0800891 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
892 }
893
894 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000895 int32_t expectedFlags = 0) {
896 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
897 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -0800898 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
899 }
900
901 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000902 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +0000903 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
904 expectedFlags);
905 }
906
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500907 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
908 int32_t expectedFlags = 0) {
909 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
910 expectedFlags);
911 }
912
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100913 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
914 ASSERT_NE(mInputReceiver, nullptr)
915 << "Cannot consume events from a window with no receiver";
916 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
917 }
918
Prabir Pradhan99987712020-11-10 18:43:05 -0800919 void consumeCaptureEvent(bool hasCapture) {
920 ASSERT_NE(mInputReceiver, nullptr)
921 << "Cannot consume events from a window with no receiver";
922 mInputReceiver->consumeCaptureEvent(hasCapture);
923 }
924
chaviwd1c23182019-12-20 18:44:56 -0800925 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
926 int32_t expectedFlags) {
927 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
928 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
929 expectedFlags);
930 }
931
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700933 if (mInputReceiver == nullptr) {
934 ADD_FAILURE() << "Invalid receive event on window with no receiver";
935 return std::nullopt;
936 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700937 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700938 }
939
940 void finishEvent(uint32_t sequenceNum) {
941 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
942 mInputReceiver->finishEvent(sequenceNum);
943 }
944
chaviwaf87b3e2019-10-01 16:59:28 -0700945 InputEvent* consume() {
946 if (mInputReceiver == nullptr) {
947 return nullptr;
948 }
949 return mInputReceiver->consume();
950 }
951
Arthur Hungb92218b2018-08-14 12:00:21 +0800952 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500953 if (mInputReceiver == nullptr &&
954 mInfo.inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL)) {
955 return; // Can't receive events if the window does not have input channel
956 }
957 ASSERT_NE(nullptr, mInputReceiver)
958 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -0800959 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +0800960 }
961
chaviwaf87b3e2019-10-01 16:59:28 -0700962 sp<IBinder> getToken() { return mInfo.token; }
963
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100964 const std::string& getName() { return mName; }
965
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000966 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
967 mInfo.ownerPid = ownerPid;
968 mInfo.ownerUid = ownerUid;
969 }
970
chaviwd1c23182019-12-20 18:44:56 -0800971private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100972 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -0800973 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700974 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800975};
976
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700977std::atomic<int32_t> FakeWindowHandle::sId{1};
978
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800979static InputEventInjectionResult injectKey(
980 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
981 int32_t displayId = ADISPLAY_ID_NONE,
982 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
983 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800984 KeyEvent event;
985 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
986
987 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800988 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700989 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
990 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +0800991
992 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700993 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
994 injectionTimeout,
995 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
Arthur Hungb92218b2018-08-14 12:00:21 +0800996}
997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800998static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
999 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001000 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1001}
1002
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001003static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1004 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001005 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1006}
1007
Garfield Tandf26e862020-07-01 20:18:19 -07001008class PointerBuilder {
1009public:
1010 PointerBuilder(int32_t id, int32_t toolType) {
1011 mProperties.clear();
1012 mProperties.id = id;
1013 mProperties.toolType = toolType;
1014 mCoords.clear();
1015 }
1016
1017 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1018
1019 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1020
1021 PointerBuilder& axis(int32_t axis, float value) {
1022 mCoords.setAxisValue(axis, value);
1023 return *this;
1024 }
1025
1026 PointerProperties buildProperties() const { return mProperties; }
1027
1028 PointerCoords buildCoords() const { return mCoords; }
1029
1030private:
1031 PointerProperties mProperties;
1032 PointerCoords mCoords;
1033};
1034
1035class MotionEventBuilder {
1036public:
1037 MotionEventBuilder(int32_t action, int32_t source) {
1038 mAction = action;
1039 mSource = source;
1040 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1041 }
1042
1043 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1044 mEventTime = eventTime;
1045 return *this;
1046 }
1047
1048 MotionEventBuilder& displayId(int32_t displayId) {
1049 mDisplayId = displayId;
1050 return *this;
1051 }
1052
1053 MotionEventBuilder& actionButton(int32_t actionButton) {
1054 mActionButton = actionButton;
1055 return *this;
1056 }
1057
1058 MotionEventBuilder& buttonState(int32_t actionButton) {
1059 mActionButton = actionButton;
1060 return *this;
1061 }
1062
1063 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1064 mRawXCursorPosition = rawXCursorPosition;
1065 return *this;
1066 }
1067
1068 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1069 mRawYCursorPosition = rawYCursorPosition;
1070 return *this;
1071 }
1072
1073 MotionEventBuilder& pointer(PointerBuilder pointer) {
1074 mPointers.push_back(pointer);
1075 return *this;
1076 }
1077
1078 MotionEvent build() {
1079 std::vector<PointerProperties> pointerProperties;
1080 std::vector<PointerCoords> pointerCoords;
1081 for (const PointerBuilder& pointer : mPointers) {
1082 pointerProperties.push_back(pointer.buildProperties());
1083 pointerCoords.push_back(pointer.buildCoords());
1084 }
1085
1086 // Set mouse cursor position for the most common cases to avoid boilerplate.
1087 if (mSource == AINPUT_SOURCE_MOUSE &&
1088 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1089 mPointers.size() == 1) {
1090 mRawXCursorPosition = pointerCoords[0].getX();
1091 mRawYCursorPosition = pointerCoords[0].getY();
1092 }
1093
1094 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001095 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001096 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
1097 mAction, mActionButton, /* flags */ 0, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001098 mButtonState, MotionClassification::NONE, identityTransform,
1099 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
1100 mRawYCursorPosition, mEventTime, mEventTime, mPointers.size(),
1101 pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001102
1103 return event;
1104 }
1105
1106private:
1107 int32_t mAction;
1108 int32_t mSource;
1109 nsecs_t mEventTime;
1110 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1111 int32_t mActionButton{0};
1112 int32_t mButtonState{0};
1113 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1114 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1115
1116 std::vector<PointerBuilder> mPointers;
1117};
1118
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001119static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001120 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1121 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001122 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001123 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1124 injectionTimeout,
1125 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1126}
1127
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001128static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001129 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1130 const PointF& position,
1131 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001132 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1133 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001134 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001135 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001136 MotionEvent event = MotionEventBuilder(action, source)
1137 .displayId(displayId)
1138 .eventTime(eventTime)
1139 .rawXCursorPosition(cursorPosition.x)
1140 .rawYCursorPosition(cursorPosition.y)
1141 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1142 .x(position.x)
1143 .y(position.y))
1144 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001145
1146 // Inject event until dispatch out.
Garfield Tandf26e862020-07-01 20:18:19 -07001147 return injectMotionEvent(dispatcher, event);
Arthur Hungb92218b2018-08-14 12:00:21 +08001148}
1149
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001150static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1151 int32_t source, int32_t displayId,
1152 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001153 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001154}
1155
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001156static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1157 int32_t source, int32_t displayId,
1158 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001159 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001160}
1161
Jackal Guof9696682018-10-05 12:23:23 +08001162static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1163 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1164 // Define a valid key event.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001165 NotifyKeyArgs args(/* id */ 0, currentTime, DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
1166 POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A, KEY_A,
1167 AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001168
1169 return args;
1170}
1171
chaviwd1c23182019-12-20 18:44:56 -08001172static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1173 const std::vector<PointF>& points) {
1174 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001175 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1176 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1177 }
1178
chaviwd1c23182019-12-20 18:44:56 -08001179 PointerProperties pointerProperties[pointerCount];
1180 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001181
chaviwd1c23182019-12-20 18:44:56 -08001182 for (size_t i = 0; i < pointerCount; i++) {
1183 pointerProperties[i].clear();
1184 pointerProperties[i].id = i;
1185 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001186
chaviwd1c23182019-12-20 18:44:56 -08001187 pointerCoords[i].clear();
1188 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1189 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1190 }
Jackal Guof9696682018-10-05 12:23:23 +08001191
1192 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1193 // Define a valid motion event.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001194 NotifyMotionArgs args(/* id */ 0, currentTime, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001195 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1196 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001197 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1198 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001199 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1200 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001201
1202 return args;
1203}
1204
chaviwd1c23182019-12-20 18:44:56 -08001205static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1206 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1207}
1208
Prabir Pradhan99987712020-11-10 18:43:05 -08001209static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(bool enabled) {
1210 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), enabled);
1211}
1212
Arthur Hungb92218b2018-08-14 12:00:21 +08001213TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001214 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001215 sp<FakeWindowHandle> window =
1216 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001217
Arthur Hung72d8dc32020-03-28 00:48:39 +00001218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001219 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1220 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1221 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001222
1223 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001224 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001225}
1226
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001227/**
1228 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1229 * To ensure that window receives only events that were directly inside of it, add
1230 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1231 * when finding touched windows.
1232 * This test serves as a sanity check for the next test, where setInputWindows is
1233 * called twice.
1234 */
1235TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001236 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001237 sp<FakeWindowHandle> window =
1238 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1239 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001240 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001241
1242 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001244 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1245 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001246 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001247
1248 // Window should receive motion event.
1249 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1250}
1251
1252/**
1253 * Calling setInputWindows twice, with the same info, should not cause any issues.
1254 * To ensure that window receives only events that were directly inside of it, add
1255 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1256 * when finding touched windows.
1257 */
1258TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001259 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001260 sp<FakeWindowHandle> window =
1261 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1262 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001263 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001264
1265 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001267 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001268 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1269 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001270 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001271
1272 // Window should receive motion event.
1273 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1274}
1275
Arthur Hungb92218b2018-08-14 12:00:21 +08001276// The foreground window should receive the first touch down event.
1277TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001278 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001279 sp<FakeWindowHandle> windowTop =
1280 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1281 sp<FakeWindowHandle> windowSecond =
1282 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001283
Arthur Hung72d8dc32020-03-28 00:48:39 +00001284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001285 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1286 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1287 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001288
1289 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001290 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001291 windowSecond->assertNoEvents();
1292}
1293
Garfield Tandf26e862020-07-01 20:18:19 -07001294TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001295 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001296 sp<FakeWindowHandle> windowLeft =
1297 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1298 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001299 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001300 sp<FakeWindowHandle> windowRight =
1301 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1302 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001303 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001304
1305 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1306
1307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1308
1309 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001311 injectMotionEvent(mDispatcher,
1312 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1313 AINPUT_SOURCE_MOUSE)
1314 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1315 .x(900)
1316 .y(400))
1317 .build()));
1318 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1319 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1320 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1321 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1322
1323 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001324 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001325 injectMotionEvent(mDispatcher,
1326 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1327 AINPUT_SOURCE_MOUSE)
1328 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1329 .x(300)
1330 .y(400))
1331 .build()));
1332 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1333 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1334 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1335 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1336 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1337 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1338
1339 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001340 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001341 injectMotionEvent(mDispatcher,
1342 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1343 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1344 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1345 .x(300)
1346 .y(400))
1347 .build()));
1348 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1349
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001351 injectMotionEvent(mDispatcher,
1352 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1353 AINPUT_SOURCE_MOUSE)
1354 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1355 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1356 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1357 .x(300)
1358 .y(400))
1359 .build()));
1360 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1361 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1362
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001364 injectMotionEvent(mDispatcher,
1365 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1366 AINPUT_SOURCE_MOUSE)
1367 .buttonState(0)
1368 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1369 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1370 .x(300)
1371 .y(400))
1372 .build()));
1373 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1374 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1375
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001377 injectMotionEvent(mDispatcher,
1378 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1379 .buttonState(0)
1380 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1381 .x(300)
1382 .y(400))
1383 .build()));
1384 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1385
1386 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001387 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001388 injectMotionEvent(mDispatcher,
1389 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1390 AINPUT_SOURCE_MOUSE)
1391 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1392 .x(900)
1393 .y(400))
1394 .build()));
1395 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1396 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1397 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1398 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1399 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1400 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1401}
1402
1403// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1404// directly in this test.
1405TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001406 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001407 sp<FakeWindowHandle> window =
1408 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1409 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001410 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001411
1412 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1413
1414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1415
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001417 injectMotionEvent(mDispatcher,
1418 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1419 AINPUT_SOURCE_MOUSE)
1420 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1421 .x(300)
1422 .y(400))
1423 .build()));
1424 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1425 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1426
1427 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001429 injectMotionEvent(mDispatcher,
1430 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1431 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1432 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1433 .x(300)
1434 .y(400))
1435 .build()));
1436 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1437
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001439 injectMotionEvent(mDispatcher,
1440 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1441 AINPUT_SOURCE_MOUSE)
1442 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1443 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1444 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1445 .x(300)
1446 .y(400))
1447 .build()));
1448 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1449 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1450
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001451 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001452 injectMotionEvent(mDispatcher,
1453 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1454 AINPUT_SOURCE_MOUSE)
1455 .buttonState(0)
1456 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1457 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1458 .x(300)
1459 .y(400))
1460 .build()));
1461 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1462 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1463
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001465 injectMotionEvent(mDispatcher,
1466 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1467 .buttonState(0)
1468 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1469 .x(300)
1470 .y(400))
1471 .build()));
1472 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1473
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001475 injectMotionEvent(mDispatcher,
1476 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1477 AINPUT_SOURCE_MOUSE)
1478 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1479 .x(300)
1480 .y(400))
1481 .build()));
1482 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1483 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1484}
1485
Garfield Tan00f511d2019-06-12 16:55:40 -07001486TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001487 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001488
1489 sp<FakeWindowHandle> windowLeft =
1490 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1491 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001492 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001493 sp<FakeWindowHandle> windowRight =
1494 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1495 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001496 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001497
1498 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1499
Arthur Hung72d8dc32020-03-28 00:48:39 +00001500 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001501
1502 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1503 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001505 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001506 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001507 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001508 windowRight->assertNoEvents();
1509}
1510
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001511TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001512 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001513 sp<FakeWindowHandle> window =
1514 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001515 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001516
Arthur Hung72d8dc32020-03-28 00:48:39 +00001517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001518 setFocusedWindow(window);
1519
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001520 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001521
1522 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1523 mDispatcher->notifyKey(&keyArgs);
1524
1525 // Window should receive key down event.
1526 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1527
1528 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1529 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001530 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001531 mDispatcher->notifyDeviceReset(&args);
1532 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1533 AKEY_EVENT_FLAG_CANCELED);
1534}
1535
1536TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001537 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001538 sp<FakeWindowHandle> window =
1539 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1540
Arthur Hung72d8dc32020-03-28 00:48:39 +00001541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001542
1543 NotifyMotionArgs motionArgs =
1544 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1545 ADISPLAY_ID_DEFAULT);
1546 mDispatcher->notifyMotion(&motionArgs);
1547
1548 // Window should receive motion down event.
1549 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1550
1551 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1552 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001553 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001554 mDispatcher->notifyDeviceReset(&args);
1555 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1556 0 /*expectedFlags*/);
1557}
1558
Svet Ganov5d3bc372020-01-26 23:11:07 -08001559TEST_F(InputDispatcherTest, TransferTouchFocus_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001560 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001561
1562 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001563 sp<FakeWindowHandle> firstWindow =
1564 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1565 sp<FakeWindowHandle> secondWindow =
1566 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001567
1568 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001570
1571 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001572 NotifyMotionArgs downMotionArgs =
1573 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1574 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001575 mDispatcher->notifyMotion(&downMotionArgs);
1576 // Only the first window should get the down event
1577 firstWindow->consumeMotionDown();
1578 secondWindow->assertNoEvents();
1579
1580 // Transfer touch focus to the second window
1581 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1582 // The first window gets cancel and the second gets down
1583 firstWindow->consumeMotionCancel();
1584 secondWindow->consumeMotionDown();
1585
1586 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001587 NotifyMotionArgs upMotionArgs =
1588 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1589 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001590 mDispatcher->notifyMotion(&upMotionArgs);
1591 // The first window gets no events and the second gets up
1592 firstWindow->assertNoEvents();
1593 secondWindow->consumeMotionUp();
1594}
1595
1596TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointerNoSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001597 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001598
1599 PointF touchPoint = {10, 10};
1600
1601 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001602 sp<FakeWindowHandle> firstWindow =
1603 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1604 sp<FakeWindowHandle> secondWindow =
1605 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001606
1607 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001609
1610 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001611 NotifyMotionArgs downMotionArgs =
1612 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1613 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001614 mDispatcher->notifyMotion(&downMotionArgs);
1615 // Only the first window should get the down event
1616 firstWindow->consumeMotionDown();
1617 secondWindow->assertNoEvents();
1618
1619 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001620 NotifyMotionArgs pointerDownMotionArgs =
1621 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1622 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1623 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1624 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001625 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1626 // Only the first window should get the pointer down event
1627 firstWindow->consumeMotionPointerDown(1);
1628 secondWindow->assertNoEvents();
1629
1630 // Transfer touch focus to the second window
1631 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1632 // The first window gets cancel and the second gets down and pointer down
1633 firstWindow->consumeMotionCancel();
1634 secondWindow->consumeMotionDown();
1635 secondWindow->consumeMotionPointerDown(1);
1636
1637 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001638 NotifyMotionArgs pointerUpMotionArgs =
1639 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1640 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1641 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1642 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001643 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1644 // The first window gets nothing and the second gets pointer up
1645 firstWindow->assertNoEvents();
1646 secondWindow->consumeMotionPointerUp(1);
1647
1648 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001649 NotifyMotionArgs upMotionArgs =
1650 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1651 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001652 mDispatcher->notifyMotion(&upMotionArgs);
1653 // The first window gets nothing and the second gets up
1654 firstWindow->assertNoEvents();
1655 secondWindow->consumeMotionUp();
1656}
1657
1658TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001659 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001660
1661 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001662 sp<FakeWindowHandle> firstWindow =
1663 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001664 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001665 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1666 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001667
1668 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001669 sp<FakeWindowHandle> secondWindow =
1670 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001671 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001672 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1673 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001674
1675 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001677
1678 PointF pointInFirst = {300, 200};
1679 PointF pointInSecond = {300, 600};
1680
1681 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001682 NotifyMotionArgs firstDownMotionArgs =
1683 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1684 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001685 mDispatcher->notifyMotion(&firstDownMotionArgs);
1686 // Only the first window should get the down event
1687 firstWindow->consumeMotionDown();
1688 secondWindow->assertNoEvents();
1689
1690 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001691 NotifyMotionArgs secondDownMotionArgs =
1692 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1693 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1694 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1695 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001696 mDispatcher->notifyMotion(&secondDownMotionArgs);
1697 // The first window gets a move and the second a down
1698 firstWindow->consumeMotionMove();
1699 secondWindow->consumeMotionDown();
1700
1701 // Transfer touch focus to the second window
1702 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1703 // The first window gets cancel and the new gets pointer down (it already saw down)
1704 firstWindow->consumeMotionCancel();
1705 secondWindow->consumeMotionPointerDown(1);
1706
1707 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001708 NotifyMotionArgs pointerUpMotionArgs =
1709 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1710 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1711 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1712 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001713 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1714 // The first window gets nothing and the second gets pointer up
1715 firstWindow->assertNoEvents();
1716 secondWindow->consumeMotionPointerUp(1);
1717
1718 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001719 NotifyMotionArgs upMotionArgs =
1720 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1721 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001722 mDispatcher->notifyMotion(&upMotionArgs);
1723 // The first window gets nothing and the second gets up
1724 firstWindow->assertNoEvents();
1725 secondWindow->consumeMotionUp();
1726}
1727
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001728TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001729 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001730 sp<FakeWindowHandle> window =
1731 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1732
Vishnu Nair47074b82020-08-14 11:54:47 -07001733 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001735 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001736
1737 window->consumeFocusEvent(true);
1738
1739 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1740 mDispatcher->notifyKey(&keyArgs);
1741
1742 // Window should receive key down event.
1743 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1744}
1745
1746TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001747 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001748 sp<FakeWindowHandle> window =
1749 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1750
Arthur Hung72d8dc32020-03-28 00:48:39 +00001751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001752
1753 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1754 mDispatcher->notifyKey(&keyArgs);
1755 mDispatcher->waitForIdle();
1756
1757 window->assertNoEvents();
1758}
1759
1760// If a window is touchable, but does not have focus, it should receive motion events, but not keys
1761TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07001762 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001763 sp<FakeWindowHandle> window =
1764 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1765
Arthur Hung72d8dc32020-03-28 00:48:39 +00001766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001767
1768 // Send key
1769 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1770 mDispatcher->notifyKey(&keyArgs);
1771 // Send motion
1772 NotifyMotionArgs motionArgs =
1773 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1774 ADISPLAY_ID_DEFAULT);
1775 mDispatcher->notifyMotion(&motionArgs);
1776
1777 // Window should receive only the motion event
1778 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1779 window->assertNoEvents(); // Key event or focus event will not be received
1780}
1781
chaviwd1c23182019-12-20 18:44:56 -08001782class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00001783public:
1784 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08001785 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07001786 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00001787 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07001788 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00001789 }
1790
chaviwd1c23182019-12-20 18:44:56 -08001791 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
1792
1793 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1794 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
1795 expectedDisplayId, expectedFlags);
1796 }
1797
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001798 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
1799
1800 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
1801
chaviwd1c23182019-12-20 18:44:56 -08001802 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1803 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
1804 expectedDisplayId, expectedFlags);
1805 }
1806
1807 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1808 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
1809 expectedDisplayId, expectedFlags);
1810 }
1811
1812 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
1813
1814private:
1815 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00001816};
1817
1818// Tests for gesture monitors
1819TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001820 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001821 sp<FakeWindowHandle> window =
1822 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001823 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001824
chaviwd1c23182019-12-20 18:44:56 -08001825 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1826 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001827
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001828 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001829 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001830 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001831 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001832 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001833}
1834
1835TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001836 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001837 sp<FakeWindowHandle> window =
1838 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1839
1840 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001841 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001842
Arthur Hung72d8dc32020-03-28 00:48:39 +00001843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001844 setFocusedWindow(window);
1845
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001846 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001847
chaviwd1c23182019-12-20 18:44:56 -08001848 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1849 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001850
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
1852 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001853 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001854 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00001855}
1856
1857TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001858 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001859 sp<FakeWindowHandle> window =
1860 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001862
chaviwd1c23182019-12-20 18:44:56 -08001863 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1864 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001865
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001867 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001868 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001869 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001870 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001871
1872 window->releaseChannel();
1873
chaviwd1c23182019-12-20 18:44:56 -08001874 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00001875
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001877 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08001879 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001880}
1881
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001882TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
1883 FakeMonitorReceiver monitor =
1884 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
1885 true /*isGestureMonitor*/);
1886
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001887 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001888 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
1889 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
1890 ASSERT_TRUE(consumeSeq);
1891
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001892 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(DISPATCHING_TIMEOUT,
1893 monitor.getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001894 monitor.finishEvent(*consumeSeq);
1895 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001896 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(monitor.getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001897}
1898
chaviw81e2bb92019-12-18 15:03:51 -08001899TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001900 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08001901 sp<FakeWindowHandle> window =
1902 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1903
Arthur Hung72d8dc32020-03-28 00:48:39 +00001904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08001905
1906 NotifyMotionArgs motionArgs =
1907 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1908 ADISPLAY_ID_DEFAULT);
1909
1910 mDispatcher->notifyMotion(&motionArgs);
1911 // Window should receive motion down event.
1912 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1913
1914 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001915 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08001916 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1917 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
1918 motionArgs.pointerCoords[0].getX() - 10);
1919
1920 mDispatcher->notifyMotion(&motionArgs);
1921 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
1922 0 /*expectedFlags*/);
1923}
1924
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001925/**
1926 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
1927 * the device default right away. In the test scenario, we check both the default value,
1928 * and the action of enabling / disabling.
1929 */
1930TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07001931 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001932 sp<FakeWindowHandle> window =
1933 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1934
1935 // Set focused application.
1936 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001937 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001938
1939 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00001940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001941 setFocusedWindow(window);
1942
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001943 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1944
1945 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07001946 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001947 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001948 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
1949
1950 SCOPED_TRACE("Disable touch mode");
1951 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07001952 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001954 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001955 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
1956
1957 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07001958 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001960 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
1961
1962 SCOPED_TRACE("Enable touch mode again");
1963 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07001964 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001965 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001966 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001967 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1968
1969 window->assertNoEvents();
1970}
1971
Gang Wange9087892020-01-07 12:17:14 -05001972TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001973 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05001974 sp<FakeWindowHandle> window =
1975 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1976
1977 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001978 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05001979
Arthur Hung72d8dc32020-03-28 00:48:39 +00001980 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001981 setFocusedWindow(window);
1982
Gang Wange9087892020-01-07 12:17:14 -05001983 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1984
1985 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
1986 mDispatcher->notifyKey(&keyArgs);
1987
1988 InputEvent* event = window->consume();
1989 ASSERT_NE(event, nullptr);
1990
1991 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
1992 ASSERT_NE(verified, nullptr);
1993 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
1994
1995 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
1996 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
1997 ASSERT_EQ(keyArgs.source, verified->source);
1998 ASSERT_EQ(keyArgs.displayId, verified->displayId);
1999
2000 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2001
2002 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2003 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002004 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2005 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2006 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2007 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2008 ASSERT_EQ(0, verifiedKey.repeatCount);
2009}
2010
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002011TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002012 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002013 sp<FakeWindowHandle> window =
2014 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2015
2016 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2017
Arthur Hung72d8dc32020-03-28 00:48:39 +00002018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002019
2020 NotifyMotionArgs motionArgs =
2021 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2022 ADISPLAY_ID_DEFAULT);
2023 mDispatcher->notifyMotion(&motionArgs);
2024
2025 InputEvent* event = window->consume();
2026 ASSERT_NE(event, nullptr);
2027
2028 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2029 ASSERT_NE(verified, nullptr);
2030 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2031
2032 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2033 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2034 EXPECT_EQ(motionArgs.source, verified->source);
2035 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2036
2037 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2038
2039 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2040 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2041 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2042 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2043 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2044 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2045 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2046}
2047
chaviw09c8d2d2020-08-24 15:48:26 -07002048/**
2049 * Ensure that separate calls to sign the same data are generating the same key.
2050 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2051 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2052 * tests.
2053 */
2054TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2055 KeyEvent event = getTestKeyEvent();
2056 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2057
2058 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2059 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2060 ASSERT_EQ(hmac1, hmac2);
2061}
2062
2063/**
2064 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2065 */
2066TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2067 KeyEvent event = getTestKeyEvent();
2068 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2069 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2070
2071 verifiedEvent.deviceId += 1;
2072 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2073
2074 verifiedEvent.source += 1;
2075 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2076
2077 verifiedEvent.eventTimeNanos += 1;
2078 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2079
2080 verifiedEvent.displayId += 1;
2081 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2082
2083 verifiedEvent.action += 1;
2084 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2085
2086 verifiedEvent.downTimeNanos += 1;
2087 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2088
2089 verifiedEvent.flags += 1;
2090 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2091
2092 verifiedEvent.keyCode += 1;
2093 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2094
2095 verifiedEvent.scanCode += 1;
2096 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2097
2098 verifiedEvent.metaState += 1;
2099 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2100
2101 verifiedEvent.repeatCount += 1;
2102 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2103}
2104
Vishnu Nair958da932020-08-21 17:12:37 -07002105TEST_F(InputDispatcherTest, SetFocusedWindow) {
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 // Top window is also focusable but is not granted focus.
2114 windowTop->setFocusable(true);
2115 windowSecond->setFocusable(true);
2116 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2117 setFocusedWindow(windowSecond);
2118
2119 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002120 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2121 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002122
2123 // Focused window should receive event.
2124 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2125 windowTop->assertNoEvents();
2126}
2127
2128TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2129 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2130 sp<FakeWindowHandle> window =
2131 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2132 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2133
2134 window->setFocusable(true);
2135 // Release channel for window is no longer valid.
2136 window->releaseChannel();
2137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2138 setFocusedWindow(window);
2139
2140 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002141 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2142 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002143
2144 // window channel is invalid, so it should not receive any input event.
2145 window->assertNoEvents();
2146}
2147
2148TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2149 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2150 sp<FakeWindowHandle> window =
2151 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2152 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2153
2154 // Window is not focusable.
2155 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2156 setFocusedWindow(window);
2157
2158 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002159 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2160 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002161
2162 // window is invalid, so it should not receive any input event.
2163 window->assertNoEvents();
2164}
2165
2166TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2167 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2168 sp<FakeWindowHandle> windowTop =
2169 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2170 sp<FakeWindowHandle> windowSecond =
2171 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2172 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2173
2174 windowTop->setFocusable(true);
2175 windowSecond->setFocusable(true);
2176 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2177 setFocusedWindow(windowTop);
2178 windowTop->consumeFocusEvent(true);
2179
2180 setFocusedWindow(windowSecond, windowTop);
2181 windowSecond->consumeFocusEvent(true);
2182 windowTop->consumeFocusEvent(false);
2183
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002184 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2185 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002186
2187 // Focused window should receive event.
2188 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2189}
2190
2191TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2192 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2193 sp<FakeWindowHandle> windowTop =
2194 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2195 sp<FakeWindowHandle> windowSecond =
2196 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2197 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2198
2199 windowTop->setFocusable(true);
2200 windowSecond->setFocusable(true);
2201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2202 setFocusedWindow(windowSecond, windowTop);
2203
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002204 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2205 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002206
2207 // Event should be dropped.
2208 windowTop->assertNoEvents();
2209 windowSecond->assertNoEvents();
2210}
2211
2212TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2213 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2214 sp<FakeWindowHandle> window =
2215 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2216 sp<FakeWindowHandle> previousFocusedWindow =
2217 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2218 ADISPLAY_ID_DEFAULT);
2219 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2220
2221 window->setFocusable(true);
2222 previousFocusedWindow->setFocusable(true);
2223 window->setVisible(false);
2224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2225 setFocusedWindow(previousFocusedWindow);
2226 previousFocusedWindow->consumeFocusEvent(true);
2227
2228 // Requesting focus on invisible window takes focus from currently focused window.
2229 setFocusedWindow(window);
2230 previousFocusedWindow->consumeFocusEvent(false);
2231
2232 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002233 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002234 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002235 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002236
2237 // Window does not get focus event or key down.
2238 window->assertNoEvents();
2239
2240 // Window becomes visible.
2241 window->setVisible(true);
2242 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2243
2244 // Window receives focus event.
2245 window->consumeFocusEvent(true);
2246 // Focused window receives key down.
2247 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2248}
2249
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002250/**
2251 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2252 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2253 * of the 'slipperyEnterWindow'.
2254 *
2255 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2256 * a way so that the touched location is no longer covered by the top window.
2257 *
2258 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2259 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2260 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2261 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2262 * with ACTION_DOWN).
2263 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2264 * window moved itself away from the touched location and had Flag::SLIPPERY.
2265 *
2266 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2267 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2268 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2269 *
2270 * In this test, we ensure that the event received by the bottom window has
2271 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2272 */
2273TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2274 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2275 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2276
2277 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2278 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2279
2280 sp<FakeWindowHandle> slipperyExitWindow =
2281 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2282 slipperyExitWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2283 InputWindowInfo::Flag::SLIPPERY);
2284 // Make sure this one overlaps the bottom window
2285 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2286 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2287 // one. Windows with the same owner are not considered to be occluding each other.
2288 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2289
2290 sp<FakeWindowHandle> slipperyEnterWindow =
2291 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2292 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2293
2294 mDispatcher->setInputWindows(
2295 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2296
2297 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2298 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2299 ADISPLAY_ID_DEFAULT, {{50, 50}});
2300 mDispatcher->notifyMotion(&args);
2301 slipperyExitWindow->consumeMotionDown();
2302 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2303 mDispatcher->setInputWindows(
2304 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2305
2306 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2307 ADISPLAY_ID_DEFAULT, {{51, 51}});
2308 mDispatcher->notifyMotion(&args);
2309
2310 slipperyExitWindow->consumeMotionCancel();
2311
2312 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2313 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2314}
2315
Garfield Tan1c7bc862020-01-28 13:24:04 -08002316class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2317protected:
2318 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2319 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2320
Chris Yea209fde2020-07-22 13:54:51 -07002321 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002322 sp<FakeWindowHandle> mWindow;
2323
2324 virtual void SetUp() override {
2325 mFakePolicy = new FakeInputDispatcherPolicy();
2326 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2327 mDispatcher = new InputDispatcher(mFakePolicy);
2328 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2329 ASSERT_EQ(OK, mDispatcher->start());
2330
2331 setUpWindow();
2332 }
2333
2334 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002335 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002336 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2337
Vishnu Nair47074b82020-08-14 11:54:47 -07002338 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002340 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002341 mWindow->consumeFocusEvent(true);
2342 }
2343
Chris Ye2ad95392020-09-01 13:44:44 -07002344 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002345 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002346 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002347 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2348 mDispatcher->notifyKey(&keyArgs);
2349
2350 // Window should receive key down event.
2351 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2352 }
2353
2354 void expectKeyRepeatOnce(int32_t repeatCount) {
2355 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2356 InputEvent* repeatEvent = mWindow->consume();
2357 ASSERT_NE(nullptr, repeatEvent);
2358
2359 uint32_t eventType = repeatEvent->getType();
2360 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2361
2362 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2363 uint32_t eventAction = repeatKeyEvent->getAction();
2364 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2365 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2366 }
2367
Chris Ye2ad95392020-09-01 13:44:44 -07002368 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002369 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002370 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002371 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2372 mDispatcher->notifyKey(&keyArgs);
2373
2374 // Window should receive key down event.
2375 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2376 0 /*expectedFlags*/);
2377 }
2378};
2379
2380TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002381 sendAndConsumeKeyDown(1 /* deviceId */);
2382 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2383 expectKeyRepeatOnce(repeatCount);
2384 }
2385}
2386
2387TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2388 sendAndConsumeKeyDown(1 /* deviceId */);
2389 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2390 expectKeyRepeatOnce(repeatCount);
2391 }
2392 sendAndConsumeKeyDown(2 /* deviceId */);
2393 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002394 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2395 expectKeyRepeatOnce(repeatCount);
2396 }
2397}
2398
2399TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002400 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002401 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002402 sendAndConsumeKeyUp(1 /* deviceId */);
2403 mWindow->assertNoEvents();
2404}
2405
2406TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2407 sendAndConsumeKeyDown(1 /* deviceId */);
2408 expectKeyRepeatOnce(1 /*repeatCount*/);
2409 sendAndConsumeKeyDown(2 /* deviceId */);
2410 expectKeyRepeatOnce(1 /*repeatCount*/);
2411 // Stale key up from device 1.
2412 sendAndConsumeKeyUp(1 /* deviceId */);
2413 // Device 2 is still down, keep repeating
2414 expectKeyRepeatOnce(2 /*repeatCount*/);
2415 expectKeyRepeatOnce(3 /*repeatCount*/);
2416 // Device 2 key up
2417 sendAndConsumeKeyUp(2 /* deviceId */);
2418 mWindow->assertNoEvents();
2419}
2420
2421TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2422 sendAndConsumeKeyDown(1 /* deviceId */);
2423 expectKeyRepeatOnce(1 /*repeatCount*/);
2424 sendAndConsumeKeyDown(2 /* deviceId */);
2425 expectKeyRepeatOnce(1 /*repeatCount*/);
2426 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2427 sendAndConsumeKeyUp(2 /* deviceId */);
2428 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002429 mWindow->assertNoEvents();
2430}
2431
2432TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002433 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002434 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2435 InputEvent* repeatEvent = mWindow->consume();
2436 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2437 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2438 IdGenerator::getSource(repeatEvent->getId()));
2439 }
2440}
2441
2442TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002443 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002444
2445 std::unordered_set<int32_t> idSet;
2446 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2447 InputEvent* repeatEvent = mWindow->consume();
2448 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2449 int32_t id = repeatEvent->getId();
2450 EXPECT_EQ(idSet.end(), idSet.find(id));
2451 idSet.insert(id);
2452 }
2453}
2454
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002455/* Test InputDispatcher for MultiDisplay */
2456class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2457public:
2458 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002459 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002460 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002461
Chris Yea209fde2020-07-22 13:54:51 -07002462 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002463 windowInPrimary =
2464 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002465
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002466 // Set focus window for primary display, but focused display would be second one.
2467 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002468 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002470 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002471 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002472
Chris Yea209fde2020-07-22 13:54:51 -07002473 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002474 windowInSecondary =
2475 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002476 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002477 // Set focus display to second one.
2478 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2479 // Set focus window for second display.
2480 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002481 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002482 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002483 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002484 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002485 }
2486
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002487 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002488 InputDispatcherTest::TearDown();
2489
Chris Yea209fde2020-07-22 13:54:51 -07002490 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002491 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002492 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002493 windowInSecondary.clear();
2494 }
2495
2496protected:
Chris Yea209fde2020-07-22 13:54:51 -07002497 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002498 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002499 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002500 sp<FakeWindowHandle> windowInSecondary;
2501};
2502
2503TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2504 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2506 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2507 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002508 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002509 windowInSecondary->assertNoEvents();
2510
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002511 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002512 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2513 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2514 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002515 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002516 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002517}
2518
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002519TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002520 // Test inject a key down with display id specified.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002521 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2522 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002523 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002524 windowInSecondary->assertNoEvents();
2525
2526 // Test inject a key down without display id specified.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002527 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2528 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002529 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002530 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002531
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002532 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002533 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002534
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002535 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002536 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2537 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002538
2539 // Test inject a key down, should timeout because of no target window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002540 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2541 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08002542 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002543 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002544 windowInSecondary->assertNoEvents();
2545}
2546
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002547// Test per-display input monitors for motion event.
2548TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002549 FakeMonitorReceiver monitorInPrimary =
2550 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2551 FakeMonitorReceiver monitorInSecondary =
2552 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002553
2554 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002555 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2556 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2557 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002558 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002559 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002560 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002561 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002562
2563 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2565 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002567 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002568 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002569 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08002570 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002571
2572 // Test inject a non-pointer motion event.
2573 // If specific a display, it will dispatch to the focused window of particular display,
2574 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2576 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
2577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002578 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002579 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002580 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002581 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002582}
2583
2584// Test per-display input monitors for key event.
2585TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002586 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08002587 FakeMonitorReceiver monitorInPrimary =
2588 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2589 FakeMonitorReceiver monitorInSecondary =
2590 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002591
2592 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2594 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002595 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002596 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002597 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002598 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002599}
2600
Vishnu Nair958da932020-08-21 17:12:37 -07002601TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
2602 sp<FakeWindowHandle> secondWindowInPrimary =
2603 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2604 secondWindowInPrimary->setFocusable(true);
2605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
2606 setFocusedWindow(secondWindowInPrimary);
2607 windowInPrimary->consumeFocusEvent(false);
2608 secondWindowInPrimary->consumeFocusEvent(true);
2609
2610 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2612 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002613 windowInPrimary->assertNoEvents();
2614 windowInSecondary->assertNoEvents();
2615 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2616}
2617
Jackal Guof9696682018-10-05 12:23:23 +08002618class InputFilterTest : public InputDispatcherTest {
2619protected:
2620 static constexpr int32_t SECOND_DISPLAY_ID = 1;
2621
2622 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
2623 NotifyMotionArgs motionArgs;
2624
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002625 motionArgs =
2626 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08002627 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002628 motionArgs =
2629 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08002630 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002631 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002632 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002633 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002634 } else {
2635 mFakePolicy->assertFilterInputEventWasNotCalled();
2636 }
2637 }
2638
2639 void testNotifyKey(bool expectToBeFiltered) {
2640 NotifyKeyArgs keyArgs;
2641
2642 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2643 mDispatcher->notifyKey(&keyArgs);
2644 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
2645 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002646 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002647
2648 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002649 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002650 } else {
2651 mFakePolicy->assertFilterInputEventWasNotCalled();
2652 }
2653 }
2654};
2655
2656// Test InputFilter for MotionEvent
2657TEST_F(InputFilterTest, MotionEvent_InputFilter) {
2658 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
2659 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2660 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2661
2662 // Enable InputFilter
2663 mDispatcher->setInputFilterEnabled(true);
2664 // Test touch on both primary and second display, and check if both events are filtered.
2665 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
2666 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
2667
2668 // Disable InputFilter
2669 mDispatcher->setInputFilterEnabled(false);
2670 // Test touch on both primary and second display, and check if both events aren't filtered.
2671 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2672 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2673}
2674
2675// Test InputFilter for KeyEvent
2676TEST_F(InputFilterTest, KeyEvent_InputFilter) {
2677 // Since the InputFilter is disabled by default, check if key event aren't filtered.
2678 testNotifyKey(/*expectToBeFiltered*/ false);
2679
2680 // Enable InputFilter
2681 mDispatcher->setInputFilterEnabled(true);
2682 // Send a key event, and check if it is filtered.
2683 testNotifyKey(/*expectToBeFiltered*/ true);
2684
2685 // Disable InputFilter
2686 mDispatcher->setInputFilterEnabled(false);
2687 // Send a key event, and check if it isn't filtered.
2688 testNotifyKey(/*expectToBeFiltered*/ false);
2689}
2690
chaviwfd6d3512019-03-25 13:23:49 -07002691class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002692 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07002693 InputDispatcherTest::SetUp();
2694
Chris Yea209fde2020-07-22 13:54:51 -07002695 std::shared_ptr<FakeApplicationHandle> application =
2696 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002697 mUnfocusedWindow =
2698 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002699 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
2700 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2701 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002702 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002703
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002704 mFocusedWindow =
2705 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2706 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01002707 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002708
2709 // Set focused application.
2710 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002711 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07002712
2713 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002715 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002716 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07002717 }
2718
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002719 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07002720 InputDispatcherTest::TearDown();
2721
2722 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002723 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07002724 }
2725
2726protected:
2727 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002728 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002729 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07002730};
2731
2732// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2733// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
2734// the onPointerDownOutsideFocus callback.
2735TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002737 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2738 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002740 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002741
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002742 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07002743 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
2744}
2745
2746// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
2747// DOWN on the window that doesn't have focus. Ensure no window received the
2748// onPointerDownOutsideFocus callback.
2749TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002751 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002752 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002753 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002754
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002755 ASSERT_TRUE(mDispatcher->waitForIdle());
2756 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002757}
2758
2759// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
2760// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
2761TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002762 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2763 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002764 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002765
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002766 ASSERT_TRUE(mDispatcher->waitForIdle());
2767 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002768}
2769
2770// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2771// DOWN on the window that already has focus. Ensure no window received the
2772// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002773TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002775 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002776 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002777 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002778 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002779
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002780 ASSERT_TRUE(mDispatcher->waitForIdle());
2781 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002782}
2783
chaviwaf87b3e2019-10-01 16:59:28 -07002784// These tests ensures we can send touch events to a single client when there are multiple input
2785// windows that point to the same client token.
2786class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
2787 virtual void SetUp() override {
2788 InputDispatcherTest::SetUp();
2789
Chris Yea209fde2020-07-22 13:54:51 -07002790 std::shared_ptr<FakeApplicationHandle> application =
2791 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07002792 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
2793 ADISPLAY_ID_DEFAULT);
2794 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
2795 // 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 +01002796 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2797 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002798 mWindow1->setFrame(Rect(0, 0, 100, 100));
2799
2800 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
2801 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01002802 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2803 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002804 mWindow2->setFrame(Rect(100, 100, 200, 200));
2805
Arthur Hung72d8dc32020-03-28 00:48:39 +00002806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07002807 }
2808
2809protected:
2810 sp<FakeWindowHandle> mWindow1;
2811 sp<FakeWindowHandle> mWindow2;
2812
2813 // Helper function to convert the point from screen coordinates into the window's space
2814 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07002815 vec2 vals = windowInfo->transform.transform(point.x, point.y);
2816 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07002817 }
2818
2819 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
2820 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002821 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07002822 InputEvent* event = window->consume();
2823
2824 ASSERT_NE(nullptr, event) << name.c_str()
2825 << ": consumer should have returned non-NULL event.";
2826
2827 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2828 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2829 << " event, got " << inputEventTypeToString(event->getType()) << " event";
2830
2831 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2832 EXPECT_EQ(expectedAction, motionEvent.getAction());
2833
2834 for (size_t i = 0; i < points.size(); i++) {
2835 float expectedX = points[i].x;
2836 float expectedY = points[i].y;
2837
2838 EXPECT_EQ(expectedX, motionEvent.getX(i))
2839 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
2840 << ", got " << motionEvent.getX(i);
2841 EXPECT_EQ(expectedY, motionEvent.getY(i))
2842 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
2843 << ", got " << motionEvent.getY(i);
2844 }
2845 }
chaviw9eaa22c2020-07-01 16:21:27 -07002846
2847 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
2848 std::vector<PointF> expectedPoints) {
2849 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
2850 ADISPLAY_ID_DEFAULT, touchedPoints);
2851 mDispatcher->notifyMotion(&motionArgs);
2852
2853 // Always consume from window1 since it's the window that has the InputReceiver
2854 consumeMotionEvent(mWindow1, action, expectedPoints);
2855 }
chaviwaf87b3e2019-10-01 16:59:28 -07002856};
2857
2858TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
2859 // Touch Window 1
2860 PointF touchedPoint = {10, 10};
2861 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002862 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002863
2864 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07002865 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002866
2867 // Touch Window 2
2868 touchedPoint = {150, 150};
2869 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002870 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002871}
2872
chaviw9eaa22c2020-07-01 16:21:27 -07002873TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
2874 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07002875 mWindow2->setWindowScale(0.5f, 0.5f);
2876
2877 // Touch Window 1
2878 PointF touchedPoint = {10, 10};
2879 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002880 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002881 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07002882 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002883
2884 // Touch Window 2
2885 touchedPoint = {150, 150};
2886 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002887 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
2888 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002889
chaviw9eaa22c2020-07-01 16:21:27 -07002890 // Update the transform so rotation is set
2891 mWindow2->setWindowTransform(0, -1, 1, 0);
2892 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
2893 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002894}
2895
chaviw9eaa22c2020-07-01 16:21:27 -07002896TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002897 mWindow2->setWindowScale(0.5f, 0.5f);
2898
2899 // Touch Window 1
2900 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2901 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002902 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002903
2904 // Touch Window 2
2905 int32_t actionPointerDown =
2906 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002907 touchedPoints.push_back(PointF{150, 150});
2908 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2909 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002910
chaviw9eaa22c2020-07-01 16:21:27 -07002911 // Release Window 2
2912 int32_t actionPointerUp =
2913 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2914 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
2915 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002916
chaviw9eaa22c2020-07-01 16:21:27 -07002917 // Update the transform so rotation is set for Window 2
2918 mWindow2->setWindowTransform(0, -1, 1, 0);
2919 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2920 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002921}
2922
chaviw9eaa22c2020-07-01 16:21:27 -07002923TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002924 mWindow2->setWindowScale(0.5f, 0.5f);
2925
2926 // Touch Window 1
2927 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2928 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002929 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002930
2931 // Touch Window 2
2932 int32_t actionPointerDown =
2933 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002934 touchedPoints.push_back(PointF{150, 150});
2935 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002936
chaviw9eaa22c2020-07-01 16:21:27 -07002937 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002938
2939 // Move both windows
2940 touchedPoints = {{20, 20}, {175, 175}};
2941 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2942 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2943
chaviw9eaa22c2020-07-01 16:21:27 -07002944 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002945
chaviw9eaa22c2020-07-01 16:21:27 -07002946 // Release Window 2
2947 int32_t actionPointerUp =
2948 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2949 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
2950 expectedPoints.pop_back();
2951
2952 // Touch Window 2
2953 mWindow2->setWindowTransform(0, -1, 1, 0);
2954 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2955 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
2956
2957 // Move both windows
2958 touchedPoints = {{20, 20}, {175, 175}};
2959 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2960 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2961
2962 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002963}
2964
2965TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
2966 mWindow1->setWindowScale(0.5f, 0.5f);
2967
2968 // Touch Window 1
2969 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2970 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002971 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002972
2973 // Touch Window 2
2974 int32_t actionPointerDown =
2975 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002976 touchedPoints.push_back(PointF{150, 150});
2977 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002978
chaviw9eaa22c2020-07-01 16:21:27 -07002979 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002980
2981 // Move both windows
2982 touchedPoints = {{20, 20}, {175, 175}};
2983 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2984 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2985
chaviw9eaa22c2020-07-01 16:21:27 -07002986 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002987}
2988
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002989class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
2990 virtual void SetUp() override {
2991 InputDispatcherTest::SetUp();
2992
Chris Yea209fde2020-07-22 13:54:51 -07002993 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002994 mApplication->setDispatchingTimeout(20ms);
2995 mWindow =
2996 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2997 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05002998 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07002999 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003000 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3001 // window.
Michael Wright44753b12020-07-08 13:48:11 +01003002 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003003
3004 // Set focused application.
3005 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3006
3007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003008 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003009 mWindow->consumeFocusEvent(true);
3010 }
3011
3012 virtual void TearDown() override {
3013 InputDispatcherTest::TearDown();
3014 mWindow.clear();
3015 }
3016
3017protected:
Chris Yea209fde2020-07-22 13:54:51 -07003018 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003019 sp<FakeWindowHandle> mWindow;
3020 static constexpr PointF WINDOW_LOCATION = {20, 20};
3021
3022 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003024 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3025 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003027 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3028 WINDOW_LOCATION));
3029 }
3030};
3031
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003032// Send a tap and respond, which should not cause an ANR.
3033TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3034 tapOnWindow();
3035 mWindow->consumeMotionDown();
3036 mWindow->consumeMotionUp();
3037 ASSERT_TRUE(mDispatcher->waitForIdle());
3038 mFakePolicy->assertNotifyAnrWasNotCalled();
3039}
3040
3041// Send a regular key and respond, which should not cause an ANR.
3042TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003044 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3045 ASSERT_TRUE(mDispatcher->waitForIdle());
3046 mFakePolicy->assertNotifyAnrWasNotCalled();
3047}
3048
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003049TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3050 mWindow->setFocusable(false);
3051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3052 mWindow->consumeFocusEvent(false);
3053
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003054 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003055 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003056 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003058 // Key will not go to window because we have no focused window.
3059 // The 'no focused window' ANR timer should start instead.
3060
3061 // Now, the focused application goes away.
3062 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3063 // The key should get dropped and there should be no ANR.
3064
3065 ASSERT_TRUE(mDispatcher->waitForIdle());
3066 mFakePolicy->assertNotifyAnrWasNotCalled();
3067}
3068
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003069// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003070// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3071// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003072TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003074 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3075 WINDOW_LOCATION));
3076
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003077 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3078 ASSERT_TRUE(sequenceNum);
3079 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003080 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003081
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003082 mWindow->finishEvent(*sequenceNum);
3083 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3084 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003085 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003086 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003087}
3088
3089// Send a key to the app and have the app not respond right away.
3090TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3091 // Inject a key, and don't respond - expect that ANR is called.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003093 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3094 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003095 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003096 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003097 ASSERT_TRUE(mDispatcher->waitForIdle());
3098}
3099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003100// We have a focused application, but no focused window
3101TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003102 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3104 mWindow->consumeFocusEvent(false);
3105
3106 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003108 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3109 WINDOW_LOCATION));
3110 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3111 mDispatcher->waitForIdle();
3112 mFakePolicy->assertNotifyAnrWasNotCalled();
3113
3114 // Once a focused event arrives, we get an ANR for this application
3115 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3116 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003117 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003118 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003119 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3120 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003121 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003122 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003123 ASSERT_TRUE(mDispatcher->waitForIdle());
3124}
3125
3126// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003127// Make sure that we don't notify policy twice about the same ANR.
3128TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003129 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003130 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3131 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003132
3133 // Once a focused event arrives, we get an ANR for this application
3134 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3135 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003136 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003137 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003138 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3139 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003140 const std::chrono::duration appTimeout =
3141 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003142 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003143
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003144 std::this_thread::sleep_for(appTimeout);
3145 // ANR should not be raised again. It is up to policy to do that if it desires.
3146 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003147
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003148 // If we now get a focused window, the ANR should stop, but the policy handles that via
3149 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003150 ASSERT_TRUE(mDispatcher->waitForIdle());
3151}
3152
3153// We have a focused application, but no focused window
3154TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003155 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003156 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3157 mWindow->consumeFocusEvent(false);
3158
3159 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003160 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003161 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003162 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3163 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003164
3165 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003166 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003167
3168 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003169 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003170 ASSERT_TRUE(mDispatcher->waitForIdle());
3171 mWindow->assertNoEvents();
3172}
3173
3174/**
3175 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3176 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3177 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3178 * the ANR mechanism should still work.
3179 *
3180 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3181 * DOWN event, while not responding on the second one.
3182 */
3183TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3184 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3185 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3186 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3187 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3188 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003189 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003190
3191 // Now send ACTION_UP, with identical timestamp
3192 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3193 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3194 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3195 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003196 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003197
3198 // We have now sent down and up. Let's consume first event and then ANR on the second.
3199 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3200 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003201 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003202}
3203
3204// If an app is not responding to a key event, gesture monitors should continue to receive
3205// new motion events
3206TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3207 FakeMonitorReceiver monitor =
3208 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3209 true /*isGestureMonitor*/);
3210
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003211 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3212 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003213 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003215
3216 // Stuck on the ACTION_UP
3217 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003218 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003219
3220 // New tap will go to the gesture monitor, but not to the window
3221 tapOnWindow();
3222 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3223 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3224
3225 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3226 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003227 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003228 mWindow->assertNoEvents();
3229 monitor.assertNoEvents();
3230}
3231
3232// If an app is not responding to a motion event, gesture monitors should continue to receive
3233// new motion events
3234TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3235 FakeMonitorReceiver monitor =
3236 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3237 true /*isGestureMonitor*/);
3238
3239 tapOnWindow();
3240 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3241 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3242
3243 mWindow->consumeMotionDown();
3244 // Stuck on the ACTION_UP
3245 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003246 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003247
3248 // New tap will go to the gesture monitor, but not to the window
3249 tapOnWindow();
3250 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3251 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3252
3253 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3254 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003255 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003256 mWindow->assertNoEvents();
3257 monitor.assertNoEvents();
3258}
3259
3260// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3261// process events, you don't get an anr. When the window later becomes unresponsive again, you
3262// get an ANR again.
3263// 1. tap -> block on ACTION_UP -> receive ANR
3264// 2. consume all pending events (= queue becomes healthy again)
3265// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3266TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3267 tapOnWindow();
3268
3269 mWindow->consumeMotionDown();
3270 // Block on ACTION_UP
3271 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003272 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003273 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3274 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003275 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003276 mWindow->assertNoEvents();
3277
3278 tapOnWindow();
3279 mWindow->consumeMotionDown();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003280 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003281 mWindow->consumeMotionUp();
3282
3283 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003284 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
3285 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003286 mWindow->assertNoEvents();
3287}
3288
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003289// If a connection remains unresponsive for a while, make sure policy is only notified once about
3290// it.
3291TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003293 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3294 WINDOW_LOCATION));
3295
3296 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003297 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003298 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003299 // 'notifyConnectionUnresponsive' should only be called once per connection
3300 mFakePolicy->assertNotifyAnrWasNotCalled();
3301 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003302 mWindow->consumeMotionDown();
3303 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3304 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3305 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003306 mDispatcher->waitForIdle();
3307 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
3308 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003309}
3310
3311/**
3312 * If a window is processing a motion event, and then a key event comes in, the key event should
3313 * not to to the focused window until the motion is processed.
3314 *
3315 * Warning!!!
3316 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3317 * and the injection timeout that we specify when injecting the key.
3318 * We must have the injection timeout (10ms) be smaller than
3319 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3320 *
3321 * If that value changes, this test should also change.
3322 */
3323TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3324 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3326
3327 tapOnWindow();
3328 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3329 ASSERT_TRUE(downSequenceNum);
3330 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3331 ASSERT_TRUE(upSequenceNum);
3332 // Don't finish the events yet, and send a key
3333 // Injection will "succeed" because we will eventually give up and send the key to the focused
3334 // window even if motions are still being processed. But because the injection timeout is short,
3335 // we will receive INJECTION_TIMED_OUT as the result.
3336
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003337 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003338 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003339 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3340 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003341 // Key will not be sent to the window, yet, because the window is still processing events
3342 // and the key remains pending, waiting for the touch events to be processed
3343 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3344 ASSERT_FALSE(keySequenceNum);
3345
3346 std::this_thread::sleep_for(500ms);
3347 // if we wait long enough though, dispatcher will give up, and still send the key
3348 // to the focused window, even though we have not yet finished the motion event
3349 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3350 mWindow->finishEvent(*downSequenceNum);
3351 mWindow->finishEvent(*upSequenceNum);
3352}
3353
3354/**
3355 * If a window is processing a motion event, and then a key event comes in, the key event should
3356 * not go to the focused window until the motion is processed.
3357 * If then a new motion comes in, then the pending key event should be going to the currently
3358 * focused window right away.
3359 */
3360TEST_F(InputDispatcherSingleWindowAnr,
3361 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3362 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3364
3365 tapOnWindow();
3366 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3367 ASSERT_TRUE(downSequenceNum);
3368 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3369 ASSERT_TRUE(upSequenceNum);
3370 // Don't finish the events yet, and send a key
3371 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003373 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003374 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003375 // At this point, key is still pending, and should not be sent to the application yet.
3376 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3377 ASSERT_FALSE(keySequenceNum);
3378
3379 // Now tap down again. It should cause the pending key to go to the focused window right away.
3380 tapOnWindow();
3381 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3382 // the other events yet. We can finish events in any order.
3383 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3384 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3385 mWindow->consumeMotionDown();
3386 mWindow->consumeMotionUp();
3387 mWindow->assertNoEvents();
3388}
3389
3390class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3391 virtual void SetUp() override {
3392 InputDispatcherTest::SetUp();
3393
Chris Yea209fde2020-07-22 13:54:51 -07003394 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003395 mApplication->setDispatchingTimeout(10ms);
3396 mUnfocusedWindow =
3397 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3398 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3399 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3400 // window.
3401 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003402 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3403 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3404 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003405
3406 mFocusedWindow =
3407 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003408 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003409 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003410 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3411 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003412
3413 // Set focused application.
3414 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003415 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003416
3417 // Expect one focus window exist in display.
3418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003419 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003420 mFocusedWindow->consumeFocusEvent(true);
3421 }
3422
3423 virtual void TearDown() override {
3424 InputDispatcherTest::TearDown();
3425
3426 mUnfocusedWindow.clear();
3427 mFocusedWindow.clear();
3428 }
3429
3430protected:
Chris Yea209fde2020-07-22 13:54:51 -07003431 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003432 sp<FakeWindowHandle> mUnfocusedWindow;
3433 sp<FakeWindowHandle> mFocusedWindow;
3434 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3435 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3436 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3437
3438 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3439
3440 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3441
3442private:
3443 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003444 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003445 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3446 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003447 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003448 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3449 location));
3450 }
3451};
3452
3453// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3454// should be ANR'd first.
3455TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003457 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3458 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003459 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003460 mFocusedWindow->consumeMotionDown();
3461 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3462 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3463 // We consumed all events, so no ANR
3464 ASSERT_TRUE(mDispatcher->waitForIdle());
3465 mFakePolicy->assertNotifyAnrWasNotCalled();
3466
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003467 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003468 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3469 FOCUSED_WINDOW_LOCATION));
3470 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
3471 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003472
3473 const std::chrono::duration timeout =
3474 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003475 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
3476 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
3477 // sequence to make it consistent
3478 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003479 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003480 mFocusedWindow->consumeMotionDown();
3481 // This cancel is generated because the connection was unresponsive
3482 mFocusedWindow->consumeMotionCancel();
3483 mFocusedWindow->assertNoEvents();
3484 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003485 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003486 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
3487 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003488}
3489
3490// If we have 2 windows with identical timeouts that are both unresponsive,
3491// it doesn't matter which order they should have ANR.
3492// But we should receive ANR for both.
3493TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
3494 // Set the timeout for unfocused window to match the focused window
3495 mUnfocusedWindow->setDispatchingTimeout(10ms);
3496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3497
3498 tapOnFocusedWindow();
3499 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003500 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveConnectionToken(10ms);
3501 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveConnectionToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003502
3503 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003504 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
3505 mFocusedWindow->getToken() == anrConnectionToken2);
3506 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
3507 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003508
3509 ASSERT_TRUE(mDispatcher->waitForIdle());
3510 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003511
3512 mFocusedWindow->consumeMotionDown();
3513 mFocusedWindow->consumeMotionUp();
3514 mUnfocusedWindow->consumeMotionOutside();
3515
3516 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveConnectionToken();
3517 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveConnectionToken();
3518
3519 // Both applications should be marked as responsive, in any order
3520 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
3521 mFocusedWindow->getToken() == responsiveToken2);
3522 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
3523 mUnfocusedWindow->getToken() == responsiveToken2);
3524 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003525}
3526
3527// If a window is already not responding, the second tap on the same window should be ignored.
3528// We should also log an error to account for the dropped event (not tested here).
3529// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
3530TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
3531 tapOnFocusedWindow();
3532 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3533 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3534 // Receive the events, but don't respond
3535 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
3536 ASSERT_TRUE(downEventSequenceNum);
3537 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
3538 ASSERT_TRUE(upEventSequenceNum);
3539 const std::chrono::duration timeout =
3540 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003541 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003542
3543 // Tap once again
3544 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003545 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003546 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3547 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003548 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003549 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3550 FOCUSED_WINDOW_LOCATION));
3551 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
3552 // valid touch target
3553 mUnfocusedWindow->assertNoEvents();
3554
3555 // Consume the first tap
3556 mFocusedWindow->finishEvent(*downEventSequenceNum);
3557 mFocusedWindow->finishEvent(*upEventSequenceNum);
3558 ASSERT_TRUE(mDispatcher->waitForIdle());
3559 // The second tap did not go to the focused window
3560 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003561 // Since all events are finished, connection should be deemed healthy again
3562 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003563 mFakePolicy->assertNotifyAnrWasNotCalled();
3564}
3565
3566// If you tap outside of all windows, there will not be ANR
3567TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003568 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003569 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3570 LOCATION_OUTSIDE_ALL_WINDOWS));
3571 ASSERT_TRUE(mDispatcher->waitForIdle());
3572 mFakePolicy->assertNotifyAnrWasNotCalled();
3573}
3574
3575// Since the focused window is paused, tapping on it should not produce any events
3576TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
3577 mFocusedWindow->setPaused(true);
3578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3579
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003580 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003581 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3582 FOCUSED_WINDOW_LOCATION));
3583
3584 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
3585 ASSERT_TRUE(mDispatcher->waitForIdle());
3586 // Should not ANR because the window is paused, and touches shouldn't go to it
3587 mFakePolicy->assertNotifyAnrWasNotCalled();
3588
3589 mFocusedWindow->assertNoEvents();
3590 mUnfocusedWindow->assertNoEvents();
3591}
3592
3593/**
3594 * If a window is processing a motion event, and then a key event comes in, the key event should
3595 * not to to the focused window until the motion is processed.
3596 * If a different window becomes focused at this time, the key should go to that window instead.
3597 *
3598 * Warning!!!
3599 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3600 * and the injection timeout that we specify when injecting the key.
3601 * We must have the injection timeout (10ms) be smaller than
3602 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3603 *
3604 * If that value changes, this test should also change.
3605 */
3606TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
3607 // Set a long ANR timeout to prevent it from triggering
3608 mFocusedWindow->setDispatchingTimeout(2s);
3609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3610
3611 tapOnUnfocusedWindow();
3612 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
3613 ASSERT_TRUE(downSequenceNum);
3614 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
3615 ASSERT_TRUE(upSequenceNum);
3616 // Don't finish the events yet, and send a key
3617 // Injection will succeed because we will eventually give up and send the key to the focused
3618 // window even if motions are still being processed.
3619
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003620 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003621 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003622 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003624 // Key will not be sent to the window, yet, because the window is still processing events
3625 // and the key remains pending, waiting for the touch events to be processed
3626 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
3627 ASSERT_FALSE(keySequenceNum);
3628
3629 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07003630 mFocusedWindow->setFocusable(false);
3631 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003633 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003634
3635 // Focus events should precede the key events
3636 mUnfocusedWindow->consumeFocusEvent(true);
3637 mFocusedWindow->consumeFocusEvent(false);
3638
3639 // Finish the tap events, which should unblock dispatcher
3640 mUnfocusedWindow->finishEvent(*downSequenceNum);
3641 mUnfocusedWindow->finishEvent(*upSequenceNum);
3642
3643 // Now that all queues are cleared and no backlog in the connections, the key event
3644 // can finally go to the newly focused "mUnfocusedWindow".
3645 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3646 mFocusedWindow->assertNoEvents();
3647 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003648 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003649}
3650
3651// When the touch stream is split across 2 windows, and one of them does not respond,
3652// then ANR should be raised and the touch should be canceled for the unresponsive window.
3653// The other window should not be affected by that.
3654TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
3655 // Touch Window 1
3656 NotifyMotionArgs motionArgs =
3657 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3658 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
3659 mDispatcher->notifyMotion(&motionArgs);
3660 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3661 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3662
3663 // Touch Window 2
3664 int32_t actionPointerDown =
3665 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3666
3667 motionArgs =
3668 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3669 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
3670 mDispatcher->notifyMotion(&motionArgs);
3671
3672 const std::chrono::duration timeout =
3673 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003674 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003675
3676 mUnfocusedWindow->consumeMotionDown();
3677 mFocusedWindow->consumeMotionDown();
3678 // Focused window may or may not receive ACTION_MOVE
3679 // But it should definitely receive ACTION_CANCEL due to the ANR
3680 InputEvent* event;
3681 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
3682 ASSERT_TRUE(moveOrCancelSequenceNum);
3683 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
3684 ASSERT_NE(nullptr, event);
3685 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
3686 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
3687 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
3688 mFocusedWindow->consumeMotionCancel();
3689 } else {
3690 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
3691 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003692 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003693 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
3694
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003695 mUnfocusedWindow->assertNoEvents();
3696 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003697 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003698}
3699
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003700/**
3701 * If we have no focused window, and a key comes in, we start the ANR timer.
3702 * The focused application should add a focused window before the timer runs out to prevent ANR.
3703 *
3704 * If the user touches another application during this time, the key should be dropped.
3705 * Next, if a new focused window comes in, without toggling the focused application,
3706 * then no ANR should occur.
3707 *
3708 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
3709 * but in some cases the policy may not update the focused application.
3710 */
3711TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
3712 std::shared_ptr<FakeApplicationHandle> focusedApplication =
3713 std::make_shared<FakeApplicationHandle>();
3714 focusedApplication->setDispatchingTimeout(60ms);
3715 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
3716 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
3717 mFocusedWindow->setFocusable(false);
3718
3719 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3720 mFocusedWindow->consumeFocusEvent(false);
3721
3722 // Send a key. The ANR timer should start because there is no focused window.
3723 // 'focusedApplication' will get blamed if this timer completes.
3724 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003725 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003726 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003727 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003729
3730 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
3731 // then the injected touches won't cause the focused event to get dropped.
3732 // The dispatcher only checks for whether the queue should be pruned upon queueing.
3733 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
3734 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
3735 // For this test, it means that the key would get delivered to the window once it becomes
3736 // focused.
3737 std::this_thread::sleep_for(10ms);
3738
3739 // Touch unfocused window. This should force the pending key to get dropped.
3740 NotifyMotionArgs motionArgs =
3741 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3742 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
3743 mDispatcher->notifyMotion(&motionArgs);
3744
3745 // We do not consume the motion right away, because that would require dispatcher to first
3746 // process (== drop) the key event, and by that time, ANR will be raised.
3747 // Set the focused window first.
3748 mFocusedWindow->setFocusable(true);
3749 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3750 setFocusedWindow(mFocusedWindow);
3751 mFocusedWindow->consumeFocusEvent(true);
3752 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
3753 // to another application. This could be a bug / behaviour in the policy.
3754
3755 mUnfocusedWindow->consumeMotionDown();
3756
3757 ASSERT_TRUE(mDispatcher->waitForIdle());
3758 // Should not ANR because we actually have a focused window. It was just added too slowly.
3759 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
3760}
3761
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003762// These tests ensure we cannot send touch events to a window that's positioned behind a window
3763// that has feature NO_INPUT_CHANNEL.
3764// Layout:
3765// Top (closest to user)
3766// mNoInputWindow (above all windows)
3767// mBottomWindow
3768// Bottom (furthest from user)
3769class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
3770 virtual void SetUp() override {
3771 InputDispatcherTest::SetUp();
3772
3773 mApplication = std::make_shared<FakeApplicationHandle>();
3774 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
3775 "Window without input channel", ADISPLAY_ID_DEFAULT,
3776 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
3777
3778 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3779 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
3780 // It's perfectly valid for this window to not have an associated input channel
3781
3782 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
3783 ADISPLAY_ID_DEFAULT);
3784 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
3785
3786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
3787 }
3788
3789protected:
3790 std::shared_ptr<FakeApplicationHandle> mApplication;
3791 sp<FakeWindowHandle> mNoInputWindow;
3792 sp<FakeWindowHandle> mBottomWindow;
3793};
3794
3795TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
3796 PointF touchedPoint = {10, 10};
3797
3798 NotifyMotionArgs motionArgs =
3799 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3800 ADISPLAY_ID_DEFAULT, {touchedPoint});
3801 mDispatcher->notifyMotion(&motionArgs);
3802
3803 mNoInputWindow->assertNoEvents();
3804 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
3805 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
3806 // and therefore should prevent mBottomWindow from receiving touches
3807 mBottomWindow->assertNoEvents();
3808}
3809
3810/**
3811 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
3812 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
3813 */
3814TEST_F(InputDispatcherMultiWindowOcclusionTests,
3815 NoInputChannelFeature_DropsTouchesWithValidChannel) {
3816 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
3817 "Window with input channel and NO_INPUT_CHANNEL",
3818 ADISPLAY_ID_DEFAULT);
3819
3820 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3821 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
3822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
3823
3824 PointF touchedPoint = {10, 10};
3825
3826 NotifyMotionArgs motionArgs =
3827 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3828 ADISPLAY_ID_DEFAULT, {touchedPoint});
3829 mDispatcher->notifyMotion(&motionArgs);
3830
3831 mNoInputWindow->assertNoEvents();
3832 mBottomWindow->assertNoEvents();
3833}
3834
Vishnu Nair958da932020-08-21 17:12:37 -07003835class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
3836protected:
3837 std::shared_ptr<FakeApplicationHandle> mApp;
3838 sp<FakeWindowHandle> mWindow;
3839 sp<FakeWindowHandle> mMirror;
3840
3841 virtual void SetUp() override {
3842 InputDispatcherTest::SetUp();
3843 mApp = std::make_shared<FakeApplicationHandle>();
3844 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3845 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
3846 mWindow->getToken());
3847 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
3848 mWindow->setFocusable(true);
3849 mMirror->setFocusable(true);
3850 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3851 }
3852};
3853
3854TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
3855 // Request focus on a mirrored window
3856 setFocusedWindow(mMirror);
3857
3858 // window gets focused
3859 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3861 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003862 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3863}
3864
3865// A focused & mirrored window remains focused only if the window and its mirror are both
3866// focusable.
3867TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
3868 setFocusedWindow(mMirror);
3869
3870 // window gets focused
3871 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003872 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3873 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003874 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3876 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003877 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3878
3879 mMirror->setFocusable(false);
3880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3881
3882 // window loses focus since one of the windows associated with the token in not focusable
3883 mWindow->consumeFocusEvent(false);
3884
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003885 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3886 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003887 mWindow->assertNoEvents();
3888}
3889
3890// A focused & mirrored window remains focused until the window and its mirror both become
3891// invisible.
3892TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
3893 setFocusedWindow(mMirror);
3894
3895 // window gets focused
3896 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003897 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3898 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003899 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3901 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003902 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3903
3904 mMirror->setVisible(false);
3905 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3906
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3908 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003909 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003910 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3911 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003912 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3913
3914 mWindow->setVisible(false);
3915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3916
3917 // window loses focus only after all windows associated with the token become invisible.
3918 mWindow->consumeFocusEvent(false);
3919
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003920 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3921 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003922 mWindow->assertNoEvents();
3923}
3924
3925// A focused & mirrored window remains focused until both windows are removed.
3926TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
3927 setFocusedWindow(mMirror);
3928
3929 // window gets focused
3930 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003931 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3932 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003933 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3935 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003936 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3937
3938 // single window is removed but the window token remains focused
3939 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
3940
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003941 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3942 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003943 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3945 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003946 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3947
3948 // Both windows are removed
3949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3950 mWindow->consumeFocusEvent(false);
3951
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003952 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3953 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003954 mWindow->assertNoEvents();
3955}
3956
3957// Focus request can be pending until one window becomes visible.
3958TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
3959 // Request focus on an invisible mirror.
3960 mWindow->setVisible(false);
3961 mMirror->setVisible(false);
3962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3963 setFocusedWindow(mMirror);
3964
3965 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003966 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003967 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003968 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003969
3970 mMirror->setVisible(true);
3971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3972
3973 // window gets focused
3974 mWindow->consumeFocusEvent(true);
3975 // window gets the pending key event
3976 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3977}
Prabir Pradhan99987712020-11-10 18:43:05 -08003978
3979class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
3980protected:
3981 std::shared_ptr<FakeApplicationHandle> mApp;
3982 sp<FakeWindowHandle> mWindow;
3983 sp<FakeWindowHandle> mSecondWindow;
3984
3985 void SetUp() override {
3986 InputDispatcherTest::SetUp();
3987 mApp = std::make_shared<FakeApplicationHandle>();
3988 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3989 mWindow->setFocusable(true);
3990 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
3991 mSecondWindow->setFocusable(true);
3992
3993 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
3994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
3995
3996 setFocusedWindow(mWindow);
3997 mWindow->consumeFocusEvent(true);
3998 }
3999
4000 void notifyPointerCaptureChanged(bool enabled) {
4001 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
4002 mDispatcher->notifyPointerCaptureChanged(&args);
4003 }
4004
4005 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
4006 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4007 mFakePolicy->waitForSetPointerCapture(enabled);
4008 notifyPointerCaptureChanged(enabled);
4009 window->consumeCaptureEvent(enabled);
4010 }
4011};
4012
4013TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4014 // Ensure that capture cannot be obtained for unfocused windows.
4015 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4016 mFakePolicy->assertSetPointerCaptureNotCalled();
4017 mSecondWindow->assertNoEvents();
4018
4019 // Ensure that capture can be enabled from the focus window.
4020 requestAndVerifyPointerCapture(mWindow, true);
4021
4022 // Ensure that capture cannot be disabled from a window that does not have capture.
4023 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4024 mFakePolicy->assertSetPointerCaptureNotCalled();
4025
4026 // Ensure that capture can be disabled from the window with capture.
4027 requestAndVerifyPointerCapture(mWindow, false);
4028}
4029
4030TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4031 requestAndVerifyPointerCapture(mWindow, true);
4032
4033 setFocusedWindow(mSecondWindow);
4034
4035 // Ensure that the capture disabled event was sent first.
4036 mWindow->consumeCaptureEvent(false);
4037 mWindow->consumeFocusEvent(false);
4038 mSecondWindow->consumeFocusEvent(true);
4039 mFakePolicy->waitForSetPointerCapture(false);
4040
4041 // Ensure that additional state changes from InputReader are not sent to the window.
4042 notifyPointerCaptureChanged(false);
4043 notifyPointerCaptureChanged(true);
4044 notifyPointerCaptureChanged(false);
4045 mWindow->assertNoEvents();
4046 mSecondWindow->assertNoEvents();
4047 mFakePolicy->assertSetPointerCaptureNotCalled();
4048}
4049
4050TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4051 requestAndVerifyPointerCapture(mWindow, true);
4052
4053 // InputReader unexpectedly disables and enables pointer capture.
4054 notifyPointerCaptureChanged(false);
4055 notifyPointerCaptureChanged(true);
4056
4057 // Ensure that Pointer Capture is disabled.
4058 mWindow->consumeCaptureEvent(false);
4059 mWindow->assertNoEvents();
4060}
4061
Garfield Tane84e6f92019-08-29 17:28:41 -07004062} // namespace android::inputdispatcher