blob: e063dfc6695ce4be2ce6844d656d643fe6db2827 [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 Vishniakou3c63fa42020-12-15 02:59:54 +0000143 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
144 const sp<IBinder>& expectedConnectionToken) {
145 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500146 ASSERT_EQ(expectedConnectionToken, connectionToken);
147 }
148
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000149 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
150 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500151 ASSERT_EQ(expectedConnectionToken, connectionToken);
152 }
153
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000154 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
155 int32_t pid = getUnresponsiveMonitorPid(timeout);
156 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500157 }
158
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000159 void assertNotifyMonitorResponsiveWasCalled() {
160 int32_t pid = getResponsiveMonitorPid();
161 ASSERT_EQ(MONITOR_PID, pid);
162 }
163
164 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500165 std::unique_lock lock(mLock);
166 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000167 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
168 }
169
170 sp<IBinder> getResponsiveWindowToken() {
171 std::unique_lock lock(mLock);
172 android::base::ScopedLockAssertion assumeLocked(mLock);
173 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
174 }
175
176 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
177 std::unique_lock lock(mLock);
178 android::base::ScopedLockAssertion assumeLocked(mLock);
179 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
180 }
181
182 int32_t getResponsiveMonitorPid() {
183 std::unique_lock lock(mLock);
184 android::base::ScopedLockAssertion assumeLocked(mLock);
185 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500186 }
187
188 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
189 // for a specific container to become non-empty. When the container is non-empty, return the
190 // first entry from the container and erase it.
191 template <class T>
192 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
193 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
194 const std::chrono::time_point start = std::chrono::steady_clock::now();
195 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700196
197 // If there is an ANR, Dispatcher won't be idle because there are still events
198 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
199 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500200 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
201 // to provide it some time to act. 100ms seems reasonable.
202 mNotifyAnr.wait_for(lock, timeToWait,
203 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700204 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500205 if (storage.empty()) {
206 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000207 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700208 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700209 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
210 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700211 if (std::chrono::abs(timeout - waited) > 100ms) {
212 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
213 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
214 << "ms, but waited "
215 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
216 << "ms instead";
217 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500218 T token = storage.front();
219 storage.pop();
220 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700221 }
222
223 void assertNotifyAnrWasNotCalled() {
224 std::scoped_lock lock(mLock);
225 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000226 ASSERT_TRUE(mAnrWindowTokens.empty());
227 ASSERT_TRUE(mAnrMonitorPids.empty());
228 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500229 << "ANR was not called, but please also consume the 'connection is responsive' "
230 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000231 ASSERT_TRUE(mResponsiveMonitorPids.empty())
232 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
233 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700234 }
235
Garfield Tan1c7bc862020-01-28 13:24:04 -0800236 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
237 mConfig.keyRepeatTimeout = timeout;
238 mConfig.keyRepeatDelay = delay;
239 }
240
Prabir Pradhan99987712020-11-10 18:43:05 -0800241 void waitForSetPointerCapture(bool enabled) {
242 std::unique_lock lock(mLock);
243 base::ScopedLockAssertion assumeLocked(mLock);
244
245 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
246 [this, enabled]() REQUIRES(mLock) {
247 return mPointerCaptureEnabled &&
248 *mPointerCaptureEnabled ==
249 enabled;
250 })) {
251 FAIL() << "Timed out waiting for setPointerCapture(" << enabled << ") to be called.";
252 }
253 mPointerCaptureEnabled.reset();
254 }
255
256 void assertSetPointerCaptureNotCalled() {
257 std::unique_lock lock(mLock);
258 base::ScopedLockAssertion assumeLocked(mLock);
259
260 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
261 FAIL() << "Expected setPointerCapture(enabled) to not be called, but was called. "
262 "enabled = "
263 << *mPointerCaptureEnabled;
264 }
265 mPointerCaptureEnabled.reset();
266 }
267
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700269 std::mutex mLock;
270 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
271 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
272 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
273 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800274
Prabir Pradhan99987712020-11-10 18:43:05 -0800275 std::condition_variable mPointerCaptureChangedCondition;
276 std::optional<bool> mPointerCaptureEnabled GUARDED_BY(mLock);
277
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700278 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700279 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000280 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
281 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
282 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
283 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700284 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700285
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600286 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700287 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800288 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800289 }
290
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000291 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700292 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000293 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700294 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500295 }
296
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000297 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500298 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000299 mAnrMonitorPids.push(pid);
300 mNotifyAnr.notify_all();
301 }
302
303 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
304 std::scoped_lock lock(mLock);
305 mResponsiveWindowTokens.push(connectionToken);
306 mNotifyAnr.notify_all();
307 }
308
309 void notifyMonitorResponsive(int32_t pid) override {
310 std::scoped_lock lock(mLock);
311 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500312 mNotifyAnr.notify_all();
313 }
314
315 void notifyNoFocusedWindowAnr(
316 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
317 std::scoped_lock lock(mLock);
318 mAnrApplications.push(applicationHandle);
319 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800320 }
321
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600322 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800323
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600324 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700325
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600326 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700327 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
328 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
329 const std::vector<float>& values) override {}
330
331 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
332 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000333
Chris Yefb552902021-02-03 17:18:37 -0800334 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
335
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600336 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800337 *outConfig = mConfig;
338 }
339
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600340 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700341 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800342 switch (inputEvent->getType()) {
343 case AINPUT_EVENT_TYPE_KEY: {
344 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800345 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800346 break;
347 }
348
349 case AINPUT_EVENT_TYPE_MOTION: {
350 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800351 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800352 break;
353 }
354 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800355 return true;
356 }
357
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600358 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800359
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600360 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800361
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600362 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800363 return 0;
364 }
365
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600366 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800367 return false;
368 }
369
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600370 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
371 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700372 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800373 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
374 * essentially a passthrough for notifySwitch.
375 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800376 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800377 }
378
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600379 void pokeUserActivity(nsecs_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600381 bool checkInjectEventsPermissionNonReentrant(int32_t, int32_t) override { return false; }
Jackal Guof9696682018-10-05 12:23:23 +0800382
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600383 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700384 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700385 mOnPointerDownToken = newToken;
386 }
387
Prabir Pradhan99987712020-11-10 18:43:05 -0800388 void setPointerCapture(bool enabled) override {
389 std::scoped_lock lock(mLock);
390 mPointerCaptureEnabled = {enabled};
391 mPointerCaptureChangedCondition.notify_all();
392 }
393
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800394 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
395 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700396 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800397 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
398 ASSERT_EQ(mFilteredEvent->getType(), type);
399
400 if (type == AINPUT_EVENT_TYPE_KEY) {
401 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
402 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
403 EXPECT_EQ(keyEvent.getAction(), action);
404 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
405 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
406 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
407 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
408 EXPECT_EQ(motionEvent.getAction(), action);
409 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
410 } else {
411 FAIL() << "Unknown type: " << type;
412 }
413
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800414 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800415 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800416};
417
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418// --- InputDispatcherTest ---
419
420class InputDispatcherTest : public testing::Test {
421protected:
422 sp<FakeInputDispatcherPolicy> mFakePolicy;
423 sp<InputDispatcher> mDispatcher;
424
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700425 virtual void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 mFakePolicy = new FakeInputDispatcherPolicy();
427 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800428 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000429 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700430 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 }
432
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700433 virtual void TearDown() override {
434 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435 mFakePolicy.clear();
436 mDispatcher.clear();
437 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700438
439 /**
440 * Used for debugging when writing the test
441 */
442 void dumpDispatcherState() {
443 std::string dump;
444 mDispatcher->dump(dump);
445 std::stringstream ss(dump);
446 std::string to;
447
448 while (std::getline(ss, to, '\n')) {
449 ALOGE("%s", to.c_str());
450 }
451 }
Vishnu Nair958da932020-08-21 17:12:37 -0700452
453 void setFocusedWindow(const sp<InputWindowHandle>& window,
454 const sp<InputWindowHandle>& focusedWindow = nullptr) {
455 FocusRequest request;
456 request.token = window->getToken();
457 if (focusedWindow) {
458 request.focusedToken = focusedWindow->getToken();
459 }
460 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
461 request.displayId = window->getInfo()->displayId;
462 mDispatcher->setFocusedWindow(request);
463 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464};
465
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
467 KeyEvent event;
468
469 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800470 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
471 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600472 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
473 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800474 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700475 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800476 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800477 << "Should reject key events with undefined action.";
478
479 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800480 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
481 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600482 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800483 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700484 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800485 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486 << "Should reject key events with ACTION_MULTIPLE.";
487}
488
489TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
490 MotionEvent event;
491 PointerProperties pointerProperties[MAX_POINTERS + 1];
492 PointerCoords pointerCoords[MAX_POINTERS + 1];
493 for (int i = 0; i <= MAX_POINTERS; i++) {
494 pointerProperties[i].clear();
495 pointerProperties[i].id = i;
496 pointerCoords[i].clear();
497 }
498
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800499 // Some constants commonly used below
500 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
501 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
502 constexpr int32_t metaState = AMETA_NONE;
503 constexpr MotionClassification classification = MotionClassification::NONE;
504
chaviw9eaa22c2020-07-01 16:21:27 -0700505 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800507 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700508 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
509 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600510 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700511 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800512 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700513 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800514 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 << "Should reject motion events with undefined action.";
516
517 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800518 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700519 AMOTION_EVENT_ACTION_POINTER_DOWN |
520 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700521 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
522 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
523 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
524 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800525 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700526 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800527 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 << "Should reject motion events with pointer down index too large.";
529
Garfield Tanfbe732e2020-01-24 11:26:14 -0800530 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700531 AMOTION_EVENT_ACTION_POINTER_DOWN |
532 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700533 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
534 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
535 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
536 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800537 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700538 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800539 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 << "Should reject motion events with pointer down index too small.";
541
542 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800543 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700544 AMOTION_EVENT_ACTION_POINTER_UP |
545 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700546 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
547 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
548 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
549 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800550 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700551 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800552 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553 << "Should reject motion events with pointer up index too large.";
554
Garfield Tanfbe732e2020-01-24 11:26:14 -0800555 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700556 AMOTION_EVENT_ACTION_POINTER_UP |
557 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700558 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
559 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
560 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
561 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800562 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700563 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800564 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 << "Should reject motion events with pointer up index too small.";
566
567 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800568 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
569 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700570 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
571 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700572 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800573 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700574 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800575 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 << "Should reject motion events with 0 pointers.";
577
Garfield Tanfbe732e2020-01-24 11:26:14 -0800578 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
579 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700580 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
581 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700582 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800583 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700584 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800585 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586 << "Should reject motion events with more than MAX_POINTERS pointers.";
587
588 // Rejects motion events with invalid pointer ids.
589 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800590 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
591 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700592 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
593 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700594 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800595 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700596 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800597 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 << "Should reject motion events with pointer ids less than 0.";
599
600 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800601 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
602 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700603 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
604 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700605 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800606 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700607 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800608 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
610
611 // Rejects motion events with duplicate pointer ids.
612 pointerProperties[0].id = 1;
613 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800614 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
615 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700616 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
617 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700618 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800619 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700620 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800621 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 << "Should reject motion events with duplicate pointer ids.";
623}
624
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800625/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
626
627TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
628 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800629 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800630 mDispatcher->notifyConfigurationChanged(&args);
631 ASSERT_TRUE(mDispatcher->waitForIdle());
632
633 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
634}
635
636TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800637 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
638 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800639 mDispatcher->notifySwitch(&args);
640
641 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
642 args.policyFlags |= POLICY_FLAG_TRUSTED;
643 mFakePolicy->assertNotifySwitchWasCalled(args);
644}
645
Arthur Hungb92218b2018-08-14 12:00:21 +0800646// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700647static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700648static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800649
650class FakeApplicationHandle : public InputApplicationHandle {
651public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700652 FakeApplicationHandle() {
653 mInfo.name = "Fake Application";
654 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500655 mInfo.dispatchingTimeoutMillis =
656 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700657 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800658 virtual ~FakeApplicationHandle() {}
659
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000660 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700661
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500662 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
663 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700664 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800665};
666
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800667class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800668public:
Garfield Tan15601662020-09-22 15:32:38 -0700669 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800670 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700671 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800672 }
673
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800674 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700675 InputEvent* event;
676 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
677 if (!consumeSeq) {
678 return nullptr;
679 }
680 finishEvent(*consumeSeq);
681 return event;
682 }
683
684 /**
685 * Receive an event without acknowledging it.
686 * Return the sequence number that could later be used to send finished signal.
687 */
688 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800689 uint32_t consumeSeq;
690 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800691
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800692 std::chrono::time_point start = std::chrono::steady_clock::now();
693 status_t status = WOULD_BLOCK;
694 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800695 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800696 &event);
697 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
698 if (elapsed > 100ms) {
699 break;
700 }
701 }
702
703 if (status == WOULD_BLOCK) {
704 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700705 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800706 }
707
708 if (status != OK) {
709 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700710 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800711 }
712 if (event == nullptr) {
713 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700714 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800715 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700716 if (outEvent != nullptr) {
717 *outEvent = event;
718 }
719 return consumeSeq;
720 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800721
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700722 /**
723 * To be used together with "receiveEvent" to complete the consumption of an event.
724 */
725 void finishEvent(uint32_t consumeSeq) {
726 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
727 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800728 }
729
730 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
731 int32_t expectedFlags) {
732 InputEvent* event = consume();
733
734 ASSERT_NE(nullptr, event) << mName.c_str()
735 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800736 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700737 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800738 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800739
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800740 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800741
Tiger Huang8664f8c2018-10-11 19:14:35 +0800742 switch (expectedEventType) {
743 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800744 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
745 EXPECT_EQ(expectedAction, keyEvent.getAction());
746 EXPECT_EQ(expectedFlags, keyEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800747 break;
748 }
749 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800750 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
751 EXPECT_EQ(expectedAction, motionEvent.getAction());
752 EXPECT_EQ(expectedFlags, motionEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800753 break;
754 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100755 case AINPUT_EVENT_TYPE_FOCUS: {
756 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
757 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800758 case AINPUT_EVENT_TYPE_CAPTURE: {
759 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
760 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800761 default: {
762 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
763 }
764 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800765 }
766
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100767 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
768 InputEvent* event = consume();
769 ASSERT_NE(nullptr, event) << mName.c_str()
770 << ": consumer should have returned non-NULL event.";
771 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
772 << "Got " << inputEventTypeToString(event->getType())
773 << " event instead of FOCUS event";
774
775 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
776 << mName.c_str() << ": event displayId should always be NONE.";
777
778 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
779 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
780 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
781 }
782
Prabir Pradhan99987712020-11-10 18:43:05 -0800783 void consumeCaptureEvent(bool hasCapture) {
784 const InputEvent* event = consume();
785 ASSERT_NE(nullptr, event) << mName.c_str()
786 << ": consumer should have returned non-NULL event.";
787 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
788 << "Got " << inputEventTypeToString(event->getType())
789 << " event instead of CAPTURE event";
790
791 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
792 << mName.c_str() << ": event displayId should always be NONE.";
793
794 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
795 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
796 }
797
chaviwd1c23182019-12-20 18:44:56 -0800798 void assertNoEvents() {
799 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700800 if (event == nullptr) {
801 return;
802 }
803 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
804 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
805 ADD_FAILURE() << "Received key event "
806 << KeyEvent::actionToString(keyEvent.getAction());
807 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
808 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
809 ADD_FAILURE() << "Received motion event "
810 << MotionEvent::actionToString(motionEvent.getAction());
811 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
812 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
813 ADD_FAILURE() << "Received focus event, hasFocus = "
814 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800815 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
816 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
817 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
818 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700819 }
820 FAIL() << mName.c_str()
821 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800822 }
823
824 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
825
826protected:
827 std::unique_ptr<InputConsumer> mConsumer;
828 PreallocatedInputEventFactory mEventFactory;
829
830 std::string mName;
831};
832
833class FakeWindowHandle : public InputWindowHandle {
834public:
835 static const int32_t WIDTH = 600;
836 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800837
Chris Yea209fde2020-07-22 13:54:51 -0700838 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800839 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500840 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800841 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500842 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700843 base::Result<std::unique_ptr<InputChannel>> channel =
844 dispatcher->createInputChannel(name);
845 token = (*channel)->getConnectionToken();
846 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800847 }
848
849 inputApplicationHandle->updateInfo();
850 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
851
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500852 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700853 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800854 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100855 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500856 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
chaviwd1c23182019-12-20 18:44:56 -0800857 mInfo.frameLeft = 0;
858 mInfo.frameTop = 0;
859 mInfo.frameRight = WIDTH;
860 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700861 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800862 mInfo.globalScaleFactor = 1.0;
863 mInfo.touchableRegion.clear();
864 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
865 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700866 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800867 mInfo.hasWallpaper = false;
868 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800869 mInfo.ownerPid = INJECTOR_PID;
870 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800871 mInfo.displayId = displayId;
872 }
873
874 virtual bool updateInfo() { return true; }
875
Vishnu Nair47074b82020-08-14 11:54:47 -0700876 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800877
Vishnu Nair958da932020-08-21 17:12:37 -0700878 void setVisible(bool visible) { mInfo.visible = visible; }
879
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700880 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500881 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700882 }
883
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700884 void setPaused(bool paused) { mInfo.paused = paused; }
885
chaviwd1c23182019-12-20 18:44:56 -0800886 void setFrame(const Rect& frame) {
887 mInfo.frameLeft = frame.left;
888 mInfo.frameTop = frame.top;
889 mInfo.frameRight = frame.right;
890 mInfo.frameBottom = frame.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -0700891 mInfo.transform.set(frame.left, frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800892 mInfo.touchableRegion.clear();
893 mInfo.addTouchableRegion(frame);
894 }
895
Michael Wright44753b12020-07-08 13:48:11 +0100896 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800897
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500898 void setInputFeatures(InputWindowInfo::Feature features) { mInfo.inputFeatures = features; }
899
chaviw9eaa22c2020-07-01 16:21:27 -0700900 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
901 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
902 }
903
904 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700905
yunho.shinf4a80b82020-11-16 21:13:57 +0900906 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
907
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800908 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
909 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
910 expectedFlags);
911 }
912
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700913 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
914 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
915 }
916
Svet Ganov5d3bc372020-01-26 23:11:07 -0800917 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000918 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800919 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
920 expectedFlags);
921 }
922
923 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000924 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800925 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
926 expectedFlags);
927 }
928
929 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000930 int32_t expectedFlags = 0) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800931 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
932 expectedFlags);
933 }
934
Svet Ganov5d3bc372020-01-26 23:11:07 -0800935 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000936 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
937 int32_t expectedFlags = 0) {
938 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
939 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -0800940 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
941 }
942
943 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000944 int32_t expectedFlags = 0) {
945 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
946 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -0800947 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
948 }
949
950 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000951 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +0000952 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
953 expectedFlags);
954 }
955
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500956 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
957 int32_t expectedFlags = 0) {
958 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
959 expectedFlags);
960 }
961
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100962 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
963 ASSERT_NE(mInputReceiver, nullptr)
964 << "Cannot consume events from a window with no receiver";
965 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
966 }
967
Prabir Pradhan99987712020-11-10 18:43:05 -0800968 void consumeCaptureEvent(bool hasCapture) {
969 ASSERT_NE(mInputReceiver, nullptr)
970 << "Cannot consume events from a window with no receiver";
971 mInputReceiver->consumeCaptureEvent(hasCapture);
972 }
973
chaviwd1c23182019-12-20 18:44:56 -0800974 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
975 int32_t expectedFlags) {
976 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
977 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
978 expectedFlags);
979 }
980
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700981 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700982 if (mInputReceiver == nullptr) {
983 ADD_FAILURE() << "Invalid receive event on window with no receiver";
984 return std::nullopt;
985 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700986 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700987 }
988
989 void finishEvent(uint32_t sequenceNum) {
990 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
991 mInputReceiver->finishEvent(sequenceNum);
992 }
993
chaviwaf87b3e2019-10-01 16:59:28 -0700994 InputEvent* consume() {
995 if (mInputReceiver == nullptr) {
996 return nullptr;
997 }
998 return mInputReceiver->consume();
999 }
1000
Arthur Hungb92218b2018-08-14 12:00:21 +08001001 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001002 if (mInputReceiver == nullptr &&
1003 mInfo.inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL)) {
1004 return; // Can't receive events if the window does not have input channel
1005 }
1006 ASSERT_NE(nullptr, mInputReceiver)
1007 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001008 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001009 }
1010
chaviwaf87b3e2019-10-01 16:59:28 -07001011 sp<IBinder> getToken() { return mInfo.token; }
1012
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001013 const std::string& getName() { return mName; }
1014
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001015 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1016 mInfo.ownerPid = ownerPid;
1017 mInfo.ownerUid = ownerUid;
1018 }
1019
chaviwd1c23182019-12-20 18:44:56 -08001020private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001021 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001022 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001023 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001024};
1025
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001026std::atomic<int32_t> FakeWindowHandle::sId{1};
1027
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001028static InputEventInjectionResult injectKey(
1029 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1030 int32_t displayId = ADISPLAY_ID_NONE,
1031 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1032 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001033 KeyEvent event;
1034 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1035
1036 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001037 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001038 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1039 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001040
1041 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001042 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
1043 injectionTimeout,
1044 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
Arthur Hungb92218b2018-08-14 12:00:21 +08001045}
1046
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001047static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1048 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001049 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1050}
1051
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001052static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1053 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001054 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1055}
1056
Garfield Tandf26e862020-07-01 20:18:19 -07001057class PointerBuilder {
1058public:
1059 PointerBuilder(int32_t id, int32_t toolType) {
1060 mProperties.clear();
1061 mProperties.id = id;
1062 mProperties.toolType = toolType;
1063 mCoords.clear();
1064 }
1065
1066 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1067
1068 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1069
1070 PointerBuilder& axis(int32_t axis, float value) {
1071 mCoords.setAxisValue(axis, value);
1072 return *this;
1073 }
1074
1075 PointerProperties buildProperties() const { return mProperties; }
1076
1077 PointerCoords buildCoords() const { return mCoords; }
1078
1079private:
1080 PointerProperties mProperties;
1081 PointerCoords mCoords;
1082};
1083
1084class MotionEventBuilder {
1085public:
1086 MotionEventBuilder(int32_t action, int32_t source) {
1087 mAction = action;
1088 mSource = source;
1089 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1090 }
1091
1092 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1093 mEventTime = eventTime;
1094 return *this;
1095 }
1096
1097 MotionEventBuilder& displayId(int32_t displayId) {
1098 mDisplayId = displayId;
1099 return *this;
1100 }
1101
1102 MotionEventBuilder& actionButton(int32_t actionButton) {
1103 mActionButton = actionButton;
1104 return *this;
1105 }
1106
1107 MotionEventBuilder& buttonState(int32_t actionButton) {
1108 mActionButton = actionButton;
1109 return *this;
1110 }
1111
1112 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1113 mRawXCursorPosition = rawXCursorPosition;
1114 return *this;
1115 }
1116
1117 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1118 mRawYCursorPosition = rawYCursorPosition;
1119 return *this;
1120 }
1121
1122 MotionEventBuilder& pointer(PointerBuilder pointer) {
1123 mPointers.push_back(pointer);
1124 return *this;
1125 }
1126
1127 MotionEvent build() {
1128 std::vector<PointerProperties> pointerProperties;
1129 std::vector<PointerCoords> pointerCoords;
1130 for (const PointerBuilder& pointer : mPointers) {
1131 pointerProperties.push_back(pointer.buildProperties());
1132 pointerCoords.push_back(pointer.buildCoords());
1133 }
1134
1135 // Set mouse cursor position for the most common cases to avoid boilerplate.
1136 if (mSource == AINPUT_SOURCE_MOUSE &&
1137 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1138 mPointers.size() == 1) {
1139 mRawXCursorPosition = pointerCoords[0].getX();
1140 mRawYCursorPosition = pointerCoords[0].getY();
1141 }
1142
1143 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001144 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001145 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
1146 mAction, mActionButton, /* flags */ 0, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001147 mButtonState, MotionClassification::NONE, identityTransform,
1148 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
1149 mRawYCursorPosition, mEventTime, mEventTime, mPointers.size(),
1150 pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001151
1152 return event;
1153 }
1154
1155private:
1156 int32_t mAction;
1157 int32_t mSource;
1158 nsecs_t mEventTime;
1159 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1160 int32_t mActionButton{0};
1161 int32_t mButtonState{0};
1162 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1163 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1164
1165 std::vector<PointerBuilder> mPointers;
1166};
1167
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001168static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001169 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1170 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001171 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001172 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1173 injectionTimeout,
1174 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1175}
1176
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001177static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001178 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1179 const PointF& position,
1180 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001181 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1182 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001183 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001184 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001185 MotionEvent event = MotionEventBuilder(action, source)
1186 .displayId(displayId)
1187 .eventTime(eventTime)
1188 .rawXCursorPosition(cursorPosition.x)
1189 .rawYCursorPosition(cursorPosition.y)
1190 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1191 .x(position.x)
1192 .y(position.y))
1193 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001194
1195 // Inject event until dispatch out.
Garfield Tandf26e862020-07-01 20:18:19 -07001196 return injectMotionEvent(dispatcher, event);
Arthur Hungb92218b2018-08-14 12:00:21 +08001197}
1198
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001199static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1200 int32_t source, int32_t displayId,
1201 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001202 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001203}
1204
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001205static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1206 int32_t source, int32_t displayId,
1207 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001208 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001209}
1210
Jackal Guof9696682018-10-05 12:23:23 +08001211static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1212 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1213 // Define a valid key event.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001214 NotifyKeyArgs args(/* id */ 0, currentTime, DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
1215 POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A, KEY_A,
1216 AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001217
1218 return args;
1219}
1220
chaviwd1c23182019-12-20 18:44:56 -08001221static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1222 const std::vector<PointF>& points) {
1223 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001224 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1225 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1226 }
1227
chaviwd1c23182019-12-20 18:44:56 -08001228 PointerProperties pointerProperties[pointerCount];
1229 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001230
chaviwd1c23182019-12-20 18:44:56 -08001231 for (size_t i = 0; i < pointerCount; i++) {
1232 pointerProperties[i].clear();
1233 pointerProperties[i].id = i;
1234 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001235
chaviwd1c23182019-12-20 18:44:56 -08001236 pointerCoords[i].clear();
1237 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1238 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1239 }
Jackal Guof9696682018-10-05 12:23:23 +08001240
1241 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1242 // Define a valid motion event.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001243 NotifyMotionArgs args(/* id */ 0, currentTime, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001244 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1245 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001246 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1247 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001248 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1249 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001250
1251 return args;
1252}
1253
chaviwd1c23182019-12-20 18:44:56 -08001254static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1255 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1256}
1257
Prabir Pradhan99987712020-11-10 18:43:05 -08001258static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(bool enabled) {
1259 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), enabled);
1260}
1261
Arthur Hungb92218b2018-08-14 12:00:21 +08001262TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001263 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001264 sp<FakeWindowHandle> window =
1265 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001266
Arthur Hung72d8dc32020-03-28 00:48:39 +00001267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001268 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1269 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1270 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001271
1272 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001273 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001274}
1275
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001276/**
1277 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1278 * To ensure that window receives only events that were directly inside of it, add
1279 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1280 * when finding touched windows.
1281 * This test serves as a sanity check for the next test, where setInputWindows is
1282 * called twice.
1283 */
1284TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001285 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001286 sp<FakeWindowHandle> window =
1287 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1288 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001289 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001290
1291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001293 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1294 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001295 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001296
1297 // Window should receive motion event.
1298 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1299}
1300
1301/**
1302 * Calling setInputWindows twice, with the same info, should not cause any issues.
1303 * To ensure that window receives only events that were directly inside of it, add
1304 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1305 * when finding touched windows.
1306 */
1307TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001308 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001309 sp<FakeWindowHandle> window =
1310 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1311 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001312 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001313
1314 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1315 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001317 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1318 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001319 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001320
1321 // Window should receive motion event.
1322 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1323}
1324
Arthur Hungb92218b2018-08-14 12:00:21 +08001325// The foreground window should receive the first touch down event.
1326TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001327 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001328 sp<FakeWindowHandle> windowTop =
1329 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1330 sp<FakeWindowHandle> windowSecond =
1331 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001332
Arthur Hung72d8dc32020-03-28 00:48:39 +00001333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1335 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1336 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001337
1338 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001339 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001340 windowSecond->assertNoEvents();
1341}
1342
Garfield Tandf26e862020-07-01 20:18:19 -07001343TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001344 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001345 sp<FakeWindowHandle> windowLeft =
1346 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1347 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001348 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001349 sp<FakeWindowHandle> windowRight =
1350 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1351 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001352 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001353
1354 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1355
1356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1357
1358 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001359 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001360 injectMotionEvent(mDispatcher,
1361 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1362 AINPUT_SOURCE_MOUSE)
1363 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1364 .x(900)
1365 .y(400))
1366 .build()));
1367 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1368 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1369 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1370 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1371
1372 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001373 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001374 injectMotionEvent(mDispatcher,
1375 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1376 AINPUT_SOURCE_MOUSE)
1377 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1378 .x(300)
1379 .y(400))
1380 .build()));
1381 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1382 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1383 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1384 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1385 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1386 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1387
1388 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001389 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001390 injectMotionEvent(mDispatcher,
1391 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1392 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1393 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1394 .x(300)
1395 .y(400))
1396 .build()));
1397 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1398
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001400 injectMotionEvent(mDispatcher,
1401 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1402 AINPUT_SOURCE_MOUSE)
1403 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1404 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1405 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1406 .x(300)
1407 .y(400))
1408 .build()));
1409 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1410 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1411
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001413 injectMotionEvent(mDispatcher,
1414 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1415 AINPUT_SOURCE_MOUSE)
1416 .buttonState(0)
1417 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1418 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1419 .x(300)
1420 .y(400))
1421 .build()));
1422 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1423 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1424
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001426 injectMotionEvent(mDispatcher,
1427 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1428 .buttonState(0)
1429 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1430 .x(300)
1431 .y(400))
1432 .build()));
1433 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1434
1435 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001436 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001437 injectMotionEvent(mDispatcher,
1438 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1439 AINPUT_SOURCE_MOUSE)
1440 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1441 .x(900)
1442 .y(400))
1443 .build()));
1444 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1445 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1446 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1447 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1448 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1449 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1450}
1451
1452// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1453// directly in this test.
1454TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001455 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001456 sp<FakeWindowHandle> window =
1457 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1458 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001459 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001460
1461 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1462
1463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1464
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001465 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001466 injectMotionEvent(mDispatcher,
1467 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1468 AINPUT_SOURCE_MOUSE)
1469 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1470 .x(300)
1471 .y(400))
1472 .build()));
1473 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1474 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1475
1476 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001478 injectMotionEvent(mDispatcher,
1479 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1480 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1481 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1482 .x(300)
1483 .y(400))
1484 .build()));
1485 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1486
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001488 injectMotionEvent(mDispatcher,
1489 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1490 AINPUT_SOURCE_MOUSE)
1491 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1492 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1493 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1494 .x(300)
1495 .y(400))
1496 .build()));
1497 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1498 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1499
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001500 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001501 injectMotionEvent(mDispatcher,
1502 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1503 AINPUT_SOURCE_MOUSE)
1504 .buttonState(0)
1505 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1506 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1507 .x(300)
1508 .y(400))
1509 .build()));
1510 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1511 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1512
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001514 injectMotionEvent(mDispatcher,
1515 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1516 .buttonState(0)
1517 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1518 .x(300)
1519 .y(400))
1520 .build()));
1521 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1522
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001524 injectMotionEvent(mDispatcher,
1525 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1526 AINPUT_SOURCE_MOUSE)
1527 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1528 .x(300)
1529 .y(400))
1530 .build()));
1531 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1532 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1533}
1534
Garfield Tan00f511d2019-06-12 16:55:40 -07001535TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001536 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001537
1538 sp<FakeWindowHandle> windowLeft =
1539 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1540 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001541 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001542 sp<FakeWindowHandle> windowRight =
1543 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1544 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001545 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001546
1547 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1548
Arthur Hung72d8dc32020-03-28 00:48:39 +00001549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001550
1551 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1552 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001554 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001555 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001556 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001557 windowRight->assertNoEvents();
1558}
1559
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001560TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001561 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001562 sp<FakeWindowHandle> window =
1563 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001564 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001565
Arthur Hung72d8dc32020-03-28 00:48:39 +00001566 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001567 setFocusedWindow(window);
1568
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001569 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001570
1571 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1572 mDispatcher->notifyKey(&keyArgs);
1573
1574 // Window should receive key down event.
1575 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1576
1577 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1578 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001579 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001580 mDispatcher->notifyDeviceReset(&args);
1581 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1582 AKEY_EVENT_FLAG_CANCELED);
1583}
1584
1585TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001586 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001587 sp<FakeWindowHandle> window =
1588 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1589
Arthur Hung72d8dc32020-03-28 00:48:39 +00001590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001591
1592 NotifyMotionArgs motionArgs =
1593 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1594 ADISPLAY_ID_DEFAULT);
1595 mDispatcher->notifyMotion(&motionArgs);
1596
1597 // Window should receive motion down event.
1598 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1599
1600 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1601 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001602 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001603 mDispatcher->notifyDeviceReset(&args);
1604 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1605 0 /*expectedFlags*/);
1606}
1607
Svet Ganov5d3bc372020-01-26 23:11:07 -08001608TEST_F(InputDispatcherTest, TransferTouchFocus_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001609 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001610
1611 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001612 sp<FakeWindowHandle> firstWindow =
1613 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1614 sp<FakeWindowHandle> secondWindow =
1615 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001616
1617 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001618 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001619
1620 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001621 NotifyMotionArgs downMotionArgs =
1622 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1623 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001624 mDispatcher->notifyMotion(&downMotionArgs);
1625 // Only the first window should get the down event
1626 firstWindow->consumeMotionDown();
1627 secondWindow->assertNoEvents();
1628
1629 // Transfer touch focus to the second window
1630 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1631 // The first window gets cancel and the second gets down
1632 firstWindow->consumeMotionCancel();
1633 secondWindow->consumeMotionDown();
1634
1635 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001636 NotifyMotionArgs upMotionArgs =
1637 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1638 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001639 mDispatcher->notifyMotion(&upMotionArgs);
1640 // The first window gets no events and the second gets up
1641 firstWindow->assertNoEvents();
1642 secondWindow->consumeMotionUp();
1643}
1644
1645TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointerNoSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001646 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001647
1648 PointF touchPoint = {10, 10};
1649
1650 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001651 sp<FakeWindowHandle> firstWindow =
1652 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1653 sp<FakeWindowHandle> secondWindow =
1654 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001655
1656 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001658
1659 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001660 NotifyMotionArgs downMotionArgs =
1661 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1662 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001663 mDispatcher->notifyMotion(&downMotionArgs);
1664 // Only the first window should get the down event
1665 firstWindow->consumeMotionDown();
1666 secondWindow->assertNoEvents();
1667
1668 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001669 NotifyMotionArgs pointerDownMotionArgs =
1670 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1671 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1672 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1673 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001674 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1675 // Only the first window should get the pointer down event
1676 firstWindow->consumeMotionPointerDown(1);
1677 secondWindow->assertNoEvents();
1678
1679 // Transfer touch focus to the second window
1680 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1681 // The first window gets cancel and the second gets down and pointer down
1682 firstWindow->consumeMotionCancel();
1683 secondWindow->consumeMotionDown();
1684 secondWindow->consumeMotionPointerDown(1);
1685
1686 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001687 NotifyMotionArgs pointerUpMotionArgs =
1688 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1689 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1690 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1691 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001692 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1693 // The first window gets nothing and the second gets pointer up
1694 firstWindow->assertNoEvents();
1695 secondWindow->consumeMotionPointerUp(1);
1696
1697 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001698 NotifyMotionArgs upMotionArgs =
1699 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1700 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001701 mDispatcher->notifyMotion(&upMotionArgs);
1702 // The first window gets nothing and the second gets up
1703 firstWindow->assertNoEvents();
1704 secondWindow->consumeMotionUp();
1705}
1706
1707TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001708 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001709
1710 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001711 sp<FakeWindowHandle> firstWindow =
1712 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001713 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001714 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1715 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001716
1717 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001718 sp<FakeWindowHandle> secondWindow =
1719 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001720 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001721 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1722 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001723
1724 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001725 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001726
1727 PointF pointInFirst = {300, 200};
1728 PointF pointInSecond = {300, 600};
1729
1730 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001731 NotifyMotionArgs firstDownMotionArgs =
1732 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1733 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001734 mDispatcher->notifyMotion(&firstDownMotionArgs);
1735 // Only the first window should get the down event
1736 firstWindow->consumeMotionDown();
1737 secondWindow->assertNoEvents();
1738
1739 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001740 NotifyMotionArgs secondDownMotionArgs =
1741 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1742 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1743 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1744 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001745 mDispatcher->notifyMotion(&secondDownMotionArgs);
1746 // The first window gets a move and the second a down
1747 firstWindow->consumeMotionMove();
1748 secondWindow->consumeMotionDown();
1749
1750 // Transfer touch focus to the second window
1751 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1752 // The first window gets cancel and the new gets pointer down (it already saw down)
1753 firstWindow->consumeMotionCancel();
1754 secondWindow->consumeMotionPointerDown(1);
1755
1756 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001757 NotifyMotionArgs pointerUpMotionArgs =
1758 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1759 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1760 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1761 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001762 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1763 // The first window gets nothing and the second gets pointer up
1764 firstWindow->assertNoEvents();
1765 secondWindow->consumeMotionPointerUp(1);
1766
1767 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001768 NotifyMotionArgs upMotionArgs =
1769 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1770 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001771 mDispatcher->notifyMotion(&upMotionArgs);
1772 // The first window gets nothing and the second gets up
1773 firstWindow->assertNoEvents();
1774 secondWindow->consumeMotionUp();
1775}
1776
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001777TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001778 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001779 sp<FakeWindowHandle> window =
1780 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1781
Vishnu Nair47074b82020-08-14 11:54:47 -07001782 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001784 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001785
1786 window->consumeFocusEvent(true);
1787
1788 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1789 mDispatcher->notifyKey(&keyArgs);
1790
1791 // Window should receive key down event.
1792 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1793}
1794
1795TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001796 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001797 sp<FakeWindowHandle> window =
1798 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1799
Arthur Hung72d8dc32020-03-28 00:48:39 +00001800 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001801
1802 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1803 mDispatcher->notifyKey(&keyArgs);
1804 mDispatcher->waitForIdle();
1805
1806 window->assertNoEvents();
1807}
1808
1809// If a window is touchable, but does not have focus, it should receive motion events, but not keys
1810TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07001811 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001812 sp<FakeWindowHandle> window =
1813 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1814
Arthur Hung72d8dc32020-03-28 00:48:39 +00001815 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001816
1817 // Send key
1818 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1819 mDispatcher->notifyKey(&keyArgs);
1820 // Send motion
1821 NotifyMotionArgs motionArgs =
1822 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1823 ADISPLAY_ID_DEFAULT);
1824 mDispatcher->notifyMotion(&motionArgs);
1825
1826 // Window should receive only the motion event
1827 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1828 window->assertNoEvents(); // Key event or focus event will not be received
1829}
1830
arthurhungea3f4fc2020-12-21 23:18:53 +08001831TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
1832 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1833
1834 // Create first non touch modal window that supports split touch
1835 sp<FakeWindowHandle> firstWindow =
1836 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1837 firstWindow->setFrame(Rect(0, 0, 600, 400));
1838 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1839 InputWindowInfo::Flag::SPLIT_TOUCH);
1840
1841 // Create second non touch modal window that supports split touch
1842 sp<FakeWindowHandle> secondWindow =
1843 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1844 secondWindow->setFrame(Rect(0, 400, 600, 800));
1845 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1846 InputWindowInfo::Flag::SPLIT_TOUCH);
1847
1848 // Add the windows to the dispatcher
1849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1850
1851 PointF pointInFirst = {300, 200};
1852 PointF pointInSecond = {300, 600};
1853
1854 // Send down to the first window
1855 NotifyMotionArgs firstDownMotionArgs =
1856 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1857 ADISPLAY_ID_DEFAULT, {pointInFirst});
1858 mDispatcher->notifyMotion(&firstDownMotionArgs);
1859 // Only the first window should get the down event
1860 firstWindow->consumeMotionDown();
1861 secondWindow->assertNoEvents();
1862
1863 // Send down to the second window
1864 NotifyMotionArgs secondDownMotionArgs =
1865 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1866 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1867 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1868 {pointInFirst, pointInSecond});
1869 mDispatcher->notifyMotion(&secondDownMotionArgs);
1870 // The first window gets a move and the second a down
1871 firstWindow->consumeMotionMove();
1872 secondWindow->consumeMotionDown();
1873
1874 // Send pointer cancel to the second window
1875 NotifyMotionArgs pointerUpMotionArgs =
1876 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1877 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1878 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1879 {pointInFirst, pointInSecond});
1880 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
1881 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1882 // The first window gets move and the second gets cancel.
1883 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
1884 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
1885
1886 // Send up event.
1887 NotifyMotionArgs upMotionArgs =
1888 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1889 ADISPLAY_ID_DEFAULT);
1890 mDispatcher->notifyMotion(&upMotionArgs);
1891 // The first window gets up and the second gets nothing.
1892 firstWindow->consumeMotionUp();
1893 secondWindow->assertNoEvents();
1894}
1895
chaviwd1c23182019-12-20 18:44:56 -08001896class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00001897public:
1898 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08001899 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07001900 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00001901 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07001902 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00001903 }
1904
chaviwd1c23182019-12-20 18:44:56 -08001905 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
1906
1907 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1908 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
1909 expectedDisplayId, expectedFlags);
1910 }
1911
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001912 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
1913
1914 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
1915
chaviwd1c23182019-12-20 18:44:56 -08001916 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1917 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
1918 expectedDisplayId, expectedFlags);
1919 }
1920
1921 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1922 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
1923 expectedDisplayId, expectedFlags);
1924 }
1925
1926 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
1927
1928private:
1929 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00001930};
1931
1932// Tests for gesture monitors
1933TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001934 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001935 sp<FakeWindowHandle> window =
1936 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001937 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001938
chaviwd1c23182019-12-20 18:44:56 -08001939 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1940 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001941
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001943 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001944 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001945 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001946 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001947}
1948
1949TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001950 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001951 sp<FakeWindowHandle> window =
1952 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1953
1954 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001955 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001956
Arthur Hung72d8dc32020-03-28 00:48:39 +00001957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001958 setFocusedWindow(window);
1959
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001960 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001961
chaviwd1c23182019-12-20 18:44:56 -08001962 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1963 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001964
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001965 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
1966 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001967 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001968 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00001969}
1970
1971TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001972 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001973 sp<FakeWindowHandle> window =
1974 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001975 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001976
chaviwd1c23182019-12-20 18:44:56 -08001977 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1978 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001979
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001981 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001982 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001983 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001984 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001985
1986 window->releaseChannel();
1987
chaviwd1c23182019-12-20 18:44:56 -08001988 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00001989
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001991 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001992 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08001993 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001994}
1995
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001996TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
1997 FakeMonitorReceiver monitor =
1998 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
1999 true /*isGestureMonitor*/);
2000
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002002 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2003 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2004 ASSERT_TRUE(consumeSeq);
2005
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002006 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002007 monitor.finishEvent(*consumeSeq);
2008 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002009 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002010}
2011
chaviw81e2bb92019-12-18 15:03:51 -08002012TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002013 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002014 sp<FakeWindowHandle> window =
2015 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2016
Arthur Hung72d8dc32020-03-28 00:48:39 +00002017 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002018
2019 NotifyMotionArgs motionArgs =
2020 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2021 ADISPLAY_ID_DEFAULT);
2022
2023 mDispatcher->notifyMotion(&motionArgs);
2024 // Window should receive motion down event.
2025 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2026
2027 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002028 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002029 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2030 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2031 motionArgs.pointerCoords[0].getX() - 10);
2032
2033 mDispatcher->notifyMotion(&motionArgs);
2034 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2035 0 /*expectedFlags*/);
2036}
2037
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002038/**
2039 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2040 * the device default right away. In the test scenario, we check both the default value,
2041 * and the action of enabling / disabling.
2042 */
2043TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002044 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002045 sp<FakeWindowHandle> window =
2046 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2047
2048 // Set focused application.
2049 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002050 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002051
2052 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002054 setFocusedWindow(window);
2055
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002056 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2057
2058 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002059 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002060 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002061 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2062
2063 SCOPED_TRACE("Disable touch mode");
2064 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002065 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002066 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002067 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002068 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2069
2070 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002071 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002073 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2074
2075 SCOPED_TRACE("Enable touch mode again");
2076 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002077 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002078 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002079 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002080 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2081
2082 window->assertNoEvents();
2083}
2084
Gang Wange9087892020-01-07 12:17:14 -05002085TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002086 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002087 sp<FakeWindowHandle> window =
2088 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2089
2090 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002091 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002092
Arthur Hung72d8dc32020-03-28 00:48:39 +00002093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002094 setFocusedWindow(window);
2095
Gang Wange9087892020-01-07 12:17:14 -05002096 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2097
2098 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2099 mDispatcher->notifyKey(&keyArgs);
2100
2101 InputEvent* event = window->consume();
2102 ASSERT_NE(event, nullptr);
2103
2104 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2105 ASSERT_NE(verified, nullptr);
2106 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2107
2108 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2109 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2110 ASSERT_EQ(keyArgs.source, verified->source);
2111 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2112
2113 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2114
2115 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2116 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002117 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2118 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2119 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2120 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2121 ASSERT_EQ(0, verifiedKey.repeatCount);
2122}
2123
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002124TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002125 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002126 sp<FakeWindowHandle> window =
2127 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2128
2129 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2130
Arthur Hung72d8dc32020-03-28 00:48:39 +00002131 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002132
2133 NotifyMotionArgs motionArgs =
2134 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2135 ADISPLAY_ID_DEFAULT);
2136 mDispatcher->notifyMotion(&motionArgs);
2137
2138 InputEvent* event = window->consume();
2139 ASSERT_NE(event, nullptr);
2140
2141 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2142 ASSERT_NE(verified, nullptr);
2143 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2144
2145 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2146 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2147 EXPECT_EQ(motionArgs.source, verified->source);
2148 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2149
2150 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2151
2152 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2153 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2154 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2155 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2156 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2157 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2158 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2159}
2160
yunho.shinf4a80b82020-11-16 21:13:57 +09002161TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickNotTransformed) {
2162 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2163 sp<FakeWindowHandle> window =
2164 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2165 const std::string name = window->getName();
2166
2167 // Window gets transformed by offset values.
2168 window->setWindowOffset(500.0f, 500.0f);
2169
2170 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2171 window->setFocusable(true);
2172
2173 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2174
2175 // First, we set focused window so that focusedWindowHandle is not null.
2176 setFocusedWindow(window);
2177
2178 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2179 window->consumeFocusEvent(true);
2180
2181 NotifyMotionArgs motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE,
2182 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_DEFAULT);
2183 mDispatcher->notifyMotion(&motionArgs);
2184
2185 // Third, we consume motion event.
2186 InputEvent* event = window->consume();
2187 ASSERT_NE(event, nullptr);
2188 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2189 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2190 << " event, got " << inputEventTypeToString(event->getType()) << " event";
2191
2192 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2193 EXPECT_EQ(AINPUT_EVENT_TYPE_MOTION, motionEvent.getAction());
2194
2195 float expectedX = motionArgs.pointerCoords[0].getX();
2196 float expectedY = motionArgs.pointerCoords[0].getY();
2197
2198 // Finally we test if the axis values from the final motion event are not transformed
2199 EXPECT_EQ(expectedX, motionEvent.getX(0)) << "expected " << expectedX << " for x coord of "
2200 << name.c_str() << ", got " << motionEvent.getX(0);
2201 EXPECT_EQ(expectedY, motionEvent.getY(0)) << "expected " << expectedY << " for y coord of "
2202 << name.c_str() << ", got " << motionEvent.getY(0);
2203}
2204
chaviw09c8d2d2020-08-24 15:48:26 -07002205/**
2206 * Ensure that separate calls to sign the same data are generating the same key.
2207 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2208 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2209 * tests.
2210 */
2211TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2212 KeyEvent event = getTestKeyEvent();
2213 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2214
2215 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2216 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2217 ASSERT_EQ(hmac1, hmac2);
2218}
2219
2220/**
2221 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2222 */
2223TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2224 KeyEvent event = getTestKeyEvent();
2225 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2226 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2227
2228 verifiedEvent.deviceId += 1;
2229 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2230
2231 verifiedEvent.source += 1;
2232 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2233
2234 verifiedEvent.eventTimeNanos += 1;
2235 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2236
2237 verifiedEvent.displayId += 1;
2238 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2239
2240 verifiedEvent.action += 1;
2241 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2242
2243 verifiedEvent.downTimeNanos += 1;
2244 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2245
2246 verifiedEvent.flags += 1;
2247 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2248
2249 verifiedEvent.keyCode += 1;
2250 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2251
2252 verifiedEvent.scanCode += 1;
2253 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2254
2255 verifiedEvent.metaState += 1;
2256 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2257
2258 verifiedEvent.repeatCount += 1;
2259 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2260}
2261
Vishnu Nair958da932020-08-21 17:12:37 -07002262TEST_F(InputDispatcherTest, SetFocusedWindow) {
2263 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2264 sp<FakeWindowHandle> windowTop =
2265 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2266 sp<FakeWindowHandle> windowSecond =
2267 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2268 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2269
2270 // Top window is also focusable but is not granted focus.
2271 windowTop->setFocusable(true);
2272 windowSecond->setFocusable(true);
2273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2274 setFocusedWindow(windowSecond);
2275
2276 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002277 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2278 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002279
2280 // Focused window should receive event.
2281 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2282 windowTop->assertNoEvents();
2283}
2284
2285TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2286 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2287 sp<FakeWindowHandle> window =
2288 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2289 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2290
2291 window->setFocusable(true);
2292 // Release channel for window is no longer valid.
2293 window->releaseChannel();
2294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2295 setFocusedWindow(window);
2296
2297 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002298 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2299 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002300
2301 // window channel is invalid, so it should not receive any input event.
2302 window->assertNoEvents();
2303}
2304
2305TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2306 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2307 sp<FakeWindowHandle> window =
2308 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2309 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2310
2311 // Window is not focusable.
2312 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2313 setFocusedWindow(window);
2314
2315 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002316 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2317 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002318
2319 // window is invalid, so it should not receive any input event.
2320 window->assertNoEvents();
2321}
2322
2323TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2324 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2325 sp<FakeWindowHandle> windowTop =
2326 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2327 sp<FakeWindowHandle> windowSecond =
2328 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2329 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2330
2331 windowTop->setFocusable(true);
2332 windowSecond->setFocusable(true);
2333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2334 setFocusedWindow(windowTop);
2335 windowTop->consumeFocusEvent(true);
2336
2337 setFocusedWindow(windowSecond, windowTop);
2338 windowSecond->consumeFocusEvent(true);
2339 windowTop->consumeFocusEvent(false);
2340
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2342 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002343
2344 // Focused window should receive event.
2345 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2346}
2347
2348TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2349 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2350 sp<FakeWindowHandle> windowTop =
2351 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2352 sp<FakeWindowHandle> windowSecond =
2353 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2354 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2355
2356 windowTop->setFocusable(true);
2357 windowSecond->setFocusable(true);
2358 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2359 setFocusedWindow(windowSecond, windowTop);
2360
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002361 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2362 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002363
2364 // Event should be dropped.
2365 windowTop->assertNoEvents();
2366 windowSecond->assertNoEvents();
2367}
2368
2369TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2370 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2371 sp<FakeWindowHandle> window =
2372 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2373 sp<FakeWindowHandle> previousFocusedWindow =
2374 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2375 ADISPLAY_ID_DEFAULT);
2376 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2377
2378 window->setFocusable(true);
2379 previousFocusedWindow->setFocusable(true);
2380 window->setVisible(false);
2381 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2382 setFocusedWindow(previousFocusedWindow);
2383 previousFocusedWindow->consumeFocusEvent(true);
2384
2385 // Requesting focus on invisible window takes focus from currently focused window.
2386 setFocusedWindow(window);
2387 previousFocusedWindow->consumeFocusEvent(false);
2388
2389 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002390 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002391 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002392 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002393
2394 // Window does not get focus event or key down.
2395 window->assertNoEvents();
2396
2397 // Window becomes visible.
2398 window->setVisible(true);
2399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2400
2401 // Window receives focus event.
2402 window->consumeFocusEvent(true);
2403 // Focused window receives key down.
2404 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2405}
2406
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002407/**
2408 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2409 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2410 * of the 'slipperyEnterWindow'.
2411 *
2412 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2413 * a way so that the touched location is no longer covered by the top window.
2414 *
2415 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2416 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2417 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2418 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2419 * with ACTION_DOWN).
2420 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2421 * window moved itself away from the touched location and had Flag::SLIPPERY.
2422 *
2423 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2424 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2425 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2426 *
2427 * In this test, we ensure that the event received by the bottom window has
2428 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2429 */
2430TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2431 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2432 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2433
2434 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2435 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2436
2437 sp<FakeWindowHandle> slipperyExitWindow =
2438 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2439 slipperyExitWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2440 InputWindowInfo::Flag::SLIPPERY);
2441 // Make sure this one overlaps the bottom window
2442 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2443 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2444 // one. Windows with the same owner are not considered to be occluding each other.
2445 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2446
2447 sp<FakeWindowHandle> slipperyEnterWindow =
2448 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2449 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2450
2451 mDispatcher->setInputWindows(
2452 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2453
2454 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2455 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2456 ADISPLAY_ID_DEFAULT, {{50, 50}});
2457 mDispatcher->notifyMotion(&args);
2458 slipperyExitWindow->consumeMotionDown();
2459 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2460 mDispatcher->setInputWindows(
2461 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2462
2463 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2464 ADISPLAY_ID_DEFAULT, {{51, 51}});
2465 mDispatcher->notifyMotion(&args);
2466
2467 slipperyExitWindow->consumeMotionCancel();
2468
2469 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2470 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2471}
2472
Garfield Tan1c7bc862020-01-28 13:24:04 -08002473class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2474protected:
2475 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2476 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2477
Chris Yea209fde2020-07-22 13:54:51 -07002478 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002479 sp<FakeWindowHandle> mWindow;
2480
2481 virtual void SetUp() override {
2482 mFakePolicy = new FakeInputDispatcherPolicy();
2483 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2484 mDispatcher = new InputDispatcher(mFakePolicy);
2485 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2486 ASSERT_EQ(OK, mDispatcher->start());
2487
2488 setUpWindow();
2489 }
2490
2491 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002492 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002493 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2494
Vishnu Nair47074b82020-08-14 11:54:47 -07002495 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002497 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002498 mWindow->consumeFocusEvent(true);
2499 }
2500
Chris Ye2ad95392020-09-01 13:44:44 -07002501 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002502 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002503 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002504 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2505 mDispatcher->notifyKey(&keyArgs);
2506
2507 // Window should receive key down event.
2508 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2509 }
2510
2511 void expectKeyRepeatOnce(int32_t repeatCount) {
2512 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2513 InputEvent* repeatEvent = mWindow->consume();
2514 ASSERT_NE(nullptr, repeatEvent);
2515
2516 uint32_t eventType = repeatEvent->getType();
2517 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2518
2519 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2520 uint32_t eventAction = repeatKeyEvent->getAction();
2521 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2522 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2523 }
2524
Chris Ye2ad95392020-09-01 13:44:44 -07002525 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002526 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002527 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002528 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2529 mDispatcher->notifyKey(&keyArgs);
2530
2531 // Window should receive key down event.
2532 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2533 0 /*expectedFlags*/);
2534 }
2535};
2536
2537TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002538 sendAndConsumeKeyDown(1 /* deviceId */);
2539 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2540 expectKeyRepeatOnce(repeatCount);
2541 }
2542}
2543
2544TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2545 sendAndConsumeKeyDown(1 /* deviceId */);
2546 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2547 expectKeyRepeatOnce(repeatCount);
2548 }
2549 sendAndConsumeKeyDown(2 /* deviceId */);
2550 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002551 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2552 expectKeyRepeatOnce(repeatCount);
2553 }
2554}
2555
2556TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002557 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002558 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002559 sendAndConsumeKeyUp(1 /* deviceId */);
2560 mWindow->assertNoEvents();
2561}
2562
2563TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2564 sendAndConsumeKeyDown(1 /* deviceId */);
2565 expectKeyRepeatOnce(1 /*repeatCount*/);
2566 sendAndConsumeKeyDown(2 /* deviceId */);
2567 expectKeyRepeatOnce(1 /*repeatCount*/);
2568 // Stale key up from device 1.
2569 sendAndConsumeKeyUp(1 /* deviceId */);
2570 // Device 2 is still down, keep repeating
2571 expectKeyRepeatOnce(2 /*repeatCount*/);
2572 expectKeyRepeatOnce(3 /*repeatCount*/);
2573 // Device 2 key up
2574 sendAndConsumeKeyUp(2 /* deviceId */);
2575 mWindow->assertNoEvents();
2576}
2577
2578TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2579 sendAndConsumeKeyDown(1 /* deviceId */);
2580 expectKeyRepeatOnce(1 /*repeatCount*/);
2581 sendAndConsumeKeyDown(2 /* deviceId */);
2582 expectKeyRepeatOnce(1 /*repeatCount*/);
2583 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2584 sendAndConsumeKeyUp(2 /* deviceId */);
2585 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002586 mWindow->assertNoEvents();
2587}
2588
2589TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002590 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002591 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2592 InputEvent* repeatEvent = mWindow->consume();
2593 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2594 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2595 IdGenerator::getSource(repeatEvent->getId()));
2596 }
2597}
2598
2599TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002600 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002601
2602 std::unordered_set<int32_t> idSet;
2603 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2604 InputEvent* repeatEvent = mWindow->consume();
2605 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2606 int32_t id = repeatEvent->getId();
2607 EXPECT_EQ(idSet.end(), idSet.find(id));
2608 idSet.insert(id);
2609 }
2610}
2611
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002612/* Test InputDispatcher for MultiDisplay */
2613class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2614public:
2615 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002616 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002617 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002618
Chris Yea209fde2020-07-22 13:54:51 -07002619 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002620 windowInPrimary =
2621 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002622
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002623 // Set focus window for primary display, but focused display would be second one.
2624 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002625 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002627 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002628 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002629
Chris Yea209fde2020-07-22 13:54:51 -07002630 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002631 windowInSecondary =
2632 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002633 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002634 // Set focus display to second one.
2635 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2636 // Set focus window for second display.
2637 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002638 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002639 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002640 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002641 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002642 }
2643
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002644 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002645 InputDispatcherTest::TearDown();
2646
Chris Yea209fde2020-07-22 13:54:51 -07002647 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002648 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002649 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002650 windowInSecondary.clear();
2651 }
2652
2653protected:
Chris Yea209fde2020-07-22 13:54:51 -07002654 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002655 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002656 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002657 sp<FakeWindowHandle> windowInSecondary;
2658};
2659
2660TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2661 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2663 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2664 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002665 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002666 windowInSecondary->assertNoEvents();
2667
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002668 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2670 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2671 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002672 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002673 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002674}
2675
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002676TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002677 // Test inject a key down with display id specified.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002678 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2679 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002680 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002681 windowInSecondary->assertNoEvents();
2682
2683 // Test inject a key down without display id specified.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2685 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002686 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002687 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002688
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002689 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002690 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002691
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002692 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002693 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2694 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002695
2696 // Test inject a key down, should timeout because of no target window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002697 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2698 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08002699 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002700 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002701 windowInSecondary->assertNoEvents();
2702}
2703
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002704// Test per-display input monitors for motion event.
2705TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002706 FakeMonitorReceiver monitorInPrimary =
2707 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2708 FakeMonitorReceiver monitorInSecondary =
2709 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002710
2711 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002712 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2713 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2714 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002715 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002716 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002717 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002718 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002719
2720 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2722 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2723 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002724 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002725 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002726 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08002727 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002728
2729 // Test inject a non-pointer motion event.
2730 // If specific a display, it will dispatch to the focused window of particular display,
2731 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2733 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
2734 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002735 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002736 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002737 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002738 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002739}
2740
2741// Test per-display input monitors for key event.
2742TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002743 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08002744 FakeMonitorReceiver monitorInPrimary =
2745 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2746 FakeMonitorReceiver monitorInSecondary =
2747 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002748
2749 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2751 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002752 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002753 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002754 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002755 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002756}
2757
Vishnu Nair958da932020-08-21 17:12:37 -07002758TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
2759 sp<FakeWindowHandle> secondWindowInPrimary =
2760 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2761 secondWindowInPrimary->setFocusable(true);
2762 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
2763 setFocusedWindow(secondWindowInPrimary);
2764 windowInPrimary->consumeFocusEvent(false);
2765 secondWindowInPrimary->consumeFocusEvent(true);
2766
2767 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2769 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002770 windowInPrimary->assertNoEvents();
2771 windowInSecondary->assertNoEvents();
2772 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2773}
2774
Jackal Guof9696682018-10-05 12:23:23 +08002775class InputFilterTest : public InputDispatcherTest {
2776protected:
2777 static constexpr int32_t SECOND_DISPLAY_ID = 1;
2778
2779 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
2780 NotifyMotionArgs motionArgs;
2781
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002782 motionArgs =
2783 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08002784 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002785 motionArgs =
2786 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08002787 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002788 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002789 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002790 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002791 } else {
2792 mFakePolicy->assertFilterInputEventWasNotCalled();
2793 }
2794 }
2795
2796 void testNotifyKey(bool expectToBeFiltered) {
2797 NotifyKeyArgs keyArgs;
2798
2799 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2800 mDispatcher->notifyKey(&keyArgs);
2801 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
2802 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002803 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002804
2805 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002806 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002807 } else {
2808 mFakePolicy->assertFilterInputEventWasNotCalled();
2809 }
2810 }
2811};
2812
2813// Test InputFilter for MotionEvent
2814TEST_F(InputFilterTest, MotionEvent_InputFilter) {
2815 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
2816 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2817 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2818
2819 // Enable InputFilter
2820 mDispatcher->setInputFilterEnabled(true);
2821 // Test touch on both primary and second display, and check if both events are filtered.
2822 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
2823 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
2824
2825 // Disable InputFilter
2826 mDispatcher->setInputFilterEnabled(false);
2827 // Test touch on both primary and second display, and check if both events aren't filtered.
2828 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2829 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2830}
2831
2832// Test InputFilter for KeyEvent
2833TEST_F(InputFilterTest, KeyEvent_InputFilter) {
2834 // Since the InputFilter is disabled by default, check if key event aren't filtered.
2835 testNotifyKey(/*expectToBeFiltered*/ false);
2836
2837 // Enable InputFilter
2838 mDispatcher->setInputFilterEnabled(true);
2839 // Send a key event, and check if it is filtered.
2840 testNotifyKey(/*expectToBeFiltered*/ true);
2841
2842 // Disable InputFilter
2843 mDispatcher->setInputFilterEnabled(false);
2844 // Send a key event, and check if it isn't filtered.
2845 testNotifyKey(/*expectToBeFiltered*/ false);
2846}
2847
chaviwfd6d3512019-03-25 13:23:49 -07002848class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002849 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07002850 InputDispatcherTest::SetUp();
2851
Chris Yea209fde2020-07-22 13:54:51 -07002852 std::shared_ptr<FakeApplicationHandle> application =
2853 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002854 mUnfocusedWindow =
2855 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002856 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
2857 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2858 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002859 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002860
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002861 mFocusedWindow =
2862 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2863 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01002864 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002865
2866 // Set focused application.
2867 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002868 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07002869
2870 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002871 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002872 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002873 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07002874 }
2875
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002876 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07002877 InputDispatcherTest::TearDown();
2878
2879 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002880 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07002881 }
2882
2883protected:
2884 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002885 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002886 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07002887};
2888
2889// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2890// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
2891// the onPointerDownOutsideFocus callback.
2892TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002894 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2895 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002896 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002897 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002898
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002899 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07002900 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
2901}
2902
2903// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
2904// DOWN on the window that doesn't have focus. Ensure no window received the
2905// onPointerDownOutsideFocus callback.
2906TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002908 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002909 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002910 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002911
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002912 ASSERT_TRUE(mDispatcher->waitForIdle());
2913 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002914}
2915
2916// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
2917// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
2918TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002919 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2920 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002921 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002922
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002923 ASSERT_TRUE(mDispatcher->waitForIdle());
2924 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002925}
2926
2927// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2928// DOWN on the window that already has focus. Ensure no window received the
2929// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002930TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002931 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002932 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002933 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002934 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002935 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002936
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002937 ASSERT_TRUE(mDispatcher->waitForIdle());
2938 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002939}
2940
chaviwaf87b3e2019-10-01 16:59:28 -07002941// These tests ensures we can send touch events to a single client when there are multiple input
2942// windows that point to the same client token.
2943class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
2944 virtual void SetUp() override {
2945 InputDispatcherTest::SetUp();
2946
Chris Yea209fde2020-07-22 13:54:51 -07002947 std::shared_ptr<FakeApplicationHandle> application =
2948 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07002949 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
2950 ADISPLAY_ID_DEFAULT);
2951 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
2952 // 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 +01002953 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2954 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002955 mWindow1->setFrame(Rect(0, 0, 100, 100));
2956
2957 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
2958 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01002959 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2960 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002961 mWindow2->setFrame(Rect(100, 100, 200, 200));
2962
Arthur Hung72d8dc32020-03-28 00:48:39 +00002963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07002964 }
2965
2966protected:
2967 sp<FakeWindowHandle> mWindow1;
2968 sp<FakeWindowHandle> mWindow2;
2969
2970 // Helper function to convert the point from screen coordinates into the window's space
2971 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07002972 vec2 vals = windowInfo->transform.transform(point.x, point.y);
2973 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07002974 }
2975
2976 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
2977 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002978 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07002979 InputEvent* event = window->consume();
2980
2981 ASSERT_NE(nullptr, event) << name.c_str()
2982 << ": consumer should have returned non-NULL event.";
2983
2984 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2985 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2986 << " event, got " << inputEventTypeToString(event->getType()) << " event";
2987
2988 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2989 EXPECT_EQ(expectedAction, motionEvent.getAction());
2990
2991 for (size_t i = 0; i < points.size(); i++) {
2992 float expectedX = points[i].x;
2993 float expectedY = points[i].y;
2994
2995 EXPECT_EQ(expectedX, motionEvent.getX(i))
2996 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
2997 << ", got " << motionEvent.getX(i);
2998 EXPECT_EQ(expectedY, motionEvent.getY(i))
2999 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3000 << ", got " << motionEvent.getY(i);
3001 }
3002 }
chaviw9eaa22c2020-07-01 16:21:27 -07003003
3004 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3005 std::vector<PointF> expectedPoints) {
3006 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3007 ADISPLAY_ID_DEFAULT, touchedPoints);
3008 mDispatcher->notifyMotion(&motionArgs);
3009
3010 // Always consume from window1 since it's the window that has the InputReceiver
3011 consumeMotionEvent(mWindow1, action, expectedPoints);
3012 }
chaviwaf87b3e2019-10-01 16:59:28 -07003013};
3014
3015TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3016 // Touch Window 1
3017 PointF touchedPoint = {10, 10};
3018 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003019 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003020
3021 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003022 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003023
3024 // Touch Window 2
3025 touchedPoint = {150, 150};
3026 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003027 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003028}
3029
chaviw9eaa22c2020-07-01 16:21:27 -07003030TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3031 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003032 mWindow2->setWindowScale(0.5f, 0.5f);
3033
3034 // Touch Window 1
3035 PointF touchedPoint = {10, 10};
3036 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003037 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003038 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003039 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003040
3041 // Touch Window 2
3042 touchedPoint = {150, 150};
3043 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003044 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3045 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003046
chaviw9eaa22c2020-07-01 16:21:27 -07003047 // Update the transform so rotation is set
3048 mWindow2->setWindowTransform(0, -1, 1, 0);
3049 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3050 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003051}
3052
chaviw9eaa22c2020-07-01 16:21:27 -07003053TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003054 mWindow2->setWindowScale(0.5f, 0.5f);
3055
3056 // Touch Window 1
3057 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3058 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003059 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003060
3061 // Touch Window 2
3062 int32_t actionPointerDown =
3063 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003064 touchedPoints.push_back(PointF{150, 150});
3065 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3066 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003067
chaviw9eaa22c2020-07-01 16:21:27 -07003068 // Release Window 2
3069 int32_t actionPointerUp =
3070 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3071 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3072 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003073
chaviw9eaa22c2020-07-01 16:21:27 -07003074 // Update the transform so rotation is set for Window 2
3075 mWindow2->setWindowTransform(0, -1, 1, 0);
3076 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3077 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003078}
3079
chaviw9eaa22c2020-07-01 16:21:27 -07003080TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003081 mWindow2->setWindowScale(0.5f, 0.5f);
3082
3083 // Touch Window 1
3084 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3085 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003086 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003087
3088 // Touch Window 2
3089 int32_t actionPointerDown =
3090 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003091 touchedPoints.push_back(PointF{150, 150});
3092 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003093
chaviw9eaa22c2020-07-01 16:21:27 -07003094 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003095
3096 // Move both windows
3097 touchedPoints = {{20, 20}, {175, 175}};
3098 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3099 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3100
chaviw9eaa22c2020-07-01 16:21:27 -07003101 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003102
chaviw9eaa22c2020-07-01 16:21:27 -07003103 // Release Window 2
3104 int32_t actionPointerUp =
3105 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3106 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3107 expectedPoints.pop_back();
3108
3109 // Touch Window 2
3110 mWindow2->setWindowTransform(0, -1, 1, 0);
3111 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3112 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3113
3114 // Move both windows
3115 touchedPoints = {{20, 20}, {175, 175}};
3116 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3117 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3118
3119 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003120}
3121
3122TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3123 mWindow1->setWindowScale(0.5f, 0.5f);
3124
3125 // Touch Window 1
3126 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3127 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003128 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003129
3130 // Touch Window 2
3131 int32_t actionPointerDown =
3132 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003133 touchedPoints.push_back(PointF{150, 150});
3134 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003135
chaviw9eaa22c2020-07-01 16:21:27 -07003136 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003137
3138 // Move both windows
3139 touchedPoints = {{20, 20}, {175, 175}};
3140 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3141 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3142
chaviw9eaa22c2020-07-01 16:21:27 -07003143 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003144}
3145
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003146class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3147 virtual void SetUp() override {
3148 InputDispatcherTest::SetUp();
3149
Chris Yea209fde2020-07-22 13:54:51 -07003150 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003151 mApplication->setDispatchingTimeout(20ms);
3152 mWindow =
3153 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3154 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003155 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003156 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003157 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3158 // window.
Michael Wright44753b12020-07-08 13:48:11 +01003159 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003160
3161 // Set focused application.
3162 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3163
3164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003165 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003166 mWindow->consumeFocusEvent(true);
3167 }
3168
3169 virtual void TearDown() override {
3170 InputDispatcherTest::TearDown();
3171 mWindow.clear();
3172 }
3173
3174protected:
Chris Yea209fde2020-07-22 13:54:51 -07003175 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003176 sp<FakeWindowHandle> mWindow;
3177 static constexpr PointF WINDOW_LOCATION = {20, 20};
3178
3179 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003180 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003181 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3182 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003183 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003184 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3185 WINDOW_LOCATION));
3186 }
3187};
3188
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003189// Send a tap and respond, which should not cause an ANR.
3190TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3191 tapOnWindow();
3192 mWindow->consumeMotionDown();
3193 mWindow->consumeMotionUp();
3194 ASSERT_TRUE(mDispatcher->waitForIdle());
3195 mFakePolicy->assertNotifyAnrWasNotCalled();
3196}
3197
3198// Send a regular key and respond, which should not cause an ANR.
3199TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003201 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3202 ASSERT_TRUE(mDispatcher->waitForIdle());
3203 mFakePolicy->assertNotifyAnrWasNotCalled();
3204}
3205
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003206TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3207 mWindow->setFocusable(false);
3208 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3209 mWindow->consumeFocusEvent(false);
3210
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003211 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003212 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003213 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003215 // Key will not go to window because we have no focused window.
3216 // The 'no focused window' ANR timer should start instead.
3217
3218 // Now, the focused application goes away.
3219 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3220 // The key should get dropped and there should be no ANR.
3221
3222 ASSERT_TRUE(mDispatcher->waitForIdle());
3223 mFakePolicy->assertNotifyAnrWasNotCalled();
3224}
3225
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003226// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003227// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3228// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003229TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003231 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3232 WINDOW_LOCATION));
3233
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003234 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3235 ASSERT_TRUE(sequenceNum);
3236 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003237 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003238
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003239 mWindow->finishEvent(*sequenceNum);
3240 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3241 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003242 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003243 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003244}
3245
3246// Send a key to the app and have the app not respond right away.
3247TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3248 // Inject a key, and don't respond - expect that ANR is called.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003249 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003250 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3251 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003252 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003253 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003254 ASSERT_TRUE(mDispatcher->waitForIdle());
3255}
3256
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003257// We have a focused application, but no focused window
3258TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003259 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3261 mWindow->consumeFocusEvent(false);
3262
3263 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003265 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3266 WINDOW_LOCATION));
3267 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3268 mDispatcher->waitForIdle();
3269 mFakePolicy->assertNotifyAnrWasNotCalled();
3270
3271 // Once a focused event arrives, we get an ANR for this application
3272 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3273 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003274 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003275 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003276 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3277 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003278 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003279 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003280 ASSERT_TRUE(mDispatcher->waitForIdle());
3281}
3282
3283// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003284// Make sure that we don't notify policy twice about the same ANR.
3285TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003286 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003287 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3288 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003289
3290 // Once a focused event arrives, we get an ANR for this application
3291 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3292 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003293 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003294 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003295 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3296 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003297 const std::chrono::duration appTimeout =
3298 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003299 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003300
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003301 std::this_thread::sleep_for(appTimeout);
3302 // ANR should not be raised again. It is up to policy to do that if it desires.
3303 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003304
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003305 // If we now get a focused window, the ANR should stop, but the policy handles that via
3306 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003307 ASSERT_TRUE(mDispatcher->waitForIdle());
3308}
3309
3310// We have a focused application, but no focused window
3311TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003312 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003313 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3314 mWindow->consumeFocusEvent(false);
3315
3316 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003317 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003318 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003319 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3320 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003321
3322 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003323 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003324
3325 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003326 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003327 ASSERT_TRUE(mDispatcher->waitForIdle());
3328 mWindow->assertNoEvents();
3329}
3330
3331/**
3332 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3333 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3334 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3335 * the ANR mechanism should still work.
3336 *
3337 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3338 * DOWN event, while not responding on the second one.
3339 */
3340TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3341 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3342 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3343 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3344 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3345 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003346 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003347
3348 // Now send ACTION_UP, with identical timestamp
3349 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3350 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3351 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3352 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003353 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003354
3355 // We have now sent down and up. Let's consume first event and then ANR on the second.
3356 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3357 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003358 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003359}
3360
3361// If an app is not responding to a key event, gesture monitors should continue to receive
3362// new motion events
3363TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3364 FakeMonitorReceiver monitor =
3365 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3366 true /*isGestureMonitor*/);
3367
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3369 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003370 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003371 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003372
3373 // Stuck on the ACTION_UP
3374 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003375 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003376
3377 // New tap will go to the gesture monitor, but not to the window
3378 tapOnWindow();
3379 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3380 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3381
3382 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3383 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003384 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003385 mWindow->assertNoEvents();
3386 monitor.assertNoEvents();
3387}
3388
3389// If an app is not responding to a motion event, gesture monitors should continue to receive
3390// new motion events
3391TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3392 FakeMonitorReceiver monitor =
3393 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3394 true /*isGestureMonitor*/);
3395
3396 tapOnWindow();
3397 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3398 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3399
3400 mWindow->consumeMotionDown();
3401 // Stuck on the ACTION_UP
3402 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003403 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003404
3405 // New tap will go to the gesture monitor, but not to the window
3406 tapOnWindow();
3407 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3408 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3409
3410 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3411 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003412 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003413 mWindow->assertNoEvents();
3414 monitor.assertNoEvents();
3415}
3416
3417// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3418// process events, you don't get an anr. When the window later becomes unresponsive again, you
3419// get an ANR again.
3420// 1. tap -> block on ACTION_UP -> receive ANR
3421// 2. consume all pending events (= queue becomes healthy again)
3422// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3423TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3424 tapOnWindow();
3425
3426 mWindow->consumeMotionDown();
3427 // Block on ACTION_UP
3428 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003429 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003430 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3431 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003432 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003433 mWindow->assertNoEvents();
3434
3435 tapOnWindow();
3436 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003437 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003438 mWindow->consumeMotionUp();
3439
3440 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003441 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003442 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003443 mWindow->assertNoEvents();
3444}
3445
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003446// If a connection remains unresponsive for a while, make sure policy is only notified once about
3447// it.
3448TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003450 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3451 WINDOW_LOCATION));
3452
3453 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003454 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003455 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003456 // 'notifyConnectionUnresponsive' should only be called once per connection
3457 mFakePolicy->assertNotifyAnrWasNotCalled();
3458 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003459 mWindow->consumeMotionDown();
3460 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3461 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3462 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003463 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003464 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003465 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003466}
3467
3468/**
3469 * If a window is processing a motion event, and then a key event comes in, the key event should
3470 * not to to the focused window until the motion is processed.
3471 *
3472 * Warning!!!
3473 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3474 * and the injection timeout that we specify when injecting the key.
3475 * We must have the injection timeout (10ms) be smaller than
3476 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3477 *
3478 * If that value changes, this test should also change.
3479 */
3480TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3481 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3482 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3483
3484 tapOnWindow();
3485 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3486 ASSERT_TRUE(downSequenceNum);
3487 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3488 ASSERT_TRUE(upSequenceNum);
3489 // Don't finish the events yet, and send a key
3490 // Injection will "succeed" because we will eventually give up and send the key to the focused
3491 // window even if motions are still being processed. But because the injection timeout is short,
3492 // we will receive INJECTION_TIMED_OUT as the result.
3493
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003494 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003495 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003496 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3497 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003498 // Key will not be sent to the window, yet, because the window is still processing events
3499 // and the key remains pending, waiting for the touch events to be processed
3500 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3501 ASSERT_FALSE(keySequenceNum);
3502
3503 std::this_thread::sleep_for(500ms);
3504 // if we wait long enough though, dispatcher will give up, and still send the key
3505 // to the focused window, even though we have not yet finished the motion event
3506 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3507 mWindow->finishEvent(*downSequenceNum);
3508 mWindow->finishEvent(*upSequenceNum);
3509}
3510
3511/**
3512 * If a window is processing a motion event, and then a key event comes in, the key event should
3513 * not go to the focused window until the motion is processed.
3514 * If then a new motion comes in, then the pending key event should be going to the currently
3515 * focused window right away.
3516 */
3517TEST_F(InputDispatcherSingleWindowAnr,
3518 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3519 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3521
3522 tapOnWindow();
3523 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3524 ASSERT_TRUE(downSequenceNum);
3525 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3526 ASSERT_TRUE(upSequenceNum);
3527 // Don't finish the events yet, and send a key
3528 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003530 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003531 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003532 // At this point, key is still pending, and should not be sent to the application yet.
3533 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3534 ASSERT_FALSE(keySequenceNum);
3535
3536 // Now tap down again. It should cause the pending key to go to the focused window right away.
3537 tapOnWindow();
3538 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3539 // the other events yet. We can finish events in any order.
3540 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3541 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3542 mWindow->consumeMotionDown();
3543 mWindow->consumeMotionUp();
3544 mWindow->assertNoEvents();
3545}
3546
3547class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3548 virtual void SetUp() override {
3549 InputDispatcherTest::SetUp();
3550
Chris Yea209fde2020-07-22 13:54:51 -07003551 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003552 mApplication->setDispatchingTimeout(10ms);
3553 mUnfocusedWindow =
3554 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3555 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3556 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3557 // window.
3558 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003559 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3560 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3561 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003562
3563 mFocusedWindow =
3564 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003565 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003566 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003567 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3568 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003569
3570 // Set focused application.
3571 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003572 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003573
3574 // Expect one focus window exist in display.
3575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003576 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003577 mFocusedWindow->consumeFocusEvent(true);
3578 }
3579
3580 virtual void TearDown() override {
3581 InputDispatcherTest::TearDown();
3582
3583 mUnfocusedWindow.clear();
3584 mFocusedWindow.clear();
3585 }
3586
3587protected:
Chris Yea209fde2020-07-22 13:54:51 -07003588 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003589 sp<FakeWindowHandle> mUnfocusedWindow;
3590 sp<FakeWindowHandle> mFocusedWindow;
3591 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3592 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3593 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3594
3595 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3596
3597 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3598
3599private:
3600 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003602 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3603 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003605 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3606 location));
3607 }
3608};
3609
3610// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3611// should be ANR'd first.
3612TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003614 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3615 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003616 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003617 mFocusedWindow->consumeMotionDown();
3618 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3619 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3620 // We consumed all events, so no ANR
3621 ASSERT_TRUE(mDispatcher->waitForIdle());
3622 mFakePolicy->assertNotifyAnrWasNotCalled();
3623
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003624 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003625 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3626 FOCUSED_WINDOW_LOCATION));
3627 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
3628 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003629
3630 const std::chrono::duration timeout =
3631 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003632 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003633 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
3634 // sequence to make it consistent
3635 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003636 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003637 mFocusedWindow->consumeMotionDown();
3638 // This cancel is generated because the connection was unresponsive
3639 mFocusedWindow->consumeMotionCancel();
3640 mFocusedWindow->assertNoEvents();
3641 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003642 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003643 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003644 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003645}
3646
3647// If we have 2 windows with identical timeouts that are both unresponsive,
3648// it doesn't matter which order they should have ANR.
3649// But we should receive ANR for both.
3650TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
3651 // Set the timeout for unfocused window to match the focused window
3652 mUnfocusedWindow->setDispatchingTimeout(10ms);
3653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3654
3655 tapOnFocusedWindow();
3656 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003657 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
3658 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003659
3660 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003661 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
3662 mFocusedWindow->getToken() == anrConnectionToken2);
3663 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
3664 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003665
3666 ASSERT_TRUE(mDispatcher->waitForIdle());
3667 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003668
3669 mFocusedWindow->consumeMotionDown();
3670 mFocusedWindow->consumeMotionUp();
3671 mUnfocusedWindow->consumeMotionOutside();
3672
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003673 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
3674 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003675
3676 // Both applications should be marked as responsive, in any order
3677 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
3678 mFocusedWindow->getToken() == responsiveToken2);
3679 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
3680 mUnfocusedWindow->getToken() == responsiveToken2);
3681 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003682}
3683
3684// If a window is already not responding, the second tap on the same window should be ignored.
3685// We should also log an error to account for the dropped event (not tested here).
3686// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
3687TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
3688 tapOnFocusedWindow();
3689 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3690 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3691 // Receive the events, but don't respond
3692 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
3693 ASSERT_TRUE(downEventSequenceNum);
3694 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
3695 ASSERT_TRUE(upEventSequenceNum);
3696 const std::chrono::duration timeout =
3697 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003698 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003699
3700 // Tap once again
3701 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003702 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003703 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3704 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003705 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003706 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3707 FOCUSED_WINDOW_LOCATION));
3708 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
3709 // valid touch target
3710 mUnfocusedWindow->assertNoEvents();
3711
3712 // Consume the first tap
3713 mFocusedWindow->finishEvent(*downEventSequenceNum);
3714 mFocusedWindow->finishEvent(*upEventSequenceNum);
3715 ASSERT_TRUE(mDispatcher->waitForIdle());
3716 // The second tap did not go to the focused window
3717 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003718 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003719 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003720 mFakePolicy->assertNotifyAnrWasNotCalled();
3721}
3722
3723// If you tap outside of all windows, there will not be ANR
3724TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003725 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003726 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3727 LOCATION_OUTSIDE_ALL_WINDOWS));
3728 ASSERT_TRUE(mDispatcher->waitForIdle());
3729 mFakePolicy->assertNotifyAnrWasNotCalled();
3730}
3731
3732// Since the focused window is paused, tapping on it should not produce any events
3733TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
3734 mFocusedWindow->setPaused(true);
3735 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3736
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003737 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003738 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3739 FOCUSED_WINDOW_LOCATION));
3740
3741 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
3742 ASSERT_TRUE(mDispatcher->waitForIdle());
3743 // Should not ANR because the window is paused, and touches shouldn't go to it
3744 mFakePolicy->assertNotifyAnrWasNotCalled();
3745
3746 mFocusedWindow->assertNoEvents();
3747 mUnfocusedWindow->assertNoEvents();
3748}
3749
3750/**
3751 * If a window is processing a motion event, and then a key event comes in, the key event should
3752 * not to to the focused window until the motion is processed.
3753 * If a different window becomes focused at this time, the key should go to that window instead.
3754 *
3755 * Warning!!!
3756 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3757 * and the injection timeout that we specify when injecting the key.
3758 * We must have the injection timeout (10ms) be smaller than
3759 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3760 *
3761 * If that value changes, this test should also change.
3762 */
3763TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
3764 // Set a long ANR timeout to prevent it from triggering
3765 mFocusedWindow->setDispatchingTimeout(2s);
3766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3767
3768 tapOnUnfocusedWindow();
3769 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
3770 ASSERT_TRUE(downSequenceNum);
3771 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
3772 ASSERT_TRUE(upSequenceNum);
3773 // Don't finish the events yet, and send a key
3774 // Injection will succeed because we will eventually give up and send the key to the focused
3775 // window even if motions are still being processed.
3776
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003777 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003778 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003779 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003781 // Key will not be sent to the window, yet, because the window is still processing events
3782 // and the key remains pending, waiting for the touch events to be processed
3783 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
3784 ASSERT_FALSE(keySequenceNum);
3785
3786 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07003787 mFocusedWindow->setFocusable(false);
3788 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003790 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003791
3792 // Focus events should precede the key events
3793 mUnfocusedWindow->consumeFocusEvent(true);
3794 mFocusedWindow->consumeFocusEvent(false);
3795
3796 // Finish the tap events, which should unblock dispatcher
3797 mUnfocusedWindow->finishEvent(*downSequenceNum);
3798 mUnfocusedWindow->finishEvent(*upSequenceNum);
3799
3800 // Now that all queues are cleared and no backlog in the connections, the key event
3801 // can finally go to the newly focused "mUnfocusedWindow".
3802 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3803 mFocusedWindow->assertNoEvents();
3804 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003805 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003806}
3807
3808// When the touch stream is split across 2 windows, and one of them does not respond,
3809// then ANR should be raised and the touch should be canceled for the unresponsive window.
3810// The other window should not be affected by that.
3811TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
3812 // Touch Window 1
3813 NotifyMotionArgs motionArgs =
3814 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3815 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
3816 mDispatcher->notifyMotion(&motionArgs);
3817 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3818 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3819
3820 // Touch Window 2
3821 int32_t actionPointerDown =
3822 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3823
3824 motionArgs =
3825 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3826 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
3827 mDispatcher->notifyMotion(&motionArgs);
3828
3829 const std::chrono::duration timeout =
3830 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003831 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003832
3833 mUnfocusedWindow->consumeMotionDown();
3834 mFocusedWindow->consumeMotionDown();
3835 // Focused window may or may not receive ACTION_MOVE
3836 // But it should definitely receive ACTION_CANCEL due to the ANR
3837 InputEvent* event;
3838 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
3839 ASSERT_TRUE(moveOrCancelSequenceNum);
3840 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
3841 ASSERT_NE(nullptr, event);
3842 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
3843 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
3844 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
3845 mFocusedWindow->consumeMotionCancel();
3846 } else {
3847 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
3848 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003849 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003850 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003851
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003852 mUnfocusedWindow->assertNoEvents();
3853 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003854 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003855}
3856
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003857/**
3858 * If we have no focused window, and a key comes in, we start the ANR timer.
3859 * The focused application should add a focused window before the timer runs out to prevent ANR.
3860 *
3861 * If the user touches another application during this time, the key should be dropped.
3862 * Next, if a new focused window comes in, without toggling the focused application,
3863 * then no ANR should occur.
3864 *
3865 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
3866 * but in some cases the policy may not update the focused application.
3867 */
3868TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
3869 std::shared_ptr<FakeApplicationHandle> focusedApplication =
3870 std::make_shared<FakeApplicationHandle>();
3871 focusedApplication->setDispatchingTimeout(60ms);
3872 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
3873 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
3874 mFocusedWindow->setFocusable(false);
3875
3876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3877 mFocusedWindow->consumeFocusEvent(false);
3878
3879 // Send a key. The ANR timer should start because there is no focused window.
3880 // 'focusedApplication' will get blamed if this timer completes.
3881 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003882 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003883 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003884 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3885 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003886
3887 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
3888 // then the injected touches won't cause the focused event to get dropped.
3889 // The dispatcher only checks for whether the queue should be pruned upon queueing.
3890 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
3891 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
3892 // For this test, it means that the key would get delivered to the window once it becomes
3893 // focused.
3894 std::this_thread::sleep_for(10ms);
3895
3896 // Touch unfocused window. This should force the pending key to get dropped.
3897 NotifyMotionArgs motionArgs =
3898 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3899 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
3900 mDispatcher->notifyMotion(&motionArgs);
3901
3902 // We do not consume the motion right away, because that would require dispatcher to first
3903 // process (== drop) the key event, and by that time, ANR will be raised.
3904 // Set the focused window first.
3905 mFocusedWindow->setFocusable(true);
3906 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3907 setFocusedWindow(mFocusedWindow);
3908 mFocusedWindow->consumeFocusEvent(true);
3909 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
3910 // to another application. This could be a bug / behaviour in the policy.
3911
3912 mUnfocusedWindow->consumeMotionDown();
3913
3914 ASSERT_TRUE(mDispatcher->waitForIdle());
3915 // Should not ANR because we actually have a focused window. It was just added too slowly.
3916 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
3917}
3918
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003919// These tests ensure we cannot send touch events to a window that's positioned behind a window
3920// that has feature NO_INPUT_CHANNEL.
3921// Layout:
3922// Top (closest to user)
3923// mNoInputWindow (above all windows)
3924// mBottomWindow
3925// Bottom (furthest from user)
3926class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
3927 virtual void SetUp() override {
3928 InputDispatcherTest::SetUp();
3929
3930 mApplication = std::make_shared<FakeApplicationHandle>();
3931 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
3932 "Window without input channel", ADISPLAY_ID_DEFAULT,
3933 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
3934
3935 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3936 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
3937 // It's perfectly valid for this window to not have an associated input channel
3938
3939 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
3940 ADISPLAY_ID_DEFAULT);
3941 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
3942
3943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
3944 }
3945
3946protected:
3947 std::shared_ptr<FakeApplicationHandle> mApplication;
3948 sp<FakeWindowHandle> mNoInputWindow;
3949 sp<FakeWindowHandle> mBottomWindow;
3950};
3951
3952TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
3953 PointF touchedPoint = {10, 10};
3954
3955 NotifyMotionArgs motionArgs =
3956 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3957 ADISPLAY_ID_DEFAULT, {touchedPoint});
3958 mDispatcher->notifyMotion(&motionArgs);
3959
3960 mNoInputWindow->assertNoEvents();
3961 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
3962 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
3963 // and therefore should prevent mBottomWindow from receiving touches
3964 mBottomWindow->assertNoEvents();
3965}
3966
3967/**
3968 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
3969 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
3970 */
3971TEST_F(InputDispatcherMultiWindowOcclusionTests,
3972 NoInputChannelFeature_DropsTouchesWithValidChannel) {
3973 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
3974 "Window with input channel and NO_INPUT_CHANNEL",
3975 ADISPLAY_ID_DEFAULT);
3976
3977 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3978 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
3979 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
3980
3981 PointF touchedPoint = {10, 10};
3982
3983 NotifyMotionArgs motionArgs =
3984 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3985 ADISPLAY_ID_DEFAULT, {touchedPoint});
3986 mDispatcher->notifyMotion(&motionArgs);
3987
3988 mNoInputWindow->assertNoEvents();
3989 mBottomWindow->assertNoEvents();
3990}
3991
Vishnu Nair958da932020-08-21 17:12:37 -07003992class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
3993protected:
3994 std::shared_ptr<FakeApplicationHandle> mApp;
3995 sp<FakeWindowHandle> mWindow;
3996 sp<FakeWindowHandle> mMirror;
3997
3998 virtual void SetUp() override {
3999 InputDispatcherTest::SetUp();
4000 mApp = std::make_shared<FakeApplicationHandle>();
4001 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4002 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4003 mWindow->getToken());
4004 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4005 mWindow->setFocusable(true);
4006 mMirror->setFocusable(true);
4007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4008 }
4009};
4010
4011TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4012 // Request focus on a mirrored window
4013 setFocusedWindow(mMirror);
4014
4015 // window gets focused
4016 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4018 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004019 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4020}
4021
4022// A focused & mirrored window remains focused only if the window and its mirror are both
4023// focusable.
4024TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4025 setFocusedWindow(mMirror);
4026
4027 // window gets focused
4028 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4030 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004031 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004032 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4033 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004034 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4035
4036 mMirror->setFocusable(false);
4037 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4038
4039 // window loses focus since one of the windows associated with the token in not focusable
4040 mWindow->consumeFocusEvent(false);
4041
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4043 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004044 mWindow->assertNoEvents();
4045}
4046
4047// A focused & mirrored window remains focused until the window and its mirror both become
4048// invisible.
4049TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4050 setFocusedWindow(mMirror);
4051
4052 // window gets focused
4053 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4055 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004056 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4058 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004059 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4060
4061 mMirror->setVisible(false);
4062 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4063
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4065 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004066 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4068 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004069 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4070
4071 mWindow->setVisible(false);
4072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4073
4074 // window loses focus only after all windows associated with the token become invisible.
4075 mWindow->consumeFocusEvent(false);
4076
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004077 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4078 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004079 mWindow->assertNoEvents();
4080}
4081
4082// A focused & mirrored window remains focused until both windows are removed.
4083TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4084 setFocusedWindow(mMirror);
4085
4086 // window gets focused
4087 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004088 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4089 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004090 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4092 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004093 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4094
4095 // single window is removed but the window token remains focused
4096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4097
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4099 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004100 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004101 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4102 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004103 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4104
4105 // Both windows are removed
4106 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4107 mWindow->consumeFocusEvent(false);
4108
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004109 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4110 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004111 mWindow->assertNoEvents();
4112}
4113
4114// Focus request can be pending until one window becomes visible.
4115TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4116 // Request focus on an invisible mirror.
4117 mWindow->setVisible(false);
4118 mMirror->setVisible(false);
4119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4120 setFocusedWindow(mMirror);
4121
4122 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004124 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004125 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004126
4127 mMirror->setVisible(true);
4128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4129
4130 // window gets focused
4131 mWindow->consumeFocusEvent(true);
4132 // window gets the pending key event
4133 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4134}
Prabir Pradhan99987712020-11-10 18:43:05 -08004135
4136class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4137protected:
4138 std::shared_ptr<FakeApplicationHandle> mApp;
4139 sp<FakeWindowHandle> mWindow;
4140 sp<FakeWindowHandle> mSecondWindow;
4141
4142 void SetUp() override {
4143 InputDispatcherTest::SetUp();
4144 mApp = std::make_shared<FakeApplicationHandle>();
4145 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4146 mWindow->setFocusable(true);
4147 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4148 mSecondWindow->setFocusable(true);
4149
4150 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4151 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4152
4153 setFocusedWindow(mWindow);
4154 mWindow->consumeFocusEvent(true);
4155 }
4156
4157 void notifyPointerCaptureChanged(bool enabled) {
4158 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
4159 mDispatcher->notifyPointerCaptureChanged(&args);
4160 }
4161
4162 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
4163 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4164 mFakePolicy->waitForSetPointerCapture(enabled);
4165 notifyPointerCaptureChanged(enabled);
4166 window->consumeCaptureEvent(enabled);
4167 }
4168};
4169
4170TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4171 // Ensure that capture cannot be obtained for unfocused windows.
4172 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4173 mFakePolicy->assertSetPointerCaptureNotCalled();
4174 mSecondWindow->assertNoEvents();
4175
4176 // Ensure that capture can be enabled from the focus window.
4177 requestAndVerifyPointerCapture(mWindow, true);
4178
4179 // Ensure that capture cannot be disabled from a window that does not have capture.
4180 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4181 mFakePolicy->assertSetPointerCaptureNotCalled();
4182
4183 // Ensure that capture can be disabled from the window with capture.
4184 requestAndVerifyPointerCapture(mWindow, false);
4185}
4186
4187TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4188 requestAndVerifyPointerCapture(mWindow, true);
4189
4190 setFocusedWindow(mSecondWindow);
4191
4192 // Ensure that the capture disabled event was sent first.
4193 mWindow->consumeCaptureEvent(false);
4194 mWindow->consumeFocusEvent(false);
4195 mSecondWindow->consumeFocusEvent(true);
4196 mFakePolicy->waitForSetPointerCapture(false);
4197
4198 // Ensure that additional state changes from InputReader are not sent to the window.
4199 notifyPointerCaptureChanged(false);
4200 notifyPointerCaptureChanged(true);
4201 notifyPointerCaptureChanged(false);
4202 mWindow->assertNoEvents();
4203 mSecondWindow->assertNoEvents();
4204 mFakePolicy->assertSetPointerCaptureNotCalled();
4205}
4206
4207TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4208 requestAndVerifyPointerCapture(mWindow, true);
4209
4210 // InputReader unexpectedly disables and enables pointer capture.
4211 notifyPointerCaptureChanged(false);
4212 notifyPointerCaptureChanged(true);
4213
4214 // Ensure that Pointer Capture is disabled.
Prabir Pradhan7d030382020-12-21 07:58:35 -08004215 mFakePolicy->waitForSetPointerCapture(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004216 mWindow->consumeCaptureEvent(false);
4217 mWindow->assertNoEvents();
4218}
4219
Garfield Tane84e6f92019-08-29 17:28:41 -07004220} // namespace android::inputdispatcher