blob: c819091ae0a677aeb30ef0b2118b803ae6d2ad57 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Garfield Tan1c7bc862020-01-28 13:24:04 -080019#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070020#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070021#include <binder/Binder.h>
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -080022#include <input/Input.h>
Robert Carr803535b2018-08-02 16:38:15 -070023
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <gtest/gtest.h>
25#include <linux/input.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080026#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070027#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080028#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080029#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080030
Garfield Tan1c7bc862020-01-28 13:24:04 -080031using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080032using android::os::InputEventInjectionResult;
33using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010034using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080035
Garfield Tane84e6f92019-08-29 17:28:41 -070036namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080037
38// An arbitrary time value.
39static const nsecs_t ARBITRARY_TIME = 1234;
40
41// An arbitrary device id.
42static const int32_t DEVICE_ID = 1;
43
Jeff Brownf086ddb2014-02-11 14:28:48 -080044// An arbitrary display id.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -080045static const int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
Jeff Brownf086ddb2014-02-11 14:28:48 -080046
Michael Wrightd02c5b62014-02-10 15:10:22 -080047// An arbitrary injector pid / uid pair that has permission to inject events.
48static const int32_t INJECTOR_PID = 999;
49static const int32_t INJECTOR_UID = 1001;
50
chaviwd1c23182019-12-20 18:44:56 -080051struct PointF {
52 float x;
53 float y;
54};
Michael Wrightd02c5b62014-02-10 15:10:22 -080055
Gang Wang342c9272020-01-13 13:15:04 -050056/**
57 * Return a DOWN key event with KEYCODE_A.
58 */
59static KeyEvent getTestKeyEvent() {
60 KeyEvent event;
61
Garfield Tanfbe732e2020-01-24 11:26:14 -080062 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
63 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
64 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050065 return event;
66}
67
Michael Wrightd02c5b62014-02-10 15:10:22 -080068// --- FakeInputDispatcherPolicy ---
69
70class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
71 InputDispatcherConfiguration mConfig;
72
73protected:
74 virtual ~FakeInputDispatcherPolicy() {
75 }
76
77public:
78 FakeInputDispatcherPolicy() {
Jackal Guof9696682018-10-05 12:23:23 +080079 }
80
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080081 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080082 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
83 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080084 }
85
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080086 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080087 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
88 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080089 }
90
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070091 void assertFilterInputEventWasNotCalled() {
92 std::scoped_lock lock(mLock);
93 ASSERT_EQ(nullptr, mFilteredEvent);
94 }
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080096 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070097 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080098 ASSERT_TRUE(mConfigurationChangedTime)
99 << "Timed out waiting for configuration changed call";
100 ASSERT_EQ(*mConfigurationChangedTime, when);
101 mConfigurationChangedTime = std::nullopt;
102 }
103
104 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700105 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800106 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800107 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800108 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
109 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
110 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
111 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
112 mLastNotifySwitch = std::nullopt;
113 }
114
chaviwfd6d3512019-03-25 13:23:49 -0700115 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700116 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800117 ASSERT_EQ(touchedToken, mOnPointerDownToken);
118 mOnPointerDownToken.clear();
119 }
120
121 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700122 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800123 ASSERT_TRUE(mOnPointerDownToken == nullptr)
124 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700125 }
126
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700127 // This function must be called soon after the expected ANR timer starts,
128 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500129 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700130 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500131 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
132 std::shared_ptr<InputApplicationHandle> application;
133 { // acquire lock
134 std::unique_lock lock(mLock);
135 android::base::ScopedLockAssertion assumeLocked(mLock);
136 ASSERT_NO_FATAL_FAILURE(
137 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
138 } // release lock
139 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700140 }
141
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500142 void assertNotifyConnectionUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
143 const sp<IBinder>& expectedConnectionToken) {
144 sp<IBinder> connectionToken = getUnresponsiveConnectionToken(timeout);
145 ASSERT_EQ(expectedConnectionToken, connectionToken);
146 }
147
148 void assertNotifyConnectionResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
149 sp<IBinder> connectionToken = getResponsiveConnectionToken();
150 ASSERT_EQ(expectedConnectionToken, connectionToken);
151 }
152
153 sp<IBinder> getUnresponsiveConnectionToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700154 std::unique_lock lock(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700155 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500156 return getAnrTokenLockedInterruptible(timeout, mAnrConnectionTokens, lock);
157 }
158
159 sp<IBinder> getResponsiveConnectionToken() {
160 std::unique_lock lock(mLock);
161 android::base::ScopedLockAssertion assumeLocked(mLock);
162 return getAnrTokenLockedInterruptible(0s, mResponsiveConnectionTokens, lock);
163 }
164
165 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
166 // for a specific container to become non-empty. When the container is non-empty, return the
167 // first entry from the container and erase it.
168 template <class T>
169 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
170 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
171 const std::chrono::time_point start = std::chrono::steady_clock::now();
172 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700173
174 // If there is an ANR, Dispatcher won't be idle because there are still events
175 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
176 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500177 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
178 // to provide it some time to act. 100ms seems reasonable.
179 mNotifyAnr.wait_for(lock, timeToWait,
180 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700181 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500182 if (storage.empty()) {
183 ADD_FAILURE() << "Did not receive the ANR callback";
184 return nullptr;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700185 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700186 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
187 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700188 if (std::chrono::abs(timeout - waited) > 100ms) {
189 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
190 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
191 << "ms, but waited "
192 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
193 << "ms instead";
194 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500195 T token = storage.front();
196 storage.pop();
197 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700198 }
199
200 void assertNotifyAnrWasNotCalled() {
201 std::scoped_lock lock(mLock);
202 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500203 ASSERT_TRUE(mAnrConnectionTokens.empty());
204 ASSERT_TRUE(mResponsiveConnectionTokens.empty())
205 << "ANR was not called, but please also consume the 'connection is responsive' "
206 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700207 }
208
Garfield Tan1c7bc862020-01-28 13:24:04 -0800209 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
210 mConfig.keyRepeatTimeout = timeout;
211 mConfig.keyRepeatDelay = delay;
212 }
213
Prabir Pradhan99987712020-11-10 18:43:05 -0800214 void waitForSetPointerCapture(bool enabled) {
215 std::unique_lock lock(mLock);
216 base::ScopedLockAssertion assumeLocked(mLock);
217
218 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
219 [this, enabled]() REQUIRES(mLock) {
220 return mPointerCaptureEnabled &&
221 *mPointerCaptureEnabled ==
222 enabled;
223 })) {
224 FAIL() << "Timed out waiting for setPointerCapture(" << enabled << ") to be called.";
225 }
226 mPointerCaptureEnabled.reset();
227 }
228
229 void assertSetPointerCaptureNotCalled() {
230 std::unique_lock lock(mLock);
231 base::ScopedLockAssertion assumeLocked(mLock);
232
233 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
234 FAIL() << "Expected setPointerCapture(enabled) to not be called, but was called. "
235 "enabled = "
236 << *mPointerCaptureEnabled;
237 }
238 mPointerCaptureEnabled.reset();
239 }
240
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700242 std::mutex mLock;
243 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
244 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
245 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
246 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800247
Prabir Pradhan99987712020-11-10 18:43:05 -0800248 std::condition_variable mPointerCaptureChangedCondition;
249 std::optional<bool> mPointerCaptureEnabled GUARDED_BY(mLock);
250
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700251 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700252 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500253 std::queue<sp<IBinder>> mAnrConnectionTokens GUARDED_BY(mLock);
254 std::queue<sp<IBinder>> mResponsiveConnectionTokens GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700255 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700256
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600257 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700258 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800259 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800260 }
261
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500262 void notifyConnectionUnresponsive(const sp<IBinder>& connectionToken,
263 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700264 std::scoped_lock lock(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500265 mAnrConnectionTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700266 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500267 }
268
269 void notifyConnectionResponsive(const sp<IBinder>& connectionToken) override {
270 std::scoped_lock lock(mLock);
271 mResponsiveConnectionTokens.push(connectionToken);
272 mNotifyAnr.notify_all();
273 }
274
275 void notifyNoFocusedWindowAnr(
276 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
277 std::scoped_lock lock(mLock);
278 mAnrApplications.push(applicationHandle);
279 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800280 }
281
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600282 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600284 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700285
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600286 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700287 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
288 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
289 const std::vector<float>& values) override {}
290
291 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
292 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000293
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600294 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800295 *outConfig = mConfig;
296 }
297
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600298 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700299 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800300 switch (inputEvent->getType()) {
301 case AINPUT_EVENT_TYPE_KEY: {
302 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800303 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800304 break;
305 }
306
307 case AINPUT_EVENT_TYPE_MOTION: {
308 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800309 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800310 break;
311 }
312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800313 return true;
314 }
315
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600316 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800317
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600318 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800319
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600320 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800321 return 0;
322 }
323
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600324 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800325 return false;
326 }
327
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600328 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
329 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700330 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800331 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
332 * essentially a passthrough for notifySwitch.
333 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800334 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800335 }
336
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600337 void pokeUserActivity(nsecs_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800338
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600339 bool checkInjectEventsPermissionNonReentrant(int32_t, int32_t) override { return false; }
Jackal Guof9696682018-10-05 12:23:23 +0800340
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600341 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700342 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700343 mOnPointerDownToken = newToken;
344 }
345
Prabir Pradhan99987712020-11-10 18:43:05 -0800346 void setPointerCapture(bool enabled) override {
347 std::scoped_lock lock(mLock);
348 mPointerCaptureEnabled = {enabled};
349 mPointerCaptureChangedCondition.notify_all();
350 }
351
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800352 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
353 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700354 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800355 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
356 ASSERT_EQ(mFilteredEvent->getType(), type);
357
358 if (type == AINPUT_EVENT_TYPE_KEY) {
359 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
360 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
361 EXPECT_EQ(keyEvent.getAction(), action);
362 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
363 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
364 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
365 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
366 EXPECT_EQ(motionEvent.getAction(), action);
367 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
368 } else {
369 FAIL() << "Unknown type: " << type;
370 }
371
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800372 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800374};
375
Michael Wrightd02c5b62014-02-10 15:10:22 -0800376// --- InputDispatcherTest ---
377
378class InputDispatcherTest : public testing::Test {
379protected:
380 sp<FakeInputDispatcherPolicy> mFakePolicy;
381 sp<InputDispatcher> mDispatcher;
382
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700383 virtual void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 mFakePolicy = new FakeInputDispatcherPolicy();
385 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800386 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
387 //Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700388 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800389 }
390
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700391 virtual void TearDown() override {
392 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800393 mFakePolicy.clear();
394 mDispatcher.clear();
395 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700396
397 /**
398 * Used for debugging when writing the test
399 */
400 void dumpDispatcherState() {
401 std::string dump;
402 mDispatcher->dump(dump);
403 std::stringstream ss(dump);
404 std::string to;
405
406 while (std::getline(ss, to, '\n')) {
407 ALOGE("%s", to.c_str());
408 }
409 }
Vishnu Nair958da932020-08-21 17:12:37 -0700410
411 void setFocusedWindow(const sp<InputWindowHandle>& window,
412 const sp<InputWindowHandle>& focusedWindow = nullptr) {
413 FocusRequest request;
414 request.token = window->getToken();
415 if (focusedWindow) {
416 request.focusedToken = focusedWindow->getToken();
417 }
418 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
419 request.displayId = window->getInfo()->displayId;
420 mDispatcher->setFocusedWindow(request);
421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422};
423
424
425TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
426 KeyEvent event;
427
428 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800429 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
430 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600431 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
432 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800433 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700434 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800435 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436 << "Should reject key events with undefined action.";
437
438 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800439 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
440 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600441 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800442 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700443 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800444 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445 << "Should reject key events with ACTION_MULTIPLE.";
446}
447
448TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
449 MotionEvent event;
450 PointerProperties pointerProperties[MAX_POINTERS + 1];
451 PointerCoords pointerCoords[MAX_POINTERS + 1];
452 for (int i = 0; i <= MAX_POINTERS; i++) {
453 pointerProperties[i].clear();
454 pointerProperties[i].id = i;
455 pointerCoords[i].clear();
456 }
457
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800458 // Some constants commonly used below
459 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
460 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
461 constexpr int32_t metaState = AMETA_NONE;
462 constexpr MotionClassification classification = MotionClassification::NONE;
463
chaviw9eaa22c2020-07-01 16:21:27 -0700464 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800466 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700467 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
468 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600469 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700470 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800471 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700472 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800473 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800474 << "Should reject motion events with undefined action.";
475
476 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800477 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700478 AMOTION_EVENT_ACTION_POINTER_DOWN |
479 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700480 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
481 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
482 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
483 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800484 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700485 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800486 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487 << "Should reject motion events with pointer down index too large.";
488
Garfield Tanfbe732e2020-01-24 11:26:14 -0800489 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700490 AMOTION_EVENT_ACTION_POINTER_DOWN |
491 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700492 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
493 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
494 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
495 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800496 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700497 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800498 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 << "Should reject motion events with pointer down index too small.";
500
501 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800502 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700503 AMOTION_EVENT_ACTION_POINTER_UP |
504 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700505 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
506 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
507 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
508 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800509 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700510 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800511 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800512 << "Should reject motion events with pointer up index too large.";
513
Garfield Tanfbe732e2020-01-24 11:26:14 -0800514 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700515 AMOTION_EVENT_ACTION_POINTER_UP |
516 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700517 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
518 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
519 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
520 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800521 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700522 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800523 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524 << "Should reject motion events with pointer up index too small.";
525
526 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800527 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
528 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700529 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
530 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700531 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800532 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700533 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800534 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 << "Should reject motion events with 0 pointers.";
536
Garfield Tanfbe732e2020-01-24 11:26:14 -0800537 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
538 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700539 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
540 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700541 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800542 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700543 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800544 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 << "Should reject motion events with more than MAX_POINTERS pointers.";
546
547 // Rejects motion events with invalid pointer ids.
548 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800549 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
550 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700551 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
552 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700553 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800554 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700555 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800556 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557 << "Should reject motion events with pointer ids less than 0.";
558
559 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800560 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
561 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700562 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
563 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700564 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800565 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700566 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800567 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
569
570 // Rejects motion events with duplicate pointer ids.
571 pointerProperties[0].id = 1;
572 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800573 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
574 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700575 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
576 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700577 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800578 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700579 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800580 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800581 << "Should reject motion events with duplicate pointer ids.";
582}
583
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800584/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
585
586TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
587 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800588 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800589 mDispatcher->notifyConfigurationChanged(&args);
590 ASSERT_TRUE(mDispatcher->waitForIdle());
591
592 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
593}
594
595TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800596 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
597 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800598 mDispatcher->notifySwitch(&args);
599
600 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
601 args.policyFlags |= POLICY_FLAG_TRUSTED;
602 mFakePolicy->assertNotifySwitchWasCalled(args);
603}
604
Arthur Hungb92218b2018-08-14 12:00:21 +0800605// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700606static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700607static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800608
609class FakeApplicationHandle : public InputApplicationHandle {
610public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700611 FakeApplicationHandle() {
612 mInfo.name = "Fake Application";
613 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500614 mInfo.dispatchingTimeoutMillis =
615 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700616 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800617 virtual ~FakeApplicationHandle() {}
618
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700619 virtual bool updateInfo() override {
Arthur Hungb92218b2018-08-14 12:00:21 +0800620 return true;
621 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700622
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500623 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
624 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700625 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800626};
627
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800628class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800629public:
Garfield Tan15601662020-09-22 15:32:38 -0700630 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800631 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700632 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800633 }
634
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800635 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700636 InputEvent* event;
637 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
638 if (!consumeSeq) {
639 return nullptr;
640 }
641 finishEvent(*consumeSeq);
642 return event;
643 }
644
645 /**
646 * Receive an event without acknowledging it.
647 * Return the sequence number that could later be used to send finished signal.
648 */
649 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800650 uint32_t consumeSeq;
651 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800652
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800653 std::chrono::time_point start = std::chrono::steady_clock::now();
654 status_t status = WOULD_BLOCK;
655 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800656 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800657 &event);
658 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
659 if (elapsed > 100ms) {
660 break;
661 }
662 }
663
664 if (status == WOULD_BLOCK) {
665 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700666 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800667 }
668
669 if (status != OK) {
670 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700671 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800672 }
673 if (event == nullptr) {
674 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700675 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800676 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700677 if (outEvent != nullptr) {
678 *outEvent = event;
679 }
680 return consumeSeq;
681 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800682
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700683 /**
684 * To be used together with "receiveEvent" to complete the consumption of an event.
685 */
686 void finishEvent(uint32_t consumeSeq) {
687 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
688 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800689 }
690
691 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
692 int32_t expectedFlags) {
693 InputEvent* event = consume();
694
695 ASSERT_NE(nullptr, event) << mName.c_str()
696 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800697 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700698 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800699 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800700
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800701 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800702
Tiger Huang8664f8c2018-10-11 19:14:35 +0800703 switch (expectedEventType) {
704 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800705 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
706 EXPECT_EQ(expectedAction, keyEvent.getAction());
707 EXPECT_EQ(expectedFlags, keyEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800708 break;
709 }
710 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800711 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
712 EXPECT_EQ(expectedAction, motionEvent.getAction());
713 EXPECT_EQ(expectedFlags, motionEvent.getFlags());
Tiger Huang8664f8c2018-10-11 19:14:35 +0800714 break;
715 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100716 case AINPUT_EVENT_TYPE_FOCUS: {
717 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
718 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800719 case AINPUT_EVENT_TYPE_CAPTURE: {
720 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
721 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800722 default: {
723 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
724 }
725 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800726 }
727
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100728 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
729 InputEvent* event = consume();
730 ASSERT_NE(nullptr, event) << mName.c_str()
731 << ": consumer should have returned non-NULL event.";
732 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
733 << "Got " << inputEventTypeToString(event->getType())
734 << " event instead of FOCUS event";
735
736 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
737 << mName.c_str() << ": event displayId should always be NONE.";
738
739 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
740 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
741 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
742 }
743
Prabir Pradhan99987712020-11-10 18:43:05 -0800744 void consumeCaptureEvent(bool hasCapture) {
745 const InputEvent* event = consume();
746 ASSERT_NE(nullptr, event) << mName.c_str()
747 << ": consumer should have returned non-NULL event.";
748 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
749 << "Got " << inputEventTypeToString(event->getType())
750 << " event instead of CAPTURE event";
751
752 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
753 << mName.c_str() << ": event displayId should always be NONE.";
754
755 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
756 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
757 }
758
chaviwd1c23182019-12-20 18:44:56 -0800759 void assertNoEvents() {
760 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700761 if (event == nullptr) {
762 return;
763 }
764 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
765 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
766 ADD_FAILURE() << "Received key event "
767 << KeyEvent::actionToString(keyEvent.getAction());
768 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
769 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
770 ADD_FAILURE() << "Received motion event "
771 << MotionEvent::actionToString(motionEvent.getAction());
772 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
773 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
774 ADD_FAILURE() << "Received focus event, hasFocus = "
775 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800776 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
777 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
778 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
779 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700780 }
781 FAIL() << mName.c_str()
782 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800783 }
784
785 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
786
787protected:
788 std::unique_ptr<InputConsumer> mConsumer;
789 PreallocatedInputEventFactory mEventFactory;
790
791 std::string mName;
792};
793
794class FakeWindowHandle : public InputWindowHandle {
795public:
796 static const int32_t WIDTH = 600;
797 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800798
Chris Yea209fde2020-07-22 13:54:51 -0700799 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800800 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500801 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800802 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500803 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700804 base::Result<std::unique_ptr<InputChannel>> channel =
805 dispatcher->createInputChannel(name);
806 token = (*channel)->getConnectionToken();
807 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800808 }
809
810 inputApplicationHandle->updateInfo();
811 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
812
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500813 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700814 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800815 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100816 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500817 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
chaviwd1c23182019-12-20 18:44:56 -0800818 mInfo.frameLeft = 0;
819 mInfo.frameTop = 0;
820 mInfo.frameRight = WIDTH;
821 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700822 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800823 mInfo.globalScaleFactor = 1.0;
824 mInfo.touchableRegion.clear();
825 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
826 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700827 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800828 mInfo.hasWallpaper = false;
829 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800830 mInfo.ownerPid = INJECTOR_PID;
831 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800832 mInfo.displayId = displayId;
833 }
834
835 virtual bool updateInfo() { return true; }
836
Vishnu Nair47074b82020-08-14 11:54:47 -0700837 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800838
Vishnu Nair958da932020-08-21 17:12:37 -0700839 void setVisible(bool visible) { mInfo.visible = visible; }
840
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700841 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500842 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700843 }
844
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700845 void setPaused(bool paused) { mInfo.paused = paused; }
846
chaviwd1c23182019-12-20 18:44:56 -0800847 void setFrame(const Rect& frame) {
848 mInfo.frameLeft = frame.left;
849 mInfo.frameTop = frame.top;
850 mInfo.frameRight = frame.right;
851 mInfo.frameBottom = frame.bottom;
chaviw1ff3d1e2020-07-01 15:53:47 -0700852 mInfo.transform.set(frame.left, frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800853 mInfo.touchableRegion.clear();
854 mInfo.addTouchableRegion(frame);
855 }
856
Michael Wright44753b12020-07-08 13:48:11 +0100857 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800858
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500859 void setInputFeatures(InputWindowInfo::Feature features) { mInfo.inputFeatures = features; }
860
chaviw9eaa22c2020-07-01 16:21:27 -0700861 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
862 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
863 }
864
865 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700866
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800867 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
868 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
869 expectedFlags);
870 }
871
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700872 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
873 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
874 }
875
Svet Ganov5d3bc372020-01-26 23:11:07 -0800876 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
877 int32_t expectedFlags = 0) {
878 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
879 expectedFlags);
880 }
881
882 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
883 int32_t expectedFlags = 0) {
884 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
885 expectedFlags);
886 }
887
888 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
889 int32_t expectedFlags = 0) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800890 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
891 expectedFlags);
892 }
893
Svet Ganov5d3bc372020-01-26 23:11:07 -0800894 void consumeMotionPointerDown(int32_t pointerIdx,
895 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT, int32_t expectedFlags = 0) {
896 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN
897 | (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
898 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
899 }
900
901 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
902 int32_t expectedFlags = 0) {
903 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP
904 | (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
905 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
906 }
907
908 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
909 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +0000910 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
911 expectedFlags);
912 }
913
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500914 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
915 int32_t expectedFlags = 0) {
916 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
917 expectedFlags);
918 }
919
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100920 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
921 ASSERT_NE(mInputReceiver, nullptr)
922 << "Cannot consume events from a window with no receiver";
923 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
924 }
925
Prabir Pradhan99987712020-11-10 18:43:05 -0800926 void consumeCaptureEvent(bool hasCapture) {
927 ASSERT_NE(mInputReceiver, nullptr)
928 << "Cannot consume events from a window with no receiver";
929 mInputReceiver->consumeCaptureEvent(hasCapture);
930 }
931
chaviwd1c23182019-12-20 18:44:56 -0800932 void consumeEvent(int32_t expectedEventType, int32_t expectedAction, int32_t expectedDisplayId,
933 int32_t expectedFlags) {
934 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
935 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
936 expectedFlags);
937 }
938
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700939 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700940 if (mInputReceiver == nullptr) {
941 ADD_FAILURE() << "Invalid receive event on window with no receiver";
942 return std::nullopt;
943 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700944 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700945 }
946
947 void finishEvent(uint32_t sequenceNum) {
948 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
949 mInputReceiver->finishEvent(sequenceNum);
950 }
951
chaviwaf87b3e2019-10-01 16:59:28 -0700952 InputEvent* consume() {
953 if (mInputReceiver == nullptr) {
954 return nullptr;
955 }
956 return mInputReceiver->consume();
957 }
958
Arthur Hungb92218b2018-08-14 12:00:21 +0800959 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500960 if (mInputReceiver == nullptr &&
961 mInfo.inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL)) {
962 return; // Can't receive events if the window does not have input channel
963 }
964 ASSERT_NE(nullptr, mInputReceiver)
965 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -0800966 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +0800967 }
968
chaviwaf87b3e2019-10-01 16:59:28 -0700969 sp<IBinder> getToken() { return mInfo.token; }
970
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100971 const std::string& getName() { return mName; }
972
chaviwd1c23182019-12-20 18:44:56 -0800973private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100974 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -0800975 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700976 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800977};
978
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700979std::atomic<int32_t> FakeWindowHandle::sId{1};
980
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800981static InputEventInjectionResult injectKey(
982 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
983 int32_t displayId = ADISPLAY_ID_NONE,
984 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
985 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800986 KeyEvent event;
987 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
988
989 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800990 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700991 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
992 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +0800993
994 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700995 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
996 injectionTimeout,
997 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
Arthur Hungb92218b2018-08-14 12:00:21 +0800998}
999
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001000static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1001 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001002 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1003}
1004
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001005static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1006 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001007 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1008}
1009
Garfield Tandf26e862020-07-01 20:18:19 -07001010class PointerBuilder {
1011public:
1012 PointerBuilder(int32_t id, int32_t toolType) {
1013 mProperties.clear();
1014 mProperties.id = id;
1015 mProperties.toolType = toolType;
1016 mCoords.clear();
1017 }
1018
1019 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1020
1021 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1022
1023 PointerBuilder& axis(int32_t axis, float value) {
1024 mCoords.setAxisValue(axis, value);
1025 return *this;
1026 }
1027
1028 PointerProperties buildProperties() const { return mProperties; }
1029
1030 PointerCoords buildCoords() const { return mCoords; }
1031
1032private:
1033 PointerProperties mProperties;
1034 PointerCoords mCoords;
1035};
1036
1037class MotionEventBuilder {
1038public:
1039 MotionEventBuilder(int32_t action, int32_t source) {
1040 mAction = action;
1041 mSource = source;
1042 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1043 }
1044
1045 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1046 mEventTime = eventTime;
1047 return *this;
1048 }
1049
1050 MotionEventBuilder& displayId(int32_t displayId) {
1051 mDisplayId = displayId;
1052 return *this;
1053 }
1054
1055 MotionEventBuilder& actionButton(int32_t actionButton) {
1056 mActionButton = actionButton;
1057 return *this;
1058 }
1059
1060 MotionEventBuilder& buttonState(int32_t actionButton) {
1061 mActionButton = actionButton;
1062 return *this;
1063 }
1064
1065 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1066 mRawXCursorPosition = rawXCursorPosition;
1067 return *this;
1068 }
1069
1070 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1071 mRawYCursorPosition = rawYCursorPosition;
1072 return *this;
1073 }
1074
1075 MotionEventBuilder& pointer(PointerBuilder pointer) {
1076 mPointers.push_back(pointer);
1077 return *this;
1078 }
1079
1080 MotionEvent build() {
1081 std::vector<PointerProperties> pointerProperties;
1082 std::vector<PointerCoords> pointerCoords;
1083 for (const PointerBuilder& pointer : mPointers) {
1084 pointerProperties.push_back(pointer.buildProperties());
1085 pointerCoords.push_back(pointer.buildCoords());
1086 }
1087
1088 // Set mouse cursor position for the most common cases to avoid boilerplate.
1089 if (mSource == AINPUT_SOURCE_MOUSE &&
1090 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1091 mPointers.size() == 1) {
1092 mRawXCursorPosition = pointerCoords[0].getX();
1093 mRawYCursorPosition = pointerCoords[0].getY();
1094 }
1095
1096 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001097 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001098 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
1099 mAction, mActionButton, /* flags */ 0, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001100 mButtonState, MotionClassification::NONE, identityTransform,
1101 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
1102 mRawYCursorPosition, mEventTime, mEventTime, mPointers.size(),
1103 pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001104
1105 return event;
1106 }
1107
1108private:
1109 int32_t mAction;
1110 int32_t mSource;
1111 nsecs_t mEventTime;
1112 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1113 int32_t mActionButton{0};
1114 int32_t mButtonState{0};
1115 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1116 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1117
1118 std::vector<PointerBuilder> mPointers;
1119};
1120
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001121static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001122 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1123 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001124 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001125 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1126 injectionTimeout,
1127 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1128}
1129
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001130static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001131 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1132 const PointF& position,
1133 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001134 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1135 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001136 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001137 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001138 MotionEvent event = MotionEventBuilder(action, source)
1139 .displayId(displayId)
1140 .eventTime(eventTime)
1141 .rawXCursorPosition(cursorPosition.x)
1142 .rawYCursorPosition(cursorPosition.y)
1143 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1144 .x(position.x)
1145 .y(position.y))
1146 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001147
1148 // Inject event until dispatch out.
Garfield Tandf26e862020-07-01 20:18:19 -07001149 return injectMotionEvent(dispatcher, event);
Arthur Hungb92218b2018-08-14 12:00:21 +08001150}
1151
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001152static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1153 int32_t source, int32_t displayId,
1154 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001155 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001156}
1157
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001158static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1159 int32_t source, int32_t displayId,
1160 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001161 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001162}
1163
Jackal Guof9696682018-10-05 12:23:23 +08001164static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1165 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1166 // Define a valid key event.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001167 NotifyKeyArgs args(/* id */ 0, currentTime, DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
1168 POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A, KEY_A,
1169 AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001170
1171 return args;
1172}
1173
chaviwd1c23182019-12-20 18:44:56 -08001174static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1175 const std::vector<PointF>& points) {
1176 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001177 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1178 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1179 }
1180
chaviwd1c23182019-12-20 18:44:56 -08001181 PointerProperties pointerProperties[pointerCount];
1182 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001183
chaviwd1c23182019-12-20 18:44:56 -08001184 for (size_t i = 0; i < pointerCount; i++) {
1185 pointerProperties[i].clear();
1186 pointerProperties[i].id = i;
1187 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001188
chaviwd1c23182019-12-20 18:44:56 -08001189 pointerCoords[i].clear();
1190 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1191 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1192 }
Jackal Guof9696682018-10-05 12:23:23 +08001193
1194 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1195 // Define a valid motion event.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001196 NotifyMotionArgs args(/* id */ 0, currentTime, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001197 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1198 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001199 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1200 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001201 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1202 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001203
1204 return args;
1205}
1206
chaviwd1c23182019-12-20 18:44:56 -08001207static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1208 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1209}
1210
Prabir Pradhan99987712020-11-10 18:43:05 -08001211static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(bool enabled) {
1212 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), enabled);
1213}
1214
Arthur Hungb92218b2018-08-14 12:00:21 +08001215TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001216 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001217 sp<FakeWindowHandle> window = new FakeWindowHandle(application, mDispatcher, "Fake Window",
1218 ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001219
Arthur Hung72d8dc32020-03-28 00:48:39 +00001220 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001221 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1222 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1223 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001224
1225 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001226 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001227}
1228
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001229/**
1230 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1231 * To ensure that window receives only events that were directly inside of it, add
1232 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1233 * when finding touched windows.
1234 * This test serves as a sanity check for the next test, where setInputWindows is
1235 * called twice.
1236 */
1237TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001238 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001239 sp<FakeWindowHandle> window =
1240 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1241 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001242 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001243
1244 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001246 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1247 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001248 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001249
1250 // Window should receive motion event.
1251 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1252}
1253
1254/**
1255 * Calling setInputWindows twice, with the same info, should not cause any issues.
1256 * To ensure that window receives only events that were directly inside of it, add
1257 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1258 * when finding touched windows.
1259 */
1260TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001261 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001262 sp<FakeWindowHandle> window =
1263 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1264 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001265 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001266
1267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001270 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1271 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001272 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001273
1274 // Window should receive motion event.
1275 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1276}
1277
Arthur Hungb92218b2018-08-14 12:00:21 +08001278// The foreground window should receive the first touch down event.
1279TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001280 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001281 sp<FakeWindowHandle> windowTop = new FakeWindowHandle(application, mDispatcher, "Top",
1282 ADISPLAY_ID_DEFAULT);
1283 sp<FakeWindowHandle> windowSecond = new FakeWindowHandle(application, mDispatcher, "Second",
1284 ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001285
Arthur Hung72d8dc32020-03-28 00:48:39 +00001286 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1288 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1289 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001290
1291 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001292 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001293 windowSecond->assertNoEvents();
1294}
1295
Garfield Tandf26e862020-07-01 20:18:19 -07001296TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001297 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001298 sp<FakeWindowHandle> windowLeft =
1299 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1300 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001301 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001302 sp<FakeWindowHandle> windowRight =
1303 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1304 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001305 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001306
1307 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1308
1309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1310
1311 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001312 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001313 injectMotionEvent(mDispatcher,
1314 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1315 AINPUT_SOURCE_MOUSE)
1316 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1317 .x(900)
1318 .y(400))
1319 .build()));
1320 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1321 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1322 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1323 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1324
1325 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001327 injectMotionEvent(mDispatcher,
1328 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1329 AINPUT_SOURCE_MOUSE)
1330 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1331 .x(300)
1332 .y(400))
1333 .build()));
1334 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1335 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1336 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1337 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1338 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1339 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1340
1341 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001342 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001343 injectMotionEvent(mDispatcher,
1344 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1345 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1346 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1347 .x(300)
1348 .y(400))
1349 .build()));
1350 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1351
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001352 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001353 injectMotionEvent(mDispatcher,
1354 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1355 AINPUT_SOURCE_MOUSE)
1356 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1357 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1358 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1359 .x(300)
1360 .y(400))
1361 .build()));
1362 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1363 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1364
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001365 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001366 injectMotionEvent(mDispatcher,
1367 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1368 AINPUT_SOURCE_MOUSE)
1369 .buttonState(0)
1370 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1371 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1372 .x(300)
1373 .y(400))
1374 .build()));
1375 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1376 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1377
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001379 injectMotionEvent(mDispatcher,
1380 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1381 .buttonState(0)
1382 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1383 .x(300)
1384 .y(400))
1385 .build()));
1386 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1387
1388 // Move mouse cursor back to right window
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_HOVER_MOVE,
1392 AINPUT_SOURCE_MOUSE)
1393 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1394 .x(900)
1395 .y(400))
1396 .build()));
1397 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1398 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1399 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1400 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1401 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1402 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1403}
1404
1405// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1406// directly in this test.
1407TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001408 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001409 sp<FakeWindowHandle> window =
1410 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1411 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001412 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001413
1414 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1415
1416 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1417
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001418 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001419 injectMotionEvent(mDispatcher,
1420 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1421 AINPUT_SOURCE_MOUSE)
1422 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1423 .x(300)
1424 .y(400))
1425 .build()));
1426 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1427 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1428
1429 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001430 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001431 injectMotionEvent(mDispatcher,
1432 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1433 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1434 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1435 .x(300)
1436 .y(400))
1437 .build()));
1438 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1439
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001441 injectMotionEvent(mDispatcher,
1442 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1443 AINPUT_SOURCE_MOUSE)
1444 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1445 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1446 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1447 .x(300)
1448 .y(400))
1449 .build()));
1450 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1451 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1452
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001453 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001454 injectMotionEvent(mDispatcher,
1455 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1456 AINPUT_SOURCE_MOUSE)
1457 .buttonState(0)
1458 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1459 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1460 .x(300)
1461 .y(400))
1462 .build()));
1463 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1464 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1465
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001467 injectMotionEvent(mDispatcher,
1468 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1469 .buttonState(0)
1470 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1471 .x(300)
1472 .y(400))
1473 .build()));
1474 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1475
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001476 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001477 injectMotionEvent(mDispatcher,
1478 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1479 AINPUT_SOURCE_MOUSE)
1480 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1481 .x(300)
1482 .y(400))
1483 .build()));
1484 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1485 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1486}
1487
Garfield Tan00f511d2019-06-12 16:55:40 -07001488TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001489 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001490
1491 sp<FakeWindowHandle> windowLeft =
1492 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1493 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001494 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001495 sp<FakeWindowHandle> windowRight =
1496 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1497 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001498 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001499
1500 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1501
Arthur Hung72d8dc32020-03-28 00:48:39 +00001502 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001503
1504 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1505 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001506 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001507 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001508 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001509 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001510 windowRight->assertNoEvents();
1511}
1512
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001513TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001514 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001515 sp<FakeWindowHandle> window =
1516 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001517 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001518
Arthur Hung72d8dc32020-03-28 00:48:39 +00001519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001520 setFocusedWindow(window);
1521
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001522 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001523
1524 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1525 mDispatcher->notifyKey(&keyArgs);
1526
1527 // Window should receive key down event.
1528 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1529
1530 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1531 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001532 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001533 mDispatcher->notifyDeviceReset(&args);
1534 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1535 AKEY_EVENT_FLAG_CANCELED);
1536}
1537
1538TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001539 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001540 sp<FakeWindowHandle> window =
1541 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1542
Arthur Hung72d8dc32020-03-28 00:48:39 +00001543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001544
1545 NotifyMotionArgs motionArgs =
1546 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1547 ADISPLAY_ID_DEFAULT);
1548 mDispatcher->notifyMotion(&motionArgs);
1549
1550 // Window should receive motion down event.
1551 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1552
1553 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1554 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001555 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001556 mDispatcher->notifyDeviceReset(&args);
1557 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1558 0 /*expectedFlags*/);
1559}
1560
Svet Ganov5d3bc372020-01-26 23:11:07 -08001561TEST_F(InputDispatcherTest, TransferTouchFocus_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001562 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001563
1564 // Create a couple of windows
1565 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1566 "First Window", ADISPLAY_ID_DEFAULT);
1567 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1568 "Second Window", ADISPLAY_ID_DEFAULT);
1569
1570 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001572
1573 // Send down to the first window
1574 NotifyMotionArgs downMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1575 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1576 mDispatcher->notifyMotion(&downMotionArgs);
1577 // Only the first window should get the down event
1578 firstWindow->consumeMotionDown();
1579 secondWindow->assertNoEvents();
1580
1581 // Transfer touch focus to the second window
1582 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1583 // The first window gets cancel and the second gets down
1584 firstWindow->consumeMotionCancel();
1585 secondWindow->consumeMotionDown();
1586
1587 // Send up event to the second window
1588 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1589 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1590 mDispatcher->notifyMotion(&upMotionArgs);
1591 // The first window gets no events and the second gets up
1592 firstWindow->assertNoEvents();
1593 secondWindow->consumeMotionUp();
1594}
1595
1596TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointerNoSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001597 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001598
1599 PointF touchPoint = {10, 10};
1600
1601 // Create a couple of windows
1602 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1603 "First Window", ADISPLAY_ID_DEFAULT);
1604 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1605 "Second Window", ADISPLAY_ID_DEFAULT);
1606
1607 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001609
1610 // Send down to the first window
1611 NotifyMotionArgs downMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1612 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint});
1613 mDispatcher->notifyMotion(&downMotionArgs);
1614 // Only the first window should get the down event
1615 firstWindow->consumeMotionDown();
1616 secondWindow->assertNoEvents();
1617
1618 // Send pointer down to the first window
1619 NotifyMotionArgs pointerDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN
1620 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1621 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint, touchPoint});
1622 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1623 // Only the first window should get the pointer down event
1624 firstWindow->consumeMotionPointerDown(1);
1625 secondWindow->assertNoEvents();
1626
1627 // Transfer touch focus to the second window
1628 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1629 // The first window gets cancel and the second gets down and pointer down
1630 firstWindow->consumeMotionCancel();
1631 secondWindow->consumeMotionDown();
1632 secondWindow->consumeMotionPointerDown(1);
1633
1634 // Send pointer up to the second window
1635 NotifyMotionArgs pointerUpMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP
1636 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1637 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {touchPoint, touchPoint});
1638 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1639 // The first window gets nothing and the second gets pointer up
1640 firstWindow->assertNoEvents();
1641 secondWindow->consumeMotionPointerUp(1);
1642
1643 // Send up event to the second window
1644 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1645 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1646 mDispatcher->notifyMotion(&upMotionArgs);
1647 // The first window gets nothing and the second gets up
1648 firstWindow->assertNoEvents();
1649 secondWindow->consumeMotionUp();
1650}
1651
1652TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001653 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001654
1655 // Create a non touch modal window that supports split touch
1656 sp<FakeWindowHandle> firstWindow = new FakeWindowHandle(application, mDispatcher,
1657 "First Window", ADISPLAY_ID_DEFAULT);
1658 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001659 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1660 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001661
1662 // Create a non touch modal window that supports split touch
1663 sp<FakeWindowHandle> secondWindow = new FakeWindowHandle(application, mDispatcher,
1664 "Second Window", ADISPLAY_ID_DEFAULT);
1665 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001666 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1667 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001668
1669 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001671
1672 PointF pointInFirst = {300, 200};
1673 PointF pointInSecond = {300, 600};
1674
1675 // Send down to the first window
1676 NotifyMotionArgs firstDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
1677 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst});
1678 mDispatcher->notifyMotion(&firstDownMotionArgs);
1679 // Only the first window should get the down event
1680 firstWindow->consumeMotionDown();
1681 secondWindow->assertNoEvents();
1682
1683 // Send down to the second window
1684 NotifyMotionArgs secondDownMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN
1685 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1686 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst, pointInSecond});
1687 mDispatcher->notifyMotion(&secondDownMotionArgs);
1688 // The first window gets a move and the second a down
1689 firstWindow->consumeMotionMove();
1690 secondWindow->consumeMotionDown();
1691
1692 // Transfer touch focus to the second window
1693 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1694 // The first window gets cancel and the new gets pointer down (it already saw down)
1695 firstWindow->consumeMotionCancel();
1696 secondWindow->consumeMotionPointerDown(1);
1697
1698 // Send pointer up to the second window
1699 NotifyMotionArgs pointerUpMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP
1700 | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1701 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {pointInFirst, pointInSecond});
1702 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1703 // The first window gets nothing and the second gets pointer up
1704 firstWindow->assertNoEvents();
1705 secondWindow->consumeMotionPointerUp(1);
1706
1707 // Send up event to the second window
1708 NotifyMotionArgs upMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_UP,
1709 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT);
1710 mDispatcher->notifyMotion(&upMotionArgs);
1711 // The first window gets nothing and the second gets up
1712 firstWindow->assertNoEvents();
1713 secondWindow->consumeMotionUp();
1714}
1715
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001716TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001717 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001718 sp<FakeWindowHandle> window =
1719 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1720
Vishnu Nair47074b82020-08-14 11:54:47 -07001721 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001723 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001724
1725 window->consumeFocusEvent(true);
1726
1727 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1728 mDispatcher->notifyKey(&keyArgs);
1729
1730 // Window should receive key down event.
1731 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1732}
1733
1734TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001735 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001736 sp<FakeWindowHandle> window =
1737 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1738
Arthur Hung72d8dc32020-03-28 00:48:39 +00001739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001740
1741 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1742 mDispatcher->notifyKey(&keyArgs);
1743 mDispatcher->waitForIdle();
1744
1745 window->assertNoEvents();
1746}
1747
1748// If a window is touchable, but does not have focus, it should receive motion events, but not keys
1749TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07001750 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001751 sp<FakeWindowHandle> window =
1752 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1753
Arthur Hung72d8dc32020-03-28 00:48:39 +00001754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001755
1756 // Send key
1757 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1758 mDispatcher->notifyKey(&keyArgs);
1759 // Send motion
1760 NotifyMotionArgs motionArgs =
1761 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1762 ADISPLAY_ID_DEFAULT);
1763 mDispatcher->notifyMotion(&motionArgs);
1764
1765 // Window should receive only the motion event
1766 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1767 window->assertNoEvents(); // Key event or focus event will not be received
1768}
1769
chaviwd1c23182019-12-20 18:44:56 -08001770class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00001771public:
1772 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08001773 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07001774 base::Result<std::unique_ptr<InputChannel>> channel =
1775 dispatcher->createInputMonitor(displayId, isGestureMonitor, name);
1776 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00001777 }
1778
chaviwd1c23182019-12-20 18:44:56 -08001779 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
1780
1781 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1782 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
1783 expectedDisplayId, expectedFlags);
1784 }
1785
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001786 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
1787
1788 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
1789
chaviwd1c23182019-12-20 18:44:56 -08001790 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1791 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
1792 expectedDisplayId, expectedFlags);
1793 }
1794
1795 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1796 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
1797 expectedDisplayId, expectedFlags);
1798 }
1799
1800 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
1801
1802private:
1803 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00001804};
1805
1806// Tests for gesture monitors
1807TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001808 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001809 sp<FakeWindowHandle> window =
1810 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001812
chaviwd1c23182019-12-20 18:44:56 -08001813 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1814 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001815
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001816 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001817 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001818 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001819 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001820 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001821}
1822
1823TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001824 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001825 sp<FakeWindowHandle> window =
1826 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1827
1828 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001829 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001830
Arthur Hung72d8dc32020-03-28 00:48:39 +00001831 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001832 setFocusedWindow(window);
1833
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001834 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00001835
chaviwd1c23182019-12-20 18:44:56 -08001836 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1837 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001838
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
1840 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001841 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001842 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00001843}
1844
1845TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001846 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00001847 sp<FakeWindowHandle> window =
1848 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00001850
chaviwd1c23182019-12-20 18:44:56 -08001851 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
1852 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00001853
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001854 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001855 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001856 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00001857 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08001858 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001859
1860 window->releaseChannel();
1861
chaviwd1c23182019-12-20 18:44:56 -08001862 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00001863
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001864 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00001865 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001866 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08001867 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00001868}
1869
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001870TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
1871 FakeMonitorReceiver monitor =
1872 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
1873 true /*isGestureMonitor*/);
1874
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001876 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
1877 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
1878 ASSERT_TRUE(consumeSeq);
1879
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001880 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(DISPATCHING_TIMEOUT,
1881 monitor.getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001882 monitor.finishEvent(*consumeSeq);
1883 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001884 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(monitor.getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001885}
1886
chaviw81e2bb92019-12-18 15:03:51 -08001887TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001888 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08001889 sp<FakeWindowHandle> window =
1890 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1891
Arthur Hung72d8dc32020-03-28 00:48:39 +00001892 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08001893
1894 NotifyMotionArgs motionArgs =
1895 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1896 ADISPLAY_ID_DEFAULT);
1897
1898 mDispatcher->notifyMotion(&motionArgs);
1899 // Window should receive motion down event.
1900 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1901
1902 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001903 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08001904 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1905 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
1906 motionArgs.pointerCoords[0].getX() - 10);
1907
1908 mDispatcher->notifyMotion(&motionArgs);
1909 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
1910 0 /*expectedFlags*/);
1911}
1912
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001913/**
1914 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
1915 * the device default right away. In the test scenario, we check both the default value,
1916 * and the action of enabling / disabling.
1917 */
1918TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07001919 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001920 sp<FakeWindowHandle> window =
1921 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1922
1923 // Set focused application.
1924 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001925 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001926
1927 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00001928 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001929 setFocusedWindow(window);
1930
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001931 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1932
1933 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07001934 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001935 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001936 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
1937
1938 SCOPED_TRACE("Disable touch mode");
1939 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07001940 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001942 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001943 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
1944
1945 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07001946 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001947 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001948 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
1949
1950 SCOPED_TRACE("Enable touch mode again");
1951 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07001952 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001954 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001955 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1956
1957 window->assertNoEvents();
1958}
1959
Gang Wange9087892020-01-07 12:17:14 -05001960TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001961 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05001962 sp<FakeWindowHandle> window =
1963 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
1964
1965 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07001966 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05001967
Arthur Hung72d8dc32020-03-28 00:48:39 +00001968 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001969 setFocusedWindow(window);
1970
Gang Wange9087892020-01-07 12:17:14 -05001971 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
1972
1973 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
1974 mDispatcher->notifyKey(&keyArgs);
1975
1976 InputEvent* event = window->consume();
1977 ASSERT_NE(event, nullptr);
1978
1979 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
1980 ASSERT_NE(verified, nullptr);
1981 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
1982
1983 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
1984 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
1985 ASSERT_EQ(keyArgs.source, verified->source);
1986 ASSERT_EQ(keyArgs.displayId, verified->displayId);
1987
1988 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
1989
1990 ASSERT_EQ(keyArgs.action, verifiedKey.action);
1991 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05001992 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
1993 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
1994 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
1995 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
1996 ASSERT_EQ(0, verifiedKey.repeatCount);
1997}
1998
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08001999TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002000 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002001 sp<FakeWindowHandle> window =
2002 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2003
2004 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2005
Arthur Hung72d8dc32020-03-28 00:48:39 +00002006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002007
2008 NotifyMotionArgs motionArgs =
2009 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2010 ADISPLAY_ID_DEFAULT);
2011 mDispatcher->notifyMotion(&motionArgs);
2012
2013 InputEvent* event = window->consume();
2014 ASSERT_NE(event, nullptr);
2015
2016 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2017 ASSERT_NE(verified, nullptr);
2018 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2019
2020 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2021 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2022 EXPECT_EQ(motionArgs.source, verified->source);
2023 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2024
2025 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2026
2027 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2028 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2029 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2030 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2031 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2032 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2033 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2034}
2035
chaviw09c8d2d2020-08-24 15:48:26 -07002036/**
2037 * Ensure that separate calls to sign the same data are generating the same key.
2038 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2039 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2040 * tests.
2041 */
2042TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2043 KeyEvent event = getTestKeyEvent();
2044 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2045
2046 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2047 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2048 ASSERT_EQ(hmac1, hmac2);
2049}
2050
2051/**
2052 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2053 */
2054TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2055 KeyEvent event = getTestKeyEvent();
2056 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2057 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2058
2059 verifiedEvent.deviceId += 1;
2060 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2061
2062 verifiedEvent.source += 1;
2063 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2064
2065 verifiedEvent.eventTimeNanos += 1;
2066 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2067
2068 verifiedEvent.displayId += 1;
2069 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2070
2071 verifiedEvent.action += 1;
2072 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2073
2074 verifiedEvent.downTimeNanos += 1;
2075 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2076
2077 verifiedEvent.flags += 1;
2078 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2079
2080 verifiedEvent.keyCode += 1;
2081 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2082
2083 verifiedEvent.scanCode += 1;
2084 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2085
2086 verifiedEvent.metaState += 1;
2087 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2088
2089 verifiedEvent.repeatCount += 1;
2090 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2091}
2092
Vishnu Nair958da932020-08-21 17:12:37 -07002093TEST_F(InputDispatcherTest, SetFocusedWindow) {
2094 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2095 sp<FakeWindowHandle> windowTop =
2096 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2097 sp<FakeWindowHandle> windowSecond =
2098 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2099 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2100
2101 // Top window is also focusable but is not granted focus.
2102 windowTop->setFocusable(true);
2103 windowSecond->setFocusable(true);
2104 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2105 setFocusedWindow(windowSecond);
2106
2107 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2109 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002110
2111 // Focused window should receive event.
2112 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2113 windowTop->assertNoEvents();
2114}
2115
2116TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2117 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2118 sp<FakeWindowHandle> window =
2119 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2120 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2121
2122 window->setFocusable(true);
2123 // Release channel for window is no longer valid.
2124 window->releaseChannel();
2125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2126 setFocusedWindow(window);
2127
2128 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002129 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2130 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002131
2132 // window channel is invalid, so it should not receive any input event.
2133 window->assertNoEvents();
2134}
2135
2136TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2137 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2138 sp<FakeWindowHandle> window =
2139 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2140 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2141
2142 // Window is not focusable.
2143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2144 setFocusedWindow(window);
2145
2146 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002147 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2148 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002149
2150 // window is invalid, so it should not receive any input event.
2151 window->assertNoEvents();
2152}
2153
2154TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2155 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2156 sp<FakeWindowHandle> windowTop =
2157 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2158 sp<FakeWindowHandle> windowSecond =
2159 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2160 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2161
2162 windowTop->setFocusable(true);
2163 windowSecond->setFocusable(true);
2164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2165 setFocusedWindow(windowTop);
2166 windowTop->consumeFocusEvent(true);
2167
2168 setFocusedWindow(windowSecond, windowTop);
2169 windowSecond->consumeFocusEvent(true);
2170 windowTop->consumeFocusEvent(false);
2171
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002172 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2173 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002174
2175 // Focused window should receive event.
2176 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2177}
2178
2179TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2180 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2181 sp<FakeWindowHandle> windowTop =
2182 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2183 sp<FakeWindowHandle> windowSecond =
2184 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2185 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2186
2187 windowTop->setFocusable(true);
2188 windowSecond->setFocusable(true);
2189 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2190 setFocusedWindow(windowSecond, windowTop);
2191
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002192 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2193 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002194
2195 // Event should be dropped.
2196 windowTop->assertNoEvents();
2197 windowSecond->assertNoEvents();
2198}
2199
2200TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2201 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2202 sp<FakeWindowHandle> window =
2203 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2204 sp<FakeWindowHandle> previousFocusedWindow =
2205 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2206 ADISPLAY_ID_DEFAULT);
2207 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2208
2209 window->setFocusable(true);
2210 previousFocusedWindow->setFocusable(true);
2211 window->setVisible(false);
2212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2213 setFocusedWindow(previousFocusedWindow);
2214 previousFocusedWindow->consumeFocusEvent(true);
2215
2216 // Requesting focus on invisible window takes focus from currently focused window.
2217 setFocusedWindow(window);
2218 previousFocusedWindow->consumeFocusEvent(false);
2219
2220 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002221 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002222 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002223 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002224
2225 // Window does not get focus event or key down.
2226 window->assertNoEvents();
2227
2228 // Window becomes visible.
2229 window->setVisible(true);
2230 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2231
2232 // Window receives focus event.
2233 window->consumeFocusEvent(true);
2234 // Focused window receives key down.
2235 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2236}
2237
Garfield Tan1c7bc862020-01-28 13:24:04 -08002238class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2239protected:
2240 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2241 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2242
Chris Yea209fde2020-07-22 13:54:51 -07002243 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002244 sp<FakeWindowHandle> mWindow;
2245
2246 virtual void SetUp() override {
2247 mFakePolicy = new FakeInputDispatcherPolicy();
2248 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2249 mDispatcher = new InputDispatcher(mFakePolicy);
2250 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2251 ASSERT_EQ(OK, mDispatcher->start());
2252
2253 setUpWindow();
2254 }
2255
2256 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002257 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002258 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2259
Vishnu Nair47074b82020-08-14 11:54:47 -07002260 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002261 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002262 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002263 mWindow->consumeFocusEvent(true);
2264 }
2265
Chris Ye2ad95392020-09-01 13:44:44 -07002266 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002267 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002268 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002269 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2270 mDispatcher->notifyKey(&keyArgs);
2271
2272 // Window should receive key down event.
2273 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2274 }
2275
2276 void expectKeyRepeatOnce(int32_t repeatCount) {
2277 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2278 InputEvent* repeatEvent = mWindow->consume();
2279 ASSERT_NE(nullptr, repeatEvent);
2280
2281 uint32_t eventType = repeatEvent->getType();
2282 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2283
2284 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2285 uint32_t eventAction = repeatKeyEvent->getAction();
2286 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2287 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2288 }
2289
Chris Ye2ad95392020-09-01 13:44:44 -07002290 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002291 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002292 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002293 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2294 mDispatcher->notifyKey(&keyArgs);
2295
2296 // Window should receive key down event.
2297 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2298 0 /*expectedFlags*/);
2299 }
2300};
2301
2302TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002303 sendAndConsumeKeyDown(1 /* deviceId */);
2304 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2305 expectKeyRepeatOnce(repeatCount);
2306 }
2307}
2308
2309TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2310 sendAndConsumeKeyDown(1 /* deviceId */);
2311 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2312 expectKeyRepeatOnce(repeatCount);
2313 }
2314 sendAndConsumeKeyDown(2 /* deviceId */);
2315 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002316 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2317 expectKeyRepeatOnce(repeatCount);
2318 }
2319}
2320
2321TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002322 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002323 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002324 sendAndConsumeKeyUp(1 /* deviceId */);
2325 mWindow->assertNoEvents();
2326}
2327
2328TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2329 sendAndConsumeKeyDown(1 /* deviceId */);
2330 expectKeyRepeatOnce(1 /*repeatCount*/);
2331 sendAndConsumeKeyDown(2 /* deviceId */);
2332 expectKeyRepeatOnce(1 /*repeatCount*/);
2333 // Stale key up from device 1.
2334 sendAndConsumeKeyUp(1 /* deviceId */);
2335 // Device 2 is still down, keep repeating
2336 expectKeyRepeatOnce(2 /*repeatCount*/);
2337 expectKeyRepeatOnce(3 /*repeatCount*/);
2338 // Device 2 key up
2339 sendAndConsumeKeyUp(2 /* deviceId */);
2340 mWindow->assertNoEvents();
2341}
2342
2343TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2344 sendAndConsumeKeyDown(1 /* deviceId */);
2345 expectKeyRepeatOnce(1 /*repeatCount*/);
2346 sendAndConsumeKeyDown(2 /* deviceId */);
2347 expectKeyRepeatOnce(1 /*repeatCount*/);
2348 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2349 sendAndConsumeKeyUp(2 /* deviceId */);
2350 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002351 mWindow->assertNoEvents();
2352}
2353
2354TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002355 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002356 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2357 InputEvent* repeatEvent = mWindow->consume();
2358 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2359 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2360 IdGenerator::getSource(repeatEvent->getId()));
2361 }
2362}
2363
2364TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002365 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002366
2367 std::unordered_set<int32_t> idSet;
2368 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2369 InputEvent* repeatEvent = mWindow->consume();
2370 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2371 int32_t id = repeatEvent->getId();
2372 EXPECT_EQ(idSet.end(), idSet.find(id));
2373 idSet.insert(id);
2374 }
2375}
2376
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002377/* Test InputDispatcher for MultiDisplay */
2378class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2379public:
2380 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002381 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002382 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002383
Chris Yea209fde2020-07-22 13:54:51 -07002384 application1 = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002385 windowInPrimary = new FakeWindowHandle(application1, mDispatcher, "D_1",
2386 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002387
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002388 // Set focus window for primary display, but focused display would be second one.
2389 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002390 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002392 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002393 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002394
Chris Yea209fde2020-07-22 13:54:51 -07002395 application2 = std::make_shared<FakeApplicationHandle>();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002396 windowInSecondary = new FakeWindowHandle(application2, mDispatcher, "D_2",
2397 SECOND_DISPLAY_ID);
2398 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002399 // Set focus display to second one.
2400 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2401 // Set focus window for second display.
2402 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002403 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002404 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002405 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002406 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002407 }
2408
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002409 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002410 InputDispatcherTest::TearDown();
2411
Chris Yea209fde2020-07-22 13:54:51 -07002412 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002413 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002414 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002415 windowInSecondary.clear();
2416 }
2417
2418protected:
Chris Yea209fde2020-07-22 13:54:51 -07002419 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002420 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002421 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002422 sp<FakeWindowHandle> windowInSecondary;
2423};
2424
2425TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2426 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2428 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002430 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002431 windowInSecondary->assertNoEvents();
2432
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002433 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002434 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2435 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2436 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002437 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002438 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002439}
2440
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002441TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002442 // Test inject a key down with display id specified.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002443 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2444 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002445 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002446 windowInSecondary->assertNoEvents();
2447
2448 // Test inject a key down without display id specified.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2450 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002451 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002452 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002453
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002454 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002455 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002456
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002457 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002458 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2459 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002460
2461 // Test inject a key down, should timeout because of no target window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002462 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2463 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08002464 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002465 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002466 windowInSecondary->assertNoEvents();
2467}
2468
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002469// Test per-display input monitors for motion event.
2470TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002471 FakeMonitorReceiver monitorInPrimary =
2472 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2473 FakeMonitorReceiver monitorInSecondary =
2474 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002475
2476 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2478 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2479 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002480 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002481 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002482 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002483 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002484
2485 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2487 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2488 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002489 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002490 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002491 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08002492 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002493
2494 // Test inject a non-pointer motion event.
2495 // If specific a display, it will dispatch to the focused window of particular display,
2496 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002497 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2498 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
2499 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002500 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002501 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002502 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002503 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002504}
2505
2506// Test per-display input monitors for key event.
2507TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
2508 //Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08002509 FakeMonitorReceiver monitorInPrimary =
2510 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2511 FakeMonitorReceiver monitorInSecondary =
2512 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002513
2514 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2516 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002517 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002518 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002519 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002520 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002521}
2522
Vishnu Nair958da932020-08-21 17:12:37 -07002523TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
2524 sp<FakeWindowHandle> secondWindowInPrimary =
2525 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2526 secondWindowInPrimary->setFocusable(true);
2527 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
2528 setFocusedWindow(secondWindowInPrimary);
2529 windowInPrimary->consumeFocusEvent(false);
2530 secondWindowInPrimary->consumeFocusEvent(true);
2531
2532 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2534 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002535 windowInPrimary->assertNoEvents();
2536 windowInSecondary->assertNoEvents();
2537 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2538}
2539
Jackal Guof9696682018-10-05 12:23:23 +08002540class InputFilterTest : public InputDispatcherTest {
2541protected:
2542 static constexpr int32_t SECOND_DISPLAY_ID = 1;
2543
2544 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
2545 NotifyMotionArgs motionArgs;
2546
2547 motionArgs = generateMotionArgs(
2548 AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
2549 mDispatcher->notifyMotion(&motionArgs);
2550 motionArgs = generateMotionArgs(
2551 AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
2552 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002553 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002554 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002555 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002556 } else {
2557 mFakePolicy->assertFilterInputEventWasNotCalled();
2558 }
2559 }
2560
2561 void testNotifyKey(bool expectToBeFiltered) {
2562 NotifyKeyArgs keyArgs;
2563
2564 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2565 mDispatcher->notifyKey(&keyArgs);
2566 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
2567 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002568 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002569
2570 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002571 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002572 } else {
2573 mFakePolicy->assertFilterInputEventWasNotCalled();
2574 }
2575 }
2576};
2577
2578// Test InputFilter for MotionEvent
2579TEST_F(InputFilterTest, MotionEvent_InputFilter) {
2580 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
2581 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2582 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2583
2584 // Enable InputFilter
2585 mDispatcher->setInputFilterEnabled(true);
2586 // Test touch on both primary and second display, and check if both events are filtered.
2587 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
2588 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
2589
2590 // Disable InputFilter
2591 mDispatcher->setInputFilterEnabled(false);
2592 // Test touch on both primary and second display, and check if both events aren't filtered.
2593 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2594 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2595}
2596
2597// Test InputFilter for KeyEvent
2598TEST_F(InputFilterTest, KeyEvent_InputFilter) {
2599 // Since the InputFilter is disabled by default, check if key event aren't filtered.
2600 testNotifyKey(/*expectToBeFiltered*/ false);
2601
2602 // Enable InputFilter
2603 mDispatcher->setInputFilterEnabled(true);
2604 // Send a key event, and check if it is filtered.
2605 testNotifyKey(/*expectToBeFiltered*/ true);
2606
2607 // Disable InputFilter
2608 mDispatcher->setInputFilterEnabled(false);
2609 // Send a key event, and check if it isn't filtered.
2610 testNotifyKey(/*expectToBeFiltered*/ false);
2611}
2612
chaviwfd6d3512019-03-25 13:23:49 -07002613class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002614 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07002615 InputDispatcherTest::SetUp();
2616
Chris Yea209fde2020-07-22 13:54:51 -07002617 std::shared_ptr<FakeApplicationHandle> application =
2618 std::make_shared<FakeApplicationHandle>();
chaviwfd6d3512019-03-25 13:23:49 -07002619 mUnfocusedWindow = new FakeWindowHandle(application, mDispatcher, "Top",
2620 ADISPLAY_ID_DEFAULT);
2621 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
2622 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2623 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002624 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002625
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002626 mFocusedWindow =
2627 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2628 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01002629 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002630
2631 // Set focused application.
2632 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002633 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07002634
2635 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002637 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002638 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07002639 }
2640
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002641 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07002642 InputDispatcherTest::TearDown();
2643
2644 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002645 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07002646 }
2647
2648protected:
2649 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002650 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002651 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07002652};
2653
2654// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2655// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
2656// the onPointerDownOutsideFocus callback.
2657TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002659 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2660 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002662 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002663
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002664 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07002665 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
2666}
2667
2668// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
2669// DOWN on the window that doesn't have focus. Ensure no window received the
2670// onPointerDownOutsideFocus callback.
2671TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002673 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002675 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002676
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002677 ASSERT_TRUE(mDispatcher->waitForIdle());
2678 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002679}
2680
2681// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
2682// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
2683TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2685 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002686 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002687
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002688 ASSERT_TRUE(mDispatcher->waitForIdle());
2689 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002690}
2691
2692// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2693// DOWN on the window that already has focus. Ensure no window received the
2694// onPointerDownOutsideFocus callback.
2695TEST_F(InputDispatcherOnPointerDownOutsideFocus,
2696 OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002698 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002699 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002700 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002701 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002702
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002703 ASSERT_TRUE(mDispatcher->waitForIdle());
2704 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002705}
2706
chaviwaf87b3e2019-10-01 16:59:28 -07002707// These tests ensures we can send touch events to a single client when there are multiple input
2708// windows that point to the same client token.
2709class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
2710 virtual void SetUp() override {
2711 InputDispatcherTest::SetUp();
2712
Chris Yea209fde2020-07-22 13:54:51 -07002713 std::shared_ptr<FakeApplicationHandle> application =
2714 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07002715 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
2716 ADISPLAY_ID_DEFAULT);
2717 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
2718 // 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 +01002719 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2720 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002721 mWindow1->setFrame(Rect(0, 0, 100, 100));
2722
2723 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
2724 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01002725 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2726 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07002727 mWindow2->setFrame(Rect(100, 100, 200, 200));
2728
Arthur Hung72d8dc32020-03-28 00:48:39 +00002729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07002730 }
2731
2732protected:
2733 sp<FakeWindowHandle> mWindow1;
2734 sp<FakeWindowHandle> mWindow2;
2735
2736 // Helper function to convert the point from screen coordinates into the window's space
2737 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07002738 vec2 vals = windowInfo->transform.transform(point.x, point.y);
2739 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07002740 }
2741
2742 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
2743 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002744 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07002745 InputEvent* event = window->consume();
2746
2747 ASSERT_NE(nullptr, event) << name.c_str()
2748 << ": consumer should have returned non-NULL event.";
2749
2750 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2751 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2752 << " event, got " << inputEventTypeToString(event->getType()) << " event";
2753
2754 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2755 EXPECT_EQ(expectedAction, motionEvent.getAction());
2756
2757 for (size_t i = 0; i < points.size(); i++) {
2758 float expectedX = points[i].x;
2759 float expectedY = points[i].y;
2760
2761 EXPECT_EQ(expectedX, motionEvent.getX(i))
2762 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
2763 << ", got " << motionEvent.getX(i);
2764 EXPECT_EQ(expectedY, motionEvent.getY(i))
2765 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
2766 << ", got " << motionEvent.getY(i);
2767 }
2768 }
chaviw9eaa22c2020-07-01 16:21:27 -07002769
2770 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
2771 std::vector<PointF> expectedPoints) {
2772 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
2773 ADISPLAY_ID_DEFAULT, touchedPoints);
2774 mDispatcher->notifyMotion(&motionArgs);
2775
2776 // Always consume from window1 since it's the window that has the InputReceiver
2777 consumeMotionEvent(mWindow1, action, expectedPoints);
2778 }
chaviwaf87b3e2019-10-01 16:59:28 -07002779};
2780
2781TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
2782 // Touch Window 1
2783 PointF touchedPoint = {10, 10};
2784 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002785 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002786
2787 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07002788 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002789
2790 // Touch Window 2
2791 touchedPoint = {150, 150};
2792 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002793 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002794}
2795
chaviw9eaa22c2020-07-01 16:21:27 -07002796TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
2797 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07002798 mWindow2->setWindowScale(0.5f, 0.5f);
2799
2800 // Touch Window 1
2801 PointF touchedPoint = {10, 10};
2802 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002803 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002804 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07002805 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002806
2807 // Touch Window 2
2808 touchedPoint = {150, 150};
2809 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07002810 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
2811 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002812
chaviw9eaa22c2020-07-01 16:21:27 -07002813 // Update the transform so rotation is set
2814 mWindow2->setWindowTransform(0, -1, 1, 0);
2815 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
2816 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07002817}
2818
chaviw9eaa22c2020-07-01 16:21:27 -07002819TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002820 mWindow2->setWindowScale(0.5f, 0.5f);
2821
2822 // Touch Window 1
2823 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2824 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002825 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002826
2827 // Touch Window 2
2828 int32_t actionPointerDown =
2829 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002830 touchedPoints.push_back(PointF{150, 150});
2831 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2832 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002833
chaviw9eaa22c2020-07-01 16:21:27 -07002834 // Release Window 2
2835 int32_t actionPointerUp =
2836 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2837 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
2838 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002839
chaviw9eaa22c2020-07-01 16:21:27 -07002840 // Update the transform so rotation is set for Window 2
2841 mWindow2->setWindowTransform(0, -1, 1, 0);
2842 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2843 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002844}
2845
chaviw9eaa22c2020-07-01 16:21:27 -07002846TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002847 mWindow2->setWindowScale(0.5f, 0.5f);
2848
2849 // Touch Window 1
2850 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2851 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002852 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002853
2854 // Touch Window 2
2855 int32_t actionPointerDown =
2856 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002857 touchedPoints.push_back(PointF{150, 150});
2858 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002859
chaviw9eaa22c2020-07-01 16:21:27 -07002860 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002861
2862 // Move both windows
2863 touchedPoints = {{20, 20}, {175, 175}};
2864 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2865 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2866
chaviw9eaa22c2020-07-01 16:21:27 -07002867 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002868
chaviw9eaa22c2020-07-01 16:21:27 -07002869 // Release Window 2
2870 int32_t actionPointerUp =
2871 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2872 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
2873 expectedPoints.pop_back();
2874
2875 // Touch Window 2
2876 mWindow2->setWindowTransform(0, -1, 1, 0);
2877 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
2878 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
2879
2880 // Move both windows
2881 touchedPoints = {{20, 20}, {175, 175}};
2882 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2883 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2884
2885 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002886}
2887
2888TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
2889 mWindow1->setWindowScale(0.5f, 0.5f);
2890
2891 // Touch Window 1
2892 std::vector<PointF> touchedPoints = {PointF{10, 10}};
2893 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07002894 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002895
2896 // Touch Window 2
2897 int32_t actionPointerDown =
2898 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07002899 touchedPoints.push_back(PointF{150, 150});
2900 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002901
chaviw9eaa22c2020-07-01 16:21:27 -07002902 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002903
2904 // Move both windows
2905 touchedPoints = {{20, 20}, {175, 175}};
2906 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
2907 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
2908
chaviw9eaa22c2020-07-01 16:21:27 -07002909 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00002910}
2911
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002912class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
2913 virtual void SetUp() override {
2914 InputDispatcherTest::SetUp();
2915
Chris Yea209fde2020-07-22 13:54:51 -07002916 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002917 mApplication->setDispatchingTimeout(20ms);
2918 mWindow =
2919 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2920 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05002921 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07002922 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002923 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2924 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002925 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002926
2927 // Set focused application.
2928 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
2929
2930 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002931 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002932 mWindow->consumeFocusEvent(true);
2933 }
2934
2935 virtual void TearDown() override {
2936 InputDispatcherTest::TearDown();
2937 mWindow.clear();
2938 }
2939
2940protected:
Chris Yea209fde2020-07-22 13:54:51 -07002941 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002942 sp<FakeWindowHandle> mWindow;
2943 static constexpr PointF WINDOW_LOCATION = {20, 20};
2944
2945 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002947 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2948 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002949 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002950 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2951 WINDOW_LOCATION));
2952 }
2953};
2954
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002955// Send a tap and respond, which should not cause an ANR.
2956TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
2957 tapOnWindow();
2958 mWindow->consumeMotionDown();
2959 mWindow->consumeMotionUp();
2960 ASSERT_TRUE(mDispatcher->waitForIdle());
2961 mFakePolicy->assertNotifyAnrWasNotCalled();
2962}
2963
2964// Send a regular key and respond, which should not cause an ANR.
2965TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002966 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002967 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
2968 ASSERT_TRUE(mDispatcher->waitForIdle());
2969 mFakePolicy->assertNotifyAnrWasNotCalled();
2970}
2971
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05002972TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
2973 mWindow->setFocusable(false);
2974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
2975 mWindow->consumeFocusEvent(false);
2976
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002977 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05002978 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002979 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
2980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05002981 // Key will not go to window because we have no focused window.
2982 // The 'no focused window' ANR timer should start instead.
2983
2984 // Now, the focused application goes away.
2985 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
2986 // The key should get dropped and there should be no ANR.
2987
2988 ASSERT_TRUE(mDispatcher->waitForIdle());
2989 mFakePolicy->assertNotifyAnrWasNotCalled();
2990}
2991
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002992// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002993// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
2994// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002995TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002997 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2998 WINDOW_LOCATION));
2999
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003000 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3001 ASSERT_TRUE(sequenceNum);
3002 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003003 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003004
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003005 mWindow->finishEvent(*sequenceNum);
3006 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3007 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003008 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003009 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003010}
3011
3012// Send a key to the app and have the app not respond right away.
3013TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3014 // Inject a key, and don't respond - expect that ANR is called.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003016 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3017 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003018 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003019 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003020 ASSERT_TRUE(mDispatcher->waitForIdle());
3021}
3022
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003023// We have a focused application, but no focused window
3024TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003025 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3027 mWindow->consumeFocusEvent(false);
3028
3029 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003030 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003031 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3032 WINDOW_LOCATION));
3033 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3034 mDispatcher->waitForIdle();
3035 mFakePolicy->assertNotifyAnrWasNotCalled();
3036
3037 // Once a focused event arrives, we get an ANR for this application
3038 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3039 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003040 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003041 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003042 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3043 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003044 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003045 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003046 ASSERT_TRUE(mDispatcher->waitForIdle());
3047}
3048
3049// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003050// Make sure that we don't notify policy twice about the same ANR.
3051TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003052 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3054 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003055
3056 // Once a focused event arrives, we get an ANR for this application
3057 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3058 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003059 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003060 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003061 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3062 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003063 const std::chrono::duration appTimeout =
3064 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003065 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003066
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003067 std::this_thread::sleep_for(appTimeout);
3068 // ANR should not be raised again. It is up to policy to do that if it desires.
3069 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003070
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003071 // If we now get a focused window, the ANR should stop, but the policy handles that via
3072 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003073 ASSERT_TRUE(mDispatcher->waitForIdle());
3074}
3075
3076// We have a focused application, but no focused window
3077TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003078 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003079 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3080 mWindow->consumeFocusEvent(false);
3081
3082 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003083 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003084 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003085 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3086 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003087
3088 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003089 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003090
3091 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003092 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003093 ASSERT_TRUE(mDispatcher->waitForIdle());
3094 mWindow->assertNoEvents();
3095}
3096
3097/**
3098 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3099 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3100 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3101 * the ANR mechanism should still work.
3102 *
3103 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3104 * DOWN event, while not responding on the second one.
3105 */
3106TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3107 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3108 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3109 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3110 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3111 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003112 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003113
3114 // Now send ACTION_UP, with identical timestamp
3115 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3116 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3117 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3118 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003119 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003120
3121 // We have now sent down and up. Let's consume first event and then ANR on the second.
3122 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3123 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003124 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003125}
3126
3127// If an app is not responding to a key event, gesture monitors should continue to receive
3128// new motion events
3129TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3130 FakeMonitorReceiver monitor =
3131 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3132 true /*isGestureMonitor*/);
3133
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3135 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003136 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003137 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003138
3139 // Stuck on the ACTION_UP
3140 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003141 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003142
3143 // New tap will go to the gesture monitor, but not to the window
3144 tapOnWindow();
3145 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3146 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3147
3148 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3149 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003150 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003151 mWindow->assertNoEvents();
3152 monitor.assertNoEvents();
3153}
3154
3155// If an app is not responding to a motion event, gesture monitors should continue to receive
3156// new motion events
3157TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3158 FakeMonitorReceiver monitor =
3159 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3160 true /*isGestureMonitor*/);
3161
3162 tapOnWindow();
3163 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3164 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3165
3166 mWindow->consumeMotionDown();
3167 // Stuck on the ACTION_UP
3168 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003169 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003170
3171 // New tap will go to the gesture monitor, but not to the window
3172 tapOnWindow();
3173 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3174 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3175
3176 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3177 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003178 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003179 mWindow->assertNoEvents();
3180 monitor.assertNoEvents();
3181}
3182
3183// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3184// process events, you don't get an anr. When the window later becomes unresponsive again, you
3185// get an ANR again.
3186// 1. tap -> block on ACTION_UP -> receive ANR
3187// 2. consume all pending events (= queue becomes healthy again)
3188// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3189TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3190 tapOnWindow();
3191
3192 mWindow->consumeMotionDown();
3193 // Block on ACTION_UP
3194 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003195 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003196 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3197 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003198 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003199 mWindow->assertNoEvents();
3200
3201 tapOnWindow();
3202 mWindow->consumeMotionDown();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003203 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003204 mWindow->consumeMotionUp();
3205
3206 mDispatcher->waitForIdle();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003207 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
3208 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003209 mWindow->assertNoEvents();
3210}
3211
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003212// If a connection remains unresponsive for a while, make sure policy is only notified once about
3213// it.
3214TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003215 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003216 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3217 WINDOW_LOCATION));
3218
3219 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003220 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003221 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003222 // 'notifyConnectionUnresponsive' should only be called once per connection
3223 mFakePolicy->assertNotifyAnrWasNotCalled();
3224 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003225 mWindow->consumeMotionDown();
3226 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3227 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3228 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003229 mDispatcher->waitForIdle();
3230 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mWindow->getToken());
3231 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003232}
3233
3234/**
3235 * If a window is processing a motion event, and then a key event comes in, the key event should
3236 * not to to the focused window until the motion is processed.
3237 *
3238 * Warning!!!
3239 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3240 * and the injection timeout that we specify when injecting the key.
3241 * We must have the injection timeout (10ms) be smaller than
3242 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3243 *
3244 * If that value changes, this test should also change.
3245 */
3246TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3247 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3248 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3249
3250 tapOnWindow();
3251 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3252 ASSERT_TRUE(downSequenceNum);
3253 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3254 ASSERT_TRUE(upSequenceNum);
3255 // Don't finish the events yet, and send a key
3256 // Injection will "succeed" because we will eventually give up and send the key to the focused
3257 // window even if motions are still being processed. But because the injection timeout is short,
3258 // we will receive INJECTION_TIMED_OUT as the result.
3259
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003260 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003261 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003262 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3263 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003264 // Key will not be sent to the window, yet, because the window is still processing events
3265 // and the key remains pending, waiting for the touch events to be processed
3266 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3267 ASSERT_FALSE(keySequenceNum);
3268
3269 std::this_thread::sleep_for(500ms);
3270 // if we wait long enough though, dispatcher will give up, and still send the key
3271 // to the focused window, even though we have not yet finished the motion event
3272 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3273 mWindow->finishEvent(*downSequenceNum);
3274 mWindow->finishEvent(*upSequenceNum);
3275}
3276
3277/**
3278 * If a window is processing a motion event, and then a key event comes in, the key event should
3279 * not go to the focused window until the motion is processed.
3280 * If then a new motion comes in, then the pending key event should be going to the currently
3281 * focused window right away.
3282 */
3283TEST_F(InputDispatcherSingleWindowAnr,
3284 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3285 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3286 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3287
3288 tapOnWindow();
3289 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3290 ASSERT_TRUE(downSequenceNum);
3291 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3292 ASSERT_TRUE(upSequenceNum);
3293 // Don't finish the events yet, and send a key
3294 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003295 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003296 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003297 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003298 // At this point, key is still pending, and should not be sent to the application yet.
3299 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3300 ASSERT_FALSE(keySequenceNum);
3301
3302 // Now tap down again. It should cause the pending key to go to the focused window right away.
3303 tapOnWindow();
3304 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3305 // the other events yet. We can finish events in any order.
3306 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3307 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3308 mWindow->consumeMotionDown();
3309 mWindow->consumeMotionUp();
3310 mWindow->assertNoEvents();
3311}
3312
3313class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3314 virtual void SetUp() override {
3315 InputDispatcherTest::SetUp();
3316
Chris Yea209fde2020-07-22 13:54:51 -07003317 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003318 mApplication->setDispatchingTimeout(10ms);
3319 mUnfocusedWindow =
3320 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3321 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3322 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3323 // window.
3324 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003325 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3326 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3327 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003328
3329 mFocusedWindow =
3330 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003331 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003332 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003333 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3334 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003335
3336 // Set focused application.
3337 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003338 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003339
3340 // Expect one focus window exist in display.
3341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003342 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003343 mFocusedWindow->consumeFocusEvent(true);
3344 }
3345
3346 virtual void TearDown() override {
3347 InputDispatcherTest::TearDown();
3348
3349 mUnfocusedWindow.clear();
3350 mFocusedWindow.clear();
3351 }
3352
3353protected:
Chris Yea209fde2020-07-22 13:54:51 -07003354 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003355 sp<FakeWindowHandle> mUnfocusedWindow;
3356 sp<FakeWindowHandle> mFocusedWindow;
3357 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3358 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3359 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3360
3361 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3362
3363 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3364
3365private:
3366 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003368 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3369 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003370 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003371 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3372 location));
3373 }
3374};
3375
3376// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3377// should be ANR'd first.
3378TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003380 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3381 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003382 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003383 mFocusedWindow->consumeMotionDown();
3384 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3385 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3386 // We consumed all events, so no ANR
3387 ASSERT_TRUE(mDispatcher->waitForIdle());
3388 mFakePolicy->assertNotifyAnrWasNotCalled();
3389
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003390 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003391 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3392 FOCUSED_WINDOW_LOCATION));
3393 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
3394 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003395
3396 const std::chrono::duration timeout =
3397 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003398 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
3399 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
3400 // sequence to make it consistent
3401 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003402 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003403 mFocusedWindow->consumeMotionDown();
3404 // This cancel is generated because the connection was unresponsive
3405 mFocusedWindow->consumeMotionCancel();
3406 mFocusedWindow->assertNoEvents();
3407 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003408 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003409 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
3410 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003411}
3412
3413// If we have 2 windows with identical timeouts that are both unresponsive,
3414// it doesn't matter which order they should have ANR.
3415// But we should receive ANR for both.
3416TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
3417 // Set the timeout for unfocused window to match the focused window
3418 mUnfocusedWindow->setDispatchingTimeout(10ms);
3419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3420
3421 tapOnFocusedWindow();
3422 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003423 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveConnectionToken(10ms);
3424 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveConnectionToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003425
3426 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003427 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
3428 mFocusedWindow->getToken() == anrConnectionToken2);
3429 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
3430 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003431
3432 ASSERT_TRUE(mDispatcher->waitForIdle());
3433 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003434
3435 mFocusedWindow->consumeMotionDown();
3436 mFocusedWindow->consumeMotionUp();
3437 mUnfocusedWindow->consumeMotionOutside();
3438
3439 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveConnectionToken();
3440 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveConnectionToken();
3441
3442 // Both applications should be marked as responsive, in any order
3443 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
3444 mFocusedWindow->getToken() == responsiveToken2);
3445 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
3446 mUnfocusedWindow->getToken() == responsiveToken2);
3447 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003448}
3449
3450// If a window is already not responding, the second tap on the same window should be ignored.
3451// We should also log an error to account for the dropped event (not tested here).
3452// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
3453TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
3454 tapOnFocusedWindow();
3455 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3456 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3457 // Receive the events, but don't respond
3458 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
3459 ASSERT_TRUE(downEventSequenceNum);
3460 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
3461 ASSERT_TRUE(upEventSequenceNum);
3462 const std::chrono::duration timeout =
3463 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003464 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003465
3466 // Tap once again
3467 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003468 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003469 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3470 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003471 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003472 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3473 FOCUSED_WINDOW_LOCATION));
3474 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
3475 // valid touch target
3476 mUnfocusedWindow->assertNoEvents();
3477
3478 // Consume the first tap
3479 mFocusedWindow->finishEvent(*downEventSequenceNum);
3480 mFocusedWindow->finishEvent(*upEventSequenceNum);
3481 ASSERT_TRUE(mDispatcher->waitForIdle());
3482 // The second tap did not go to the focused window
3483 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003484 // Since all events are finished, connection should be deemed healthy again
3485 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003486 mFakePolicy->assertNotifyAnrWasNotCalled();
3487}
3488
3489// If you tap outside of all windows, there will not be ANR
3490TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003491 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003492 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3493 LOCATION_OUTSIDE_ALL_WINDOWS));
3494 ASSERT_TRUE(mDispatcher->waitForIdle());
3495 mFakePolicy->assertNotifyAnrWasNotCalled();
3496}
3497
3498// Since the focused window is paused, tapping on it should not produce any events
3499TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
3500 mFocusedWindow->setPaused(true);
3501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3502
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003503 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003504 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3505 FOCUSED_WINDOW_LOCATION));
3506
3507 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
3508 ASSERT_TRUE(mDispatcher->waitForIdle());
3509 // Should not ANR because the window is paused, and touches shouldn't go to it
3510 mFakePolicy->assertNotifyAnrWasNotCalled();
3511
3512 mFocusedWindow->assertNoEvents();
3513 mUnfocusedWindow->assertNoEvents();
3514}
3515
3516/**
3517 * If a window is processing a motion event, and then a key event comes in, the key event should
3518 * not to to the focused window until the motion is processed.
3519 * If a different window becomes focused at this time, the key should go to that window instead.
3520 *
3521 * Warning!!!
3522 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3523 * and the injection timeout that we specify when injecting the key.
3524 * We must have the injection timeout (10ms) be smaller than
3525 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3526 *
3527 * If that value changes, this test should also change.
3528 */
3529TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
3530 // Set a long ANR timeout to prevent it from triggering
3531 mFocusedWindow->setDispatchingTimeout(2s);
3532 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3533
3534 tapOnUnfocusedWindow();
3535 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
3536 ASSERT_TRUE(downSequenceNum);
3537 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
3538 ASSERT_TRUE(upSequenceNum);
3539 // Don't finish the events yet, and send a key
3540 // Injection will succeed because we will eventually give up and send the key to the focused
3541 // window even if motions are still being processed.
3542
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003543 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003544 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003545 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003547 // Key will not be sent to the window, yet, because the window is still processing events
3548 // and the key remains pending, waiting for the touch events to be processed
3549 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
3550 ASSERT_FALSE(keySequenceNum);
3551
3552 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07003553 mFocusedWindow->setFocusable(false);
3554 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003556 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003557
3558 // Focus events should precede the key events
3559 mUnfocusedWindow->consumeFocusEvent(true);
3560 mFocusedWindow->consumeFocusEvent(false);
3561
3562 // Finish the tap events, which should unblock dispatcher
3563 mUnfocusedWindow->finishEvent(*downSequenceNum);
3564 mUnfocusedWindow->finishEvent(*upSequenceNum);
3565
3566 // Now that all queues are cleared and no backlog in the connections, the key event
3567 // can finally go to the newly focused "mUnfocusedWindow".
3568 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3569 mFocusedWindow->assertNoEvents();
3570 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003571 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003572}
3573
3574// When the touch stream is split across 2 windows, and one of them does not respond,
3575// then ANR should be raised and the touch should be canceled for the unresponsive window.
3576// The other window should not be affected by that.
3577TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
3578 // Touch Window 1
3579 NotifyMotionArgs motionArgs =
3580 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3581 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
3582 mDispatcher->notifyMotion(&motionArgs);
3583 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3584 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3585
3586 // Touch Window 2
3587 int32_t actionPointerDown =
3588 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3589
3590 motionArgs =
3591 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3592 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
3593 mDispatcher->notifyMotion(&motionArgs);
3594
3595 const std::chrono::duration timeout =
3596 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003597 mFakePolicy->assertNotifyConnectionUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003598
3599 mUnfocusedWindow->consumeMotionDown();
3600 mFocusedWindow->consumeMotionDown();
3601 // Focused window may or may not receive ACTION_MOVE
3602 // But it should definitely receive ACTION_CANCEL due to the ANR
3603 InputEvent* event;
3604 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
3605 ASSERT_TRUE(moveOrCancelSequenceNum);
3606 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
3607 ASSERT_NE(nullptr, event);
3608 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
3609 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
3610 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
3611 mFocusedWindow->consumeMotionCancel();
3612 } else {
3613 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
3614 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003615 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003616 mFakePolicy->assertNotifyConnectionResponsiveWasCalled(mFocusedWindow->getToken());
3617
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003618 mUnfocusedWindow->assertNoEvents();
3619 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003620 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003621}
3622
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003623/**
3624 * If we have no focused window, and a key comes in, we start the ANR timer.
3625 * The focused application should add a focused window before the timer runs out to prevent ANR.
3626 *
3627 * If the user touches another application during this time, the key should be dropped.
3628 * Next, if a new focused window comes in, without toggling the focused application,
3629 * then no ANR should occur.
3630 *
3631 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
3632 * but in some cases the policy may not update the focused application.
3633 */
3634TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
3635 std::shared_ptr<FakeApplicationHandle> focusedApplication =
3636 std::make_shared<FakeApplicationHandle>();
3637 focusedApplication->setDispatchingTimeout(60ms);
3638 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
3639 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
3640 mFocusedWindow->setFocusable(false);
3641
3642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3643 mFocusedWindow->consumeFocusEvent(false);
3644
3645 // Send a key. The ANR timer should start because there is no focused window.
3646 // 'focusedApplication' will get blamed if this timer completes.
3647 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003648 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003649 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003650 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003652
3653 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
3654 // then the injected touches won't cause the focused event to get dropped.
3655 // The dispatcher only checks for whether the queue should be pruned upon queueing.
3656 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
3657 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
3658 // For this test, it means that the key would get delivered to the window once it becomes
3659 // focused.
3660 std::this_thread::sleep_for(10ms);
3661
3662 // Touch unfocused window. This should force the pending key to get dropped.
3663 NotifyMotionArgs motionArgs =
3664 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3665 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
3666 mDispatcher->notifyMotion(&motionArgs);
3667
3668 // We do not consume the motion right away, because that would require dispatcher to first
3669 // process (== drop) the key event, and by that time, ANR will be raised.
3670 // Set the focused window first.
3671 mFocusedWindow->setFocusable(true);
3672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3673 setFocusedWindow(mFocusedWindow);
3674 mFocusedWindow->consumeFocusEvent(true);
3675 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
3676 // to another application. This could be a bug / behaviour in the policy.
3677
3678 mUnfocusedWindow->consumeMotionDown();
3679
3680 ASSERT_TRUE(mDispatcher->waitForIdle());
3681 // Should not ANR because we actually have a focused window. It was just added too slowly.
3682 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
3683}
3684
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05003685// These tests ensure we cannot send touch events to a window that's positioned behind a window
3686// that has feature NO_INPUT_CHANNEL.
3687// Layout:
3688// Top (closest to user)
3689// mNoInputWindow (above all windows)
3690// mBottomWindow
3691// Bottom (furthest from user)
3692class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
3693 virtual void SetUp() override {
3694 InputDispatcherTest::SetUp();
3695
3696 mApplication = std::make_shared<FakeApplicationHandle>();
3697 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
3698 "Window without input channel", ADISPLAY_ID_DEFAULT,
3699 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
3700
3701 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3702 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
3703 // It's perfectly valid for this window to not have an associated input channel
3704
3705 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
3706 ADISPLAY_ID_DEFAULT);
3707 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
3708
3709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
3710 }
3711
3712protected:
3713 std::shared_ptr<FakeApplicationHandle> mApplication;
3714 sp<FakeWindowHandle> mNoInputWindow;
3715 sp<FakeWindowHandle> mBottomWindow;
3716};
3717
3718TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
3719 PointF touchedPoint = {10, 10};
3720
3721 NotifyMotionArgs motionArgs =
3722 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3723 ADISPLAY_ID_DEFAULT, {touchedPoint});
3724 mDispatcher->notifyMotion(&motionArgs);
3725
3726 mNoInputWindow->assertNoEvents();
3727 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
3728 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
3729 // and therefore should prevent mBottomWindow from receiving touches
3730 mBottomWindow->assertNoEvents();
3731}
3732
3733/**
3734 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
3735 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
3736 */
3737TEST_F(InputDispatcherMultiWindowOcclusionTests,
3738 NoInputChannelFeature_DropsTouchesWithValidChannel) {
3739 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
3740 "Window with input channel and NO_INPUT_CHANNEL",
3741 ADISPLAY_ID_DEFAULT);
3742
3743 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
3744 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
3745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
3746
3747 PointF touchedPoint = {10, 10};
3748
3749 NotifyMotionArgs motionArgs =
3750 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3751 ADISPLAY_ID_DEFAULT, {touchedPoint});
3752 mDispatcher->notifyMotion(&motionArgs);
3753
3754 mNoInputWindow->assertNoEvents();
3755 mBottomWindow->assertNoEvents();
3756}
3757
Vishnu Nair958da932020-08-21 17:12:37 -07003758class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
3759protected:
3760 std::shared_ptr<FakeApplicationHandle> mApp;
3761 sp<FakeWindowHandle> mWindow;
3762 sp<FakeWindowHandle> mMirror;
3763
3764 virtual void SetUp() override {
3765 InputDispatcherTest::SetUp();
3766 mApp = std::make_shared<FakeApplicationHandle>();
3767 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3768 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
3769 mWindow->getToken());
3770 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
3771 mWindow->setFocusable(true);
3772 mMirror->setFocusable(true);
3773 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3774 }
3775};
3776
3777TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
3778 // Request focus on a mirrored window
3779 setFocusedWindow(mMirror);
3780
3781 // window gets focused
3782 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003783 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3784 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003785 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3786}
3787
3788// A focused & mirrored window remains focused only if the window and its mirror are both
3789// focusable.
3790TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
3791 setFocusedWindow(mMirror);
3792
3793 // window gets focused
3794 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003795 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3796 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003797 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3799 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003800 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3801
3802 mMirror->setFocusable(false);
3803 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3804
3805 // window loses focus since one of the windows associated with the token in not focusable
3806 mWindow->consumeFocusEvent(false);
3807
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003808 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3809 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003810 mWindow->assertNoEvents();
3811}
3812
3813// A focused & mirrored window remains focused until the window and its mirror both become
3814// invisible.
3815TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
3816 setFocusedWindow(mMirror);
3817
3818 // window gets focused
3819 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003820 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3821 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003822 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3824 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003825 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3826
3827 mMirror->setVisible(false);
3828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3829
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3831 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003832 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3834 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003835 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3836
3837 mWindow->setVisible(false);
3838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3839
3840 // window loses focus only after all windows associated with the token become invisible.
3841 mWindow->consumeFocusEvent(false);
3842
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003843 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3844 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003845 mWindow->assertNoEvents();
3846}
3847
3848// A focused & mirrored window remains focused until both windows are removed.
3849TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
3850 setFocusedWindow(mMirror);
3851
3852 // window gets focused
3853 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003854 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3855 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003856 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3858 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003859 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3860
3861 // single window is removed but the window token remains focused
3862 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
3863
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003864 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3865 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003866 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003867 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
3868 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003869 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
3870
3871 // Both windows are removed
3872 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3873 mWindow->consumeFocusEvent(false);
3874
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003875 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3876 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003877 mWindow->assertNoEvents();
3878}
3879
3880// Focus request can be pending until one window becomes visible.
3881TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
3882 // Request focus on an invisible mirror.
3883 mWindow->setVisible(false);
3884 mMirror->setVisible(false);
3885 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3886 setFocusedWindow(mMirror);
3887
3888 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003889 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003890 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003891 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003892
3893 mMirror->setVisible(true);
3894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
3895
3896 // window gets focused
3897 mWindow->consumeFocusEvent(true);
3898 // window gets the pending key event
3899 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3900}
Prabir Pradhan99987712020-11-10 18:43:05 -08003901
3902class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
3903protected:
3904 std::shared_ptr<FakeApplicationHandle> mApp;
3905 sp<FakeWindowHandle> mWindow;
3906 sp<FakeWindowHandle> mSecondWindow;
3907
3908 void SetUp() override {
3909 InputDispatcherTest::SetUp();
3910 mApp = std::make_shared<FakeApplicationHandle>();
3911 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3912 mWindow->setFocusable(true);
3913 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
3914 mSecondWindow->setFocusable(true);
3915
3916 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
3917 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
3918
3919 setFocusedWindow(mWindow);
3920 mWindow->consumeFocusEvent(true);
3921 }
3922
3923 void notifyPointerCaptureChanged(bool enabled) {
3924 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
3925 mDispatcher->notifyPointerCaptureChanged(&args);
3926 }
3927
3928 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
3929 mDispatcher->requestPointerCapture(window->getToken(), enabled);
3930 mFakePolicy->waitForSetPointerCapture(enabled);
3931 notifyPointerCaptureChanged(enabled);
3932 window->consumeCaptureEvent(enabled);
3933 }
3934};
3935
3936TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
3937 // Ensure that capture cannot be obtained for unfocused windows.
3938 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
3939 mFakePolicy->assertSetPointerCaptureNotCalled();
3940 mSecondWindow->assertNoEvents();
3941
3942 // Ensure that capture can be enabled from the focus window.
3943 requestAndVerifyPointerCapture(mWindow, true);
3944
3945 // Ensure that capture cannot be disabled from a window that does not have capture.
3946 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
3947 mFakePolicy->assertSetPointerCaptureNotCalled();
3948
3949 // Ensure that capture can be disabled from the window with capture.
3950 requestAndVerifyPointerCapture(mWindow, false);
3951}
3952
3953TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
3954 requestAndVerifyPointerCapture(mWindow, true);
3955
3956 setFocusedWindow(mSecondWindow);
3957
3958 // Ensure that the capture disabled event was sent first.
3959 mWindow->consumeCaptureEvent(false);
3960 mWindow->consumeFocusEvent(false);
3961 mSecondWindow->consumeFocusEvent(true);
3962 mFakePolicy->waitForSetPointerCapture(false);
3963
3964 // Ensure that additional state changes from InputReader are not sent to the window.
3965 notifyPointerCaptureChanged(false);
3966 notifyPointerCaptureChanged(true);
3967 notifyPointerCaptureChanged(false);
3968 mWindow->assertNoEvents();
3969 mSecondWindow->assertNoEvents();
3970 mFakePolicy->assertSetPointerCaptureNotCalled();
3971}
3972
3973TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
3974 requestAndVerifyPointerCapture(mWindow, true);
3975
3976 // InputReader unexpectedly disables and enables pointer capture.
3977 notifyPointerCaptureChanged(false);
3978 notifyPointerCaptureChanged(true);
3979
3980 // Ensure that Pointer Capture is disabled.
3981 mWindow->consumeCaptureEvent(false);
3982 mWindow->assertNoEvents();
3983}
3984
Garfield Tane84e6f92019-08-29 17:28:41 -07003985} // namespace android::inputdispatcher