blob: 86a1515a4922fd6010328a3783a7f8434f872fd7 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Garfield Tan1c7bc862020-01-28 13:24:04 -080019#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070020#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070021#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080022#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100023#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <linux/input.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100025
Garfield Tan1c7bc862020-01-28 13:24:04 -080026#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070027#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080028#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080029#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080030
Garfield Tan1c7bc862020-01-28 13:24:04 -080031using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050032using android::gui::FocusRequest;
33using android::gui::TouchOcclusionMode;
34using android::gui::WindowInfo;
35using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080036using android::os::InputEventInjectionResult;
37using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010038using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080039
Garfield Tane84e6f92019-08-29 17:28:41 -070040namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
42// An arbitrary time value.
43static const nsecs_t ARBITRARY_TIME = 1234;
44
45// An arbitrary device id.
46static const int32_t DEVICE_ID = 1;
47
Jeff Brownf086ddb2014-02-11 14:28:48 -080048// An arbitrary display id.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -080049static const int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
Jeff Brownf086ddb2014-02-11 14:28:48 -080050
Michael Wrightd02c5b62014-02-10 15:10:22 -080051// An arbitrary injector pid / uid pair that has permission to inject events.
52static const int32_t INJECTOR_PID = 999;
53static const int32_t INJECTOR_UID = 1001;
54
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000055// An arbitrary pid of the gesture monitor window
56static constexpr int32_t MONITOR_PID = 2001;
57
chaviwd1c23182019-12-20 18:44:56 -080058struct PointF {
59 float x;
60 float y;
61};
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
Gang Wang342c9272020-01-13 13:15:04 -050063/**
64 * Return a DOWN key event with KEYCODE_A.
65 */
66static KeyEvent getTestKeyEvent() {
67 KeyEvent event;
68
Garfield Tanfbe732e2020-01-24 11:26:14 -080069 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
70 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
71 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050072 return event;
73}
74
Michael Wrightd02c5b62014-02-10 15:10:22 -080075// --- FakeInputDispatcherPolicy ---
76
77class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
78 InputDispatcherConfiguration mConfig;
79
80protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100081 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
83public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100084 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080085
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080086 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080087 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
88 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080089 }
90
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080091 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080092 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
93 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080094 }
95
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070096 void assertFilterInputEventWasNotCalled() {
97 std::scoped_lock lock(mLock);
98 ASSERT_EQ(nullptr, mFilteredEvent);
99 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800101 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700102 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800103 ASSERT_TRUE(mConfigurationChangedTime)
104 << "Timed out waiting for configuration changed call";
105 ASSERT_EQ(*mConfigurationChangedTime, when);
106 mConfigurationChangedTime = std::nullopt;
107 }
108
109 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700110 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800111 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800112 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800113 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
114 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
115 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
116 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
117 mLastNotifySwitch = std::nullopt;
118 }
119
chaviwfd6d3512019-03-25 13:23:49 -0700120 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700121 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800122 ASSERT_EQ(touchedToken, mOnPointerDownToken);
123 mOnPointerDownToken.clear();
124 }
125
126 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700127 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800128 ASSERT_TRUE(mOnPointerDownToken == nullptr)
129 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700130 }
131
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700132 // This function must be called soon after the expected ANR timer starts,
133 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500134 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700135 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500136 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
137 std::shared_ptr<InputApplicationHandle> application;
138 { // acquire lock
139 std::unique_lock lock(mLock);
140 android::base::ScopedLockAssertion assumeLocked(mLock);
141 ASSERT_NO_FATAL_FAILURE(
142 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
143 } // release lock
144 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700145 }
146
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000147 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
148 const sp<IBinder>& expectedConnectionToken) {
149 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500150 ASSERT_EQ(expectedConnectionToken, connectionToken);
151 }
152
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000153 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
154 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500155 ASSERT_EQ(expectedConnectionToken, connectionToken);
156 }
157
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000158 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
159 int32_t pid = getUnresponsiveMonitorPid(timeout);
160 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500161 }
162
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000163 void assertNotifyMonitorResponsiveWasCalled() {
164 int32_t pid = getResponsiveMonitorPid();
165 ASSERT_EQ(MONITOR_PID, pid);
166 }
167
168 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500169 std::unique_lock lock(mLock);
170 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000171 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
172 }
173
174 sp<IBinder> getResponsiveWindowToken() {
175 std::unique_lock lock(mLock);
176 android::base::ScopedLockAssertion assumeLocked(mLock);
177 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
178 }
179
180 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
181 std::unique_lock lock(mLock);
182 android::base::ScopedLockAssertion assumeLocked(mLock);
183 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
184 }
185
186 int32_t getResponsiveMonitorPid() {
187 std::unique_lock lock(mLock);
188 android::base::ScopedLockAssertion assumeLocked(mLock);
189 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500190 }
191
192 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
193 // for a specific container to become non-empty. When the container is non-empty, return the
194 // first entry from the container and erase it.
195 template <class T>
196 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
197 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
198 const std::chrono::time_point start = std::chrono::steady_clock::now();
199 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700200
201 // If there is an ANR, Dispatcher won't be idle because there are still events
202 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
203 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500204 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
205 // to provide it some time to act. 100ms seems reasonable.
206 mNotifyAnr.wait_for(lock, timeToWait,
207 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700208 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500209 if (storage.empty()) {
210 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000211 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700212 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700213 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
214 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700215 if (std::chrono::abs(timeout - waited) > 100ms) {
216 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
217 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
218 << "ms, but waited "
219 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
220 << "ms instead";
221 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500222 T token = storage.front();
223 storage.pop();
224 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700225 }
226
227 void assertNotifyAnrWasNotCalled() {
228 std::scoped_lock lock(mLock);
229 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000230 ASSERT_TRUE(mAnrWindowTokens.empty());
231 ASSERT_TRUE(mAnrMonitorPids.empty());
232 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500233 << "ANR was not called, but please also consume the 'connection is responsive' "
234 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000235 ASSERT_TRUE(mResponsiveMonitorPids.empty())
236 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
237 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700238 }
239
Garfield Tan1c7bc862020-01-28 13:24:04 -0800240 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
241 mConfig.keyRepeatTimeout = timeout;
242 mConfig.keyRepeatDelay = delay;
243 }
244
Prabir Pradhan99987712020-11-10 18:43:05 -0800245 void waitForSetPointerCapture(bool enabled) {
246 std::unique_lock lock(mLock);
247 base::ScopedLockAssertion assumeLocked(mLock);
248
249 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
250 [this, enabled]() REQUIRES(mLock) {
251 return mPointerCaptureEnabled &&
252 *mPointerCaptureEnabled ==
253 enabled;
254 })) {
255 FAIL() << "Timed out waiting for setPointerCapture(" << enabled << ") to be called.";
256 }
257 mPointerCaptureEnabled.reset();
258 }
259
260 void assertSetPointerCaptureNotCalled() {
261 std::unique_lock lock(mLock);
262 base::ScopedLockAssertion assumeLocked(mLock);
263
264 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
265 FAIL() << "Expected setPointerCapture(enabled) to not be called, but was called. "
266 "enabled = "
267 << *mPointerCaptureEnabled;
268 }
269 mPointerCaptureEnabled.reset();
270 }
271
arthurhungf452d0b2021-01-06 00:19:52 +0800272 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
273 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800274 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800275 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800276 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800277 }
278
Michael Wrightd02c5b62014-02-10 15:10:22 -0800279private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700280 std::mutex mLock;
281 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
282 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
283 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
284 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800285
Prabir Pradhan99987712020-11-10 18:43:05 -0800286 std::condition_variable mPointerCaptureChangedCondition;
287 std::optional<bool> mPointerCaptureEnabled GUARDED_BY(mLock);
288
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700289 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700290 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000291 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
292 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
293 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
294 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700295 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700296
arthurhungf452d0b2021-01-06 00:19:52 +0800297 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800298 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800299
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600300 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700301 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800302 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303 }
304
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000305 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700306 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000307 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700308 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500309 }
310
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000311 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500312 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000313 mAnrMonitorPids.push(pid);
314 mNotifyAnr.notify_all();
315 }
316
317 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
318 std::scoped_lock lock(mLock);
319 mResponsiveWindowTokens.push(connectionToken);
320 mNotifyAnr.notify_all();
321 }
322
323 void notifyMonitorResponsive(int32_t pid) override {
324 std::scoped_lock lock(mLock);
325 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500326 mNotifyAnr.notify_all();
327 }
328
329 void notifyNoFocusedWindowAnr(
330 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
331 std::scoped_lock lock(mLock);
332 mAnrApplications.push(applicationHandle);
333 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334 }
335
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600336 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800337
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600338 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700339
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600340 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700341 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
342 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
343 const std::vector<float>& values) override {}
344
345 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
346 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000347
Chris Yefb552902021-02-03 17:18:37 -0800348 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
349
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600350 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800351 *outConfig = mConfig;
352 }
353
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600354 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700355 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800356 switch (inputEvent->getType()) {
357 case AINPUT_EVENT_TYPE_KEY: {
358 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800359 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800360 break;
361 }
362
363 case AINPUT_EVENT_TYPE_MOTION: {
364 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800365 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800366 break;
367 }
368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800369 return true;
370 }
371
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600372 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800373
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600374 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800375
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600376 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800377 return 0;
378 }
379
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600380 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800381 return false;
382 }
383
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600384 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
385 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700386 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800387 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
388 * essentially a passthrough for notifySwitch.
389 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800390 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391 }
392
Sean Stoutb4e0a592021-02-23 07:34:53 -0800393 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800394
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800395 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
396 return pid == INJECTOR_PID && uid == INJECTOR_UID;
397 }
Jackal Guof9696682018-10-05 12:23:23 +0800398
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600399 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700400 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700401 mOnPointerDownToken = newToken;
402 }
403
Prabir Pradhan99987712020-11-10 18:43:05 -0800404 void setPointerCapture(bool enabled) override {
405 std::scoped_lock lock(mLock);
406 mPointerCaptureEnabled = {enabled};
407 mPointerCaptureChangedCondition.notify_all();
408 }
409
arthurhungf452d0b2021-01-06 00:19:52 +0800410 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
411 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800412 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800413 mDropTargetWindowToken = token;
414 }
415
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800416 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
417 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700418 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800419 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
420 ASSERT_EQ(mFilteredEvent->getType(), type);
421
422 if (type == AINPUT_EVENT_TYPE_KEY) {
423 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
424 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
425 EXPECT_EQ(keyEvent.getAction(), action);
426 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
427 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
428 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
429 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
430 EXPECT_EQ(motionEvent.getAction(), action);
431 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
432 } else {
433 FAIL() << "Unknown type: " << type;
434 }
435
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800436 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438};
439
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440// --- InputDispatcherTest ---
441
442class InputDispatcherTest : public testing::Test {
443protected:
444 sp<FakeInputDispatcherPolicy> mFakePolicy;
445 sp<InputDispatcher> mDispatcher;
446
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000447 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 mFakePolicy = new FakeInputDispatcherPolicy();
449 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800450 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000451 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700452 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453 }
454
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000455 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700456 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800457 mFakePolicy.clear();
458 mDispatcher.clear();
459 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700460
461 /**
462 * Used for debugging when writing the test
463 */
464 void dumpDispatcherState() {
465 std::string dump;
466 mDispatcher->dump(dump);
467 std::stringstream ss(dump);
468 std::string to;
469
470 while (std::getline(ss, to, '\n')) {
471 ALOGE("%s", to.c_str());
472 }
473 }
Vishnu Nair958da932020-08-21 17:12:37 -0700474
chaviw3277faf2021-05-19 16:45:23 -0500475 void setFocusedWindow(const sp<WindowInfoHandle>& window,
476 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700477 FocusRequest request;
478 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000479 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700480 if (focusedWindow) {
481 request.focusedToken = focusedWindow->getToken();
482 }
483 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
484 request.displayId = window->getInfo()->displayId;
485 mDispatcher->setFocusedWindow(request);
486 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487};
488
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
490 KeyEvent event;
491
492 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800493 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
494 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600495 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
496 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800497 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700498 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800499 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 << "Should reject key events with undefined action.";
501
502 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800503 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
504 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600505 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800506 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700507 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800508 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 << "Should reject key events with ACTION_MULTIPLE.";
510}
511
512TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
513 MotionEvent event;
514 PointerProperties pointerProperties[MAX_POINTERS + 1];
515 PointerCoords pointerCoords[MAX_POINTERS + 1];
516 for (int i = 0; i <= MAX_POINTERS; i++) {
517 pointerProperties[i].clear();
518 pointerProperties[i].id = i;
519 pointerCoords[i].clear();
520 }
521
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800522 // Some constants commonly used below
523 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
524 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
525 constexpr int32_t metaState = AMETA_NONE;
526 constexpr MotionClassification classification = MotionClassification::NONE;
527
chaviw9eaa22c2020-07-01 16:21:27 -0700528 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800530 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700531 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
532 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500533 AMOTION_EVENT_INVALID_CURSOR_POSITION, INVALID_DISPLAY_SIZE,
534 INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700535 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800536 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700537 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800538 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800539 << "Should reject motion events with undefined action.";
540
541 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800542 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700543 AMOTION_EVENT_ACTION_POINTER_DOWN |
544 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700545 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
546 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500547 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
548 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800549 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700550 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800551 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 << "Should reject motion events with pointer down index too large.";
553
Garfield Tanfbe732e2020-01-24 11:26:14 -0800554 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700555 AMOTION_EVENT_ACTION_POINTER_DOWN |
556 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700557 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
558 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500559 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
560 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800561 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700562 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800563 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 << "Should reject motion events with pointer down index too small.";
565
566 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800567 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700568 AMOTION_EVENT_ACTION_POINTER_UP |
569 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700570 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
571 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500572 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
573 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800574 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700575 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800576 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 << "Should reject motion events with pointer up index too large.";
578
Garfield Tanfbe732e2020-01-24 11:26:14 -0800579 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700580 AMOTION_EVENT_ACTION_POINTER_UP |
581 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700582 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
583 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500584 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
585 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800586 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700587 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800588 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 << "Should reject motion events with pointer up index too small.";
590
591 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800592 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
593 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700594 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500595 AMOTION_EVENT_INVALID_CURSOR_POSITION, INVALID_DISPLAY_SIZE,
596 INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700597 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800598 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700599 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800600 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 << "Should reject motion events with 0 pointers.";
602
Garfield Tanfbe732e2020-01-24 11:26:14 -0800603 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
604 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700605 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500606 AMOTION_EVENT_INVALID_CURSOR_POSITION, INVALID_DISPLAY_SIZE,
607 INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700608 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800609 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700610 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800611 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 << "Should reject motion events with more than MAX_POINTERS pointers.";
613
614 // Rejects motion events with invalid pointer ids.
615 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800616 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
617 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700618 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500619 AMOTION_EVENT_INVALID_CURSOR_POSITION, INVALID_DISPLAY_SIZE,
620 INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700621 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800622 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700623 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 << "Should reject motion events with pointer ids less than 0.";
626
627 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800628 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
629 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700630 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500631 AMOTION_EVENT_INVALID_CURSOR_POSITION, INVALID_DISPLAY_SIZE,
632 INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700633 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800634 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700635 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800636 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
638
639 // Rejects motion events with duplicate pointer ids.
640 pointerProperties[0].id = 1;
641 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800642 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
643 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700644 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
chaviw3277faf2021-05-19 16:45:23 -0500645 AMOTION_EVENT_INVALID_CURSOR_POSITION, INVALID_DISPLAY_SIZE,
646 INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700647 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800648 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700649 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800650 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 << "Should reject motion events with duplicate pointer ids.";
652}
653
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800654/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
655
656TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
657 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800658 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800659 mDispatcher->notifyConfigurationChanged(&args);
660 ASSERT_TRUE(mDispatcher->waitForIdle());
661
662 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
663}
664
665TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800666 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
667 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800668 mDispatcher->notifySwitch(&args);
669
670 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
671 args.policyFlags |= POLICY_FLAG_TRUSTED;
672 mFakePolicy->assertNotifySwitchWasCalled(args);
673}
674
Arthur Hungb92218b2018-08-14 12:00:21 +0800675// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700676static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700677static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800678
679class FakeApplicationHandle : public InputApplicationHandle {
680public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700681 FakeApplicationHandle() {
682 mInfo.name = "Fake Application";
683 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500684 mInfo.dispatchingTimeoutMillis =
685 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700686 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800687 virtual ~FakeApplicationHandle() {}
688
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000689 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700690
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500691 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
692 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700693 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800694};
695
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800696class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800697public:
Garfield Tan15601662020-09-22 15:32:38 -0700698 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800699 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700700 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800701 }
702
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800703 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700704 InputEvent* event;
705 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
706 if (!consumeSeq) {
707 return nullptr;
708 }
709 finishEvent(*consumeSeq);
710 return event;
711 }
712
713 /**
714 * Receive an event without acknowledging it.
715 * Return the sequence number that could later be used to send finished signal.
716 */
717 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800718 uint32_t consumeSeq;
719 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800720
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800721 std::chrono::time_point start = std::chrono::steady_clock::now();
722 status_t status = WOULD_BLOCK;
723 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800724 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800725 &event);
726 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
727 if (elapsed > 100ms) {
728 break;
729 }
730 }
731
732 if (status == WOULD_BLOCK) {
733 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700734 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800735 }
736
737 if (status != OK) {
738 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700739 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800740 }
741 if (event == nullptr) {
742 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700743 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800744 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700745 if (outEvent != nullptr) {
746 *outEvent = event;
747 }
748 return consumeSeq;
749 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800750
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700751 /**
752 * To be used together with "receiveEvent" to complete the consumption of an event.
753 */
754 void finishEvent(uint32_t consumeSeq) {
755 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
756 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800757 }
758
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000759 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
760 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
761 ASSERT_EQ(OK, status);
762 }
763
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000764 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
765 std::optional<int32_t> expectedDisplayId,
766 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800767 InputEvent* event = consume();
768
769 ASSERT_NE(nullptr, event) << mName.c_str()
770 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800771 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700772 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800773 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800774
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000775 if (expectedDisplayId.has_value()) {
776 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
777 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800778
Tiger Huang8664f8c2018-10-11 19:14:35 +0800779 switch (expectedEventType) {
780 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800781 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
782 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000783 if (expectedFlags.has_value()) {
784 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
785 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800786 break;
787 }
788 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800789 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
790 EXPECT_EQ(expectedAction, motionEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000791 if (expectedFlags.has_value()) {
792 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
793 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800794 break;
795 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100796 case AINPUT_EVENT_TYPE_FOCUS: {
797 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
798 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800799 case AINPUT_EVENT_TYPE_CAPTURE: {
800 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
801 }
arthurhungb89ccb02020-12-30 16:19:01 +0800802 case AINPUT_EVENT_TYPE_DRAG: {
803 FAIL() << "Use 'consumeDragEvent' for DRAG events";
804 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800805 default: {
806 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
807 }
808 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800809 }
810
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100811 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
812 InputEvent* event = consume();
813 ASSERT_NE(nullptr, event) << mName.c_str()
814 << ": consumer should have returned non-NULL event.";
815 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
816 << "Got " << inputEventTypeToString(event->getType())
817 << " event instead of FOCUS event";
818
819 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
820 << mName.c_str() << ": event displayId should always be NONE.";
821
822 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
823 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
824 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
825 }
826
Prabir Pradhan99987712020-11-10 18:43:05 -0800827 void consumeCaptureEvent(bool hasCapture) {
828 const InputEvent* event = consume();
829 ASSERT_NE(nullptr, event) << mName.c_str()
830 << ": consumer should have returned non-NULL event.";
831 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
832 << "Got " << inputEventTypeToString(event->getType())
833 << " event instead of CAPTURE event";
834
835 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
836 << mName.c_str() << ": event displayId should always be NONE.";
837
838 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
839 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
840 }
841
arthurhungb89ccb02020-12-30 16:19:01 +0800842 void consumeDragEvent(bool isExiting, float x, float y) {
843 const InputEvent* event = consume();
844 ASSERT_NE(nullptr, event) << mName.c_str()
845 << ": consumer should have returned non-NULL event.";
846 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
847 << "Got " << inputEventTypeToString(event->getType())
848 << " event instead of DRAG event";
849
850 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
851 << mName.c_str() << ": event displayId should always be NONE.";
852
853 const auto& dragEvent = static_cast<const DragEvent&>(*event);
854 EXPECT_EQ(isExiting, dragEvent.isExiting());
855 EXPECT_EQ(x, dragEvent.getX());
856 EXPECT_EQ(y, dragEvent.getY());
857 }
858
chaviwd1c23182019-12-20 18:44:56 -0800859 void assertNoEvents() {
860 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700861 if (event == nullptr) {
862 return;
863 }
864 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
865 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
866 ADD_FAILURE() << "Received key event "
867 << KeyEvent::actionToString(keyEvent.getAction());
868 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
869 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
870 ADD_FAILURE() << "Received motion event "
871 << MotionEvent::actionToString(motionEvent.getAction());
872 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
873 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
874 ADD_FAILURE() << "Received focus event, hasFocus = "
875 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800876 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
877 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
878 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
879 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700880 }
881 FAIL() << mName.c_str()
882 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800883 }
884
885 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
886
887protected:
888 std::unique_ptr<InputConsumer> mConsumer;
889 PreallocatedInputEventFactory mEventFactory;
890
891 std::string mName;
892};
893
chaviw3277faf2021-05-19 16:45:23 -0500894class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800895public:
896 static const int32_t WIDTH = 600;
897 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800898
Chris Yea209fde2020-07-22 13:54:51 -0700899 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800900 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500901 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800902 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500903 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700904 base::Result<std::unique_ptr<InputChannel>> channel =
905 dispatcher->createInputChannel(name);
906 token = (*channel)->getConnectionToken();
907 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800908 }
909
910 inputApplicationHandle->updateInfo();
911 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
912
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500913 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700914 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800915 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500916 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500917 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000918 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800919 mInfo.frameLeft = 0;
920 mInfo.frameTop = 0;
921 mInfo.frameRight = WIDTH;
922 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700923 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800924 mInfo.globalScaleFactor = 1.0;
925 mInfo.touchableRegion.clear();
926 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
927 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700928 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800929 mInfo.hasWallpaper = false;
930 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800931 mInfo.ownerPid = INJECTOR_PID;
932 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800933 mInfo.displayId = displayId;
934 }
935
936 virtual bool updateInfo() { return true; }
937
Vishnu Nair47074b82020-08-14 11:54:47 -0700938 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800939
Vishnu Nair958da932020-08-21 17:12:37 -0700940 void setVisible(bool visible) { mInfo.visible = visible; }
941
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700942 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500943 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700944 }
945
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 void setPaused(bool paused) { mInfo.paused = paused; }
947
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000948 void setAlpha(float alpha) { mInfo.alpha = alpha; }
949
chaviw3277faf2021-05-19 16:45:23 -0500950 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000951
Bernardo Rufino7393d172021-02-26 13:56:11 +0000952 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
953
chaviwd1c23182019-12-20 18:44:56 -0800954 void setFrame(const Rect& frame) {
955 mInfo.frameLeft = frame.left;
956 mInfo.frameTop = frame.top;
957 mInfo.frameRight = frame.right;
958 mInfo.frameBottom = frame.bottom;
arthurhungb89ccb02020-12-30 16:19:01 +0800959 mInfo.transform.set(-frame.left, -frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800960 mInfo.touchableRegion.clear();
961 mInfo.addTouchableRegion(frame);
962 }
963
chaviw3277faf2021-05-19 16:45:23 -0500964 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000965
chaviw3277faf2021-05-19 16:45:23 -0500966 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800967
chaviw3277faf2021-05-19 16:45:23 -0500968 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500969
chaviw9eaa22c2020-07-01 16:21:27 -0700970 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
971 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
972 }
973
974 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700975
yunho.shinf4a80b82020-11-16 21:13:57 +0900976 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
977
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800978 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
979 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
980 expectedFlags);
981 }
982
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700983 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
984 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
985 }
986
Svet Ganov5d3bc372020-01-26 23:11:07 -0800987 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000988 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800989 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
990 expectedFlags);
991 }
992
993 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000994 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800995 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
996 expectedFlags);
997 }
998
999 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001000 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001001 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1002 }
1003
1004 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1005 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001006 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1007 expectedFlags);
1008 }
1009
Svet Ganov5d3bc372020-01-26 23:11:07 -08001010 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001011 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1012 int32_t expectedFlags = 0) {
1013 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1014 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001015 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1016 }
1017
1018 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001019 int32_t expectedFlags = 0) {
1020 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1021 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001022 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1023 }
1024
1025 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001026 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001027 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1028 expectedFlags);
1029 }
1030
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001031 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1032 int32_t expectedFlags = 0) {
1033 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1034 expectedFlags);
1035 }
1036
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001037 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1038 ASSERT_NE(mInputReceiver, nullptr)
1039 << "Cannot consume events from a window with no receiver";
1040 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1041 }
1042
Prabir Pradhan99987712020-11-10 18:43:05 -08001043 void consumeCaptureEvent(bool hasCapture) {
1044 ASSERT_NE(mInputReceiver, nullptr)
1045 << "Cannot consume events from a window with no receiver";
1046 mInputReceiver->consumeCaptureEvent(hasCapture);
1047 }
1048
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001049 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1050 std::optional<int32_t> expectedDisplayId,
1051 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001052 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1053 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1054 expectedFlags);
1055 }
1056
arthurhungb89ccb02020-12-30 16:19:01 +08001057 void consumeDragEvent(bool isExiting, float x, float y) {
1058 mInputReceiver->consumeDragEvent(isExiting, x, y);
1059 }
1060
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001061 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001062 if (mInputReceiver == nullptr) {
1063 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1064 return std::nullopt;
1065 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001066 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001067 }
1068
1069 void finishEvent(uint32_t sequenceNum) {
1070 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1071 mInputReceiver->finishEvent(sequenceNum);
1072 }
1073
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001074 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1075 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1076 mInputReceiver->sendTimeline(inputEventId, timeline);
1077 }
1078
chaviwaf87b3e2019-10-01 16:59:28 -07001079 InputEvent* consume() {
1080 if (mInputReceiver == nullptr) {
1081 return nullptr;
1082 }
1083 return mInputReceiver->consume();
1084 }
1085
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001086 MotionEvent* consumeMotion() {
1087 InputEvent* event = consume();
1088 if (event == nullptr) {
1089 ADD_FAILURE() << "Consume failed : no event";
1090 return nullptr;
1091 }
1092 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1093 ADD_FAILURE() << "Instead of motion event, got "
1094 << inputEventTypeToString(event->getType());
1095 return nullptr;
1096 }
1097 return static_cast<MotionEvent*>(event);
1098 }
1099
Arthur Hungb92218b2018-08-14 12:00:21 +08001100 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001101 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001102 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001103 return; // Can't receive events if the window does not have input channel
1104 }
1105 ASSERT_NE(nullptr, mInputReceiver)
1106 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001107 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001108 }
1109
chaviwaf87b3e2019-10-01 16:59:28 -07001110 sp<IBinder> getToken() { return mInfo.token; }
1111
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001112 const std::string& getName() { return mName; }
1113
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001114 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1115 mInfo.ownerPid = ownerPid;
1116 mInfo.ownerUid = ownerUid;
1117 }
1118
chaviwd1c23182019-12-20 18:44:56 -08001119private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001120 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001121 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001122 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001123};
1124
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001125std::atomic<int32_t> FakeWindowHandle::sId{1};
1126
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001127static InputEventInjectionResult injectKey(
1128 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1129 int32_t displayId = ADISPLAY_ID_NONE,
1130 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001131 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1132 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001133 KeyEvent event;
1134 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1135
1136 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001137 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001138 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1139 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001140
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001141 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1142 if (!allowKeyRepeat) {
1143 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1144 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001145 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001146 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001147 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001148}
1149
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001150static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1151 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001152 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1153}
1154
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001155// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1156// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1157// has to be woken up to process the repeating key.
1158static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1159 int32_t displayId = ADISPLAY_ID_NONE) {
1160 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1161 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1162 /* allowKeyRepeat */ false);
1163}
1164
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001165static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1166 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001167 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1168}
1169
Garfield Tandf26e862020-07-01 20:18:19 -07001170class PointerBuilder {
1171public:
1172 PointerBuilder(int32_t id, int32_t toolType) {
1173 mProperties.clear();
1174 mProperties.id = id;
1175 mProperties.toolType = toolType;
1176 mCoords.clear();
1177 }
1178
1179 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1180
1181 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1182
1183 PointerBuilder& axis(int32_t axis, float value) {
1184 mCoords.setAxisValue(axis, value);
1185 return *this;
1186 }
1187
1188 PointerProperties buildProperties() const { return mProperties; }
1189
1190 PointerCoords buildCoords() const { return mCoords; }
1191
1192private:
1193 PointerProperties mProperties;
1194 PointerCoords mCoords;
1195};
1196
1197class MotionEventBuilder {
1198public:
1199 MotionEventBuilder(int32_t action, int32_t source) {
1200 mAction = action;
1201 mSource = source;
1202 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1203 }
1204
1205 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1206 mEventTime = eventTime;
1207 return *this;
1208 }
1209
1210 MotionEventBuilder& displayId(int32_t displayId) {
1211 mDisplayId = displayId;
1212 return *this;
1213 }
1214
1215 MotionEventBuilder& actionButton(int32_t actionButton) {
1216 mActionButton = actionButton;
1217 return *this;
1218 }
1219
arthurhung6d4bed92021-03-17 11:59:33 +08001220 MotionEventBuilder& buttonState(int32_t buttonState) {
1221 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001222 return *this;
1223 }
1224
1225 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1226 mRawXCursorPosition = rawXCursorPosition;
1227 return *this;
1228 }
1229
1230 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1231 mRawYCursorPosition = rawYCursorPosition;
1232 return *this;
1233 }
1234
1235 MotionEventBuilder& pointer(PointerBuilder pointer) {
1236 mPointers.push_back(pointer);
1237 return *this;
1238 }
1239
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001240 MotionEventBuilder& addFlag(uint32_t flags) {
1241 mFlags |= flags;
1242 return *this;
1243 }
1244
Garfield Tandf26e862020-07-01 20:18:19 -07001245 MotionEvent build() {
1246 std::vector<PointerProperties> pointerProperties;
1247 std::vector<PointerCoords> pointerCoords;
1248 for (const PointerBuilder& pointer : mPointers) {
1249 pointerProperties.push_back(pointer.buildProperties());
1250 pointerCoords.push_back(pointer.buildCoords());
1251 }
1252
1253 // Set mouse cursor position for the most common cases to avoid boilerplate.
1254 if (mSource == AINPUT_SOURCE_MOUSE &&
1255 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1256 mPointers.size() == 1) {
1257 mRawXCursorPosition = pointerCoords[0].getX();
1258 mRawYCursorPosition = pointerCoords[0].getY();
1259 }
1260
1261 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001262 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001263 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001264 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001265 mButtonState, MotionClassification::NONE, identityTransform,
1266 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07001267 mRawYCursorPosition, mDisplayWidth, mDisplayHeight, mEventTime, mEventTime,
1268 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001269
1270 return event;
1271 }
1272
1273private:
1274 int32_t mAction;
1275 int32_t mSource;
1276 nsecs_t mEventTime;
1277 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1278 int32_t mActionButton{0};
1279 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001280 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001281 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1282 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
chaviw3277faf2021-05-19 16:45:23 -05001283 int32_t mDisplayWidth{INVALID_DISPLAY_SIZE};
1284 int32_t mDisplayHeight{INVALID_DISPLAY_SIZE};
Garfield Tandf26e862020-07-01 20:18:19 -07001285
1286 std::vector<PointerBuilder> mPointers;
1287};
1288
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001289static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001290 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1291 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001293 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1294 injectionTimeout,
1295 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1296}
1297
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001298static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001299 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1300 const PointF& position,
1301 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001302 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1303 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001304 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001305 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001306 MotionEvent event = MotionEventBuilder(action, source)
1307 .displayId(displayId)
1308 .eventTime(eventTime)
1309 .rawXCursorPosition(cursorPosition.x)
1310 .rawYCursorPosition(cursorPosition.y)
1311 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1312 .x(position.x)
1313 .y(position.y))
1314 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001315
1316 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001317 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001318}
1319
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001320static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1321 int32_t source, int32_t displayId,
1322 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001323 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001324}
1325
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001326static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1327 int32_t source, int32_t displayId,
1328 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001329 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001330}
1331
Jackal Guof9696682018-10-05 12:23:23 +08001332static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1333 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1334 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001335 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1336 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1337 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001338
1339 return args;
1340}
1341
chaviwd1c23182019-12-20 18:44:56 -08001342static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1343 const std::vector<PointF>& points) {
1344 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001345 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1346 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1347 }
1348
chaviwd1c23182019-12-20 18:44:56 -08001349 PointerProperties pointerProperties[pointerCount];
1350 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001351
chaviwd1c23182019-12-20 18:44:56 -08001352 for (size_t i = 0; i < pointerCount; i++) {
1353 pointerProperties[i].clear();
1354 pointerProperties[i].id = i;
1355 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001356
chaviwd1c23182019-12-20 18:44:56 -08001357 pointerCoords[i].clear();
1358 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1359 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1360 }
Jackal Guof9696682018-10-05 12:23:23 +08001361
1362 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1363 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001364 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001365 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1366 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001367 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1368 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001369 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1370 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001371
1372 return args;
1373}
1374
chaviwd1c23182019-12-20 18:44:56 -08001375static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1376 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1377}
1378
Prabir Pradhan99987712020-11-10 18:43:05 -08001379static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(bool enabled) {
1380 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), enabled);
1381}
1382
Arthur Hungb92218b2018-08-14 12:00:21 +08001383TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001384 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001385 sp<FakeWindowHandle> window =
1386 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001387
Arthur Hung72d8dc32020-03-28 00:48:39 +00001388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001389 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1390 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1391 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001392
1393 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001394 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001395}
1396
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001397/**
1398 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1399 * To ensure that window receives only events that were directly inside of it, add
1400 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1401 * when finding touched windows.
1402 * This test serves as a sanity check for the next test, where setInputWindows is
1403 * called twice.
1404 */
1405TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001406 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001407 sp<FakeWindowHandle> window =
1408 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1409 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001410 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001411
1412 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001413 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001414 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1415 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001416 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001417
1418 // Window should receive motion event.
1419 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1420}
1421
1422/**
1423 * Calling setInputWindows twice, with the same info, should not cause any issues.
1424 * To ensure that window receives only events that were directly inside of it, add
1425 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1426 * when finding touched windows.
1427 */
1428TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001429 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001430 sp<FakeWindowHandle> window =
1431 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1432 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001433 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001434
1435 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001437 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001438 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1439 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001440 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001441
1442 // Window should receive motion event.
1443 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1444}
1445
Arthur Hungb92218b2018-08-14 12:00:21 +08001446// The foreground window should receive the first touch down event.
1447TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001448 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001449 sp<FakeWindowHandle> windowTop =
1450 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1451 sp<FakeWindowHandle> windowSecond =
1452 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001453
Arthur Hung72d8dc32020-03-28 00:48:39 +00001454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001455 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1456 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1457 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001458
1459 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001460 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001461 windowSecond->assertNoEvents();
1462}
1463
Garfield Tandf26e862020-07-01 20:18:19 -07001464TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001465 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001466 sp<FakeWindowHandle> windowLeft =
1467 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1468 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001469 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001470 sp<FakeWindowHandle> windowRight =
1471 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1472 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001473 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001474
1475 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1476
1477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1478
1479 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001480 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001481 injectMotionEvent(mDispatcher,
1482 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1483 AINPUT_SOURCE_MOUSE)
1484 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1485 .x(900)
1486 .y(400))
1487 .build()));
1488 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1489 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1490 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1491 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1492
1493 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001495 injectMotionEvent(mDispatcher,
1496 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1497 AINPUT_SOURCE_MOUSE)
1498 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1499 .x(300)
1500 .y(400))
1501 .build()));
1502 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1503 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1504 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1505 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1506 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1507 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1508
1509 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001511 injectMotionEvent(mDispatcher,
1512 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1513 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1514 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1515 .x(300)
1516 .y(400))
1517 .build()));
1518 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1519
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001521 injectMotionEvent(mDispatcher,
1522 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1523 AINPUT_SOURCE_MOUSE)
1524 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1525 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1526 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1527 .x(300)
1528 .y(400))
1529 .build()));
1530 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1531 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1532
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001534 injectMotionEvent(mDispatcher,
1535 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1536 AINPUT_SOURCE_MOUSE)
1537 .buttonState(0)
1538 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1539 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1540 .x(300)
1541 .y(400))
1542 .build()));
1543 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1544 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1545
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001547 injectMotionEvent(mDispatcher,
1548 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1549 .buttonState(0)
1550 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1551 .x(300)
1552 .y(400))
1553 .build()));
1554 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1555
1556 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001558 injectMotionEvent(mDispatcher,
1559 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1560 AINPUT_SOURCE_MOUSE)
1561 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1562 .x(900)
1563 .y(400))
1564 .build()));
1565 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1566 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1567 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1568 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1569 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1570 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1571}
1572
1573// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1574// directly in this test.
1575TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001576 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001577 sp<FakeWindowHandle> window =
1578 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1579 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001580 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001581
1582 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1583
1584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1585
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001587 injectMotionEvent(mDispatcher,
1588 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1589 AINPUT_SOURCE_MOUSE)
1590 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1591 .x(300)
1592 .y(400))
1593 .build()));
1594 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1595 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1596
1597 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001599 injectMotionEvent(mDispatcher,
1600 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1601 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1602 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1603 .x(300)
1604 .y(400))
1605 .build()));
1606 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1607
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001608 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001609 injectMotionEvent(mDispatcher,
1610 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1611 AINPUT_SOURCE_MOUSE)
1612 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1613 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1614 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1615 .x(300)
1616 .y(400))
1617 .build()));
1618 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1619 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1620
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001622 injectMotionEvent(mDispatcher,
1623 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1624 AINPUT_SOURCE_MOUSE)
1625 .buttonState(0)
1626 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1627 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1628 .x(300)
1629 .y(400))
1630 .build()));
1631 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1632 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1633
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001635 injectMotionEvent(mDispatcher,
1636 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1637 .buttonState(0)
1638 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1639 .x(300)
1640 .y(400))
1641 .build()));
1642 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1643
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001644 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001645 injectMotionEvent(mDispatcher,
1646 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1647 AINPUT_SOURCE_MOUSE)
1648 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1649 .x(300)
1650 .y(400))
1651 .build()));
1652 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1653 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1654}
1655
Garfield Tan00f511d2019-06-12 16:55:40 -07001656TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001657 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001658
1659 sp<FakeWindowHandle> windowLeft =
1660 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1661 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001662 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001663 sp<FakeWindowHandle> windowRight =
1664 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1665 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001666 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001667
1668 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1669
Arthur Hung72d8dc32020-03-28 00:48:39 +00001670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001671
1672 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1673 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001674 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001675 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001676 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001677 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001678 windowRight->assertNoEvents();
1679}
1680
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001681TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001682 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001683 sp<FakeWindowHandle> window =
1684 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001685 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001686
Arthur Hung72d8dc32020-03-28 00:48:39 +00001687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001688 setFocusedWindow(window);
1689
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001690 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001691
1692 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1693 mDispatcher->notifyKey(&keyArgs);
1694
1695 // Window should receive key down event.
1696 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1697
1698 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1699 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001700 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001701 mDispatcher->notifyDeviceReset(&args);
1702 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1703 AKEY_EVENT_FLAG_CANCELED);
1704}
1705
1706TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001707 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001708 sp<FakeWindowHandle> window =
1709 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1710
Arthur Hung72d8dc32020-03-28 00:48:39 +00001711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001712
1713 NotifyMotionArgs motionArgs =
1714 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1715 ADISPLAY_ID_DEFAULT);
1716 mDispatcher->notifyMotion(&motionArgs);
1717
1718 // Window should receive motion down event.
1719 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1720
1721 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1722 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001723 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001724 mDispatcher->notifyDeviceReset(&args);
1725 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1726 0 /*expectedFlags*/);
1727}
1728
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001729using TransferFunction =
1730 std::function<bool(sp<InputDispatcher> dispatcher, sp<IBinder>, sp<IBinder>)>;
1731
1732class TransferTouchFixture : public InputDispatcherTest,
1733 public ::testing::WithParamInterface<TransferFunction> {};
1734
1735TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001736 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001737
1738 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001739 sp<FakeWindowHandle> firstWindow =
1740 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1741 sp<FakeWindowHandle> secondWindow =
1742 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001743
1744 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001746
1747 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001748 NotifyMotionArgs downMotionArgs =
1749 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1750 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001751 mDispatcher->notifyMotion(&downMotionArgs);
1752 // Only the first window should get the down event
1753 firstWindow->consumeMotionDown();
1754 secondWindow->assertNoEvents();
1755
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001756 // Transfer touch to the second window
1757 TransferFunction f = GetParam();
1758 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1759 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001760 // The first window gets cancel and the second gets down
1761 firstWindow->consumeMotionCancel();
1762 secondWindow->consumeMotionDown();
1763
1764 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001765 NotifyMotionArgs upMotionArgs =
1766 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1767 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001768 mDispatcher->notifyMotion(&upMotionArgs);
1769 // The first window gets no events and the second gets up
1770 firstWindow->assertNoEvents();
1771 secondWindow->consumeMotionUp();
1772}
1773
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001774TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001775 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001776
1777 PointF touchPoint = {10, 10};
1778
1779 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001780 sp<FakeWindowHandle> firstWindow =
1781 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1782 sp<FakeWindowHandle> secondWindow =
1783 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001784
1785 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001787
1788 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001789 NotifyMotionArgs downMotionArgs =
1790 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1791 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001792 mDispatcher->notifyMotion(&downMotionArgs);
1793 // Only the first window should get the down event
1794 firstWindow->consumeMotionDown();
1795 secondWindow->assertNoEvents();
1796
1797 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001798 NotifyMotionArgs pointerDownMotionArgs =
1799 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1800 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1801 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1802 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001803 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1804 // Only the first window should get the pointer down event
1805 firstWindow->consumeMotionPointerDown(1);
1806 secondWindow->assertNoEvents();
1807
1808 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001809 TransferFunction f = GetParam();
1810 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1811 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001812 // The first window gets cancel and the second gets down and pointer down
1813 firstWindow->consumeMotionCancel();
1814 secondWindow->consumeMotionDown();
1815 secondWindow->consumeMotionPointerDown(1);
1816
1817 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001818 NotifyMotionArgs pointerUpMotionArgs =
1819 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1820 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1821 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1822 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001823 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1824 // The first window gets nothing and the second gets pointer up
1825 firstWindow->assertNoEvents();
1826 secondWindow->consumeMotionPointerUp(1);
1827
1828 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001829 NotifyMotionArgs upMotionArgs =
1830 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1831 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001832 mDispatcher->notifyMotion(&upMotionArgs);
1833 // The first window gets nothing and the second gets up
1834 firstWindow->assertNoEvents();
1835 secondWindow->consumeMotionUp();
1836}
1837
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001838// For the cases of single pointer touch and two pointers non-split touch, the api's
1839// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
1840// for the case where there are multiple pointers split across several windows.
1841INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
1842 ::testing::Values(
1843 [&](sp<InputDispatcher> dispatcher, sp<IBinder> /*ignored*/,
1844 sp<IBinder> destChannelToken) {
1845 return dispatcher->transferTouch(destChannelToken);
1846 },
1847 [&](sp<InputDispatcher> dispatcher, sp<IBinder> from,
1848 sp<IBinder> to) {
1849 return dispatcher->transferTouchFocus(from, to,
1850 false /*isDragAndDrop*/);
1851 }));
1852
Svet Ganov5d3bc372020-01-26 23:11:07 -08001853TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001854 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001855
1856 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001857 sp<FakeWindowHandle> firstWindow =
1858 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001859 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05001860 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001861
1862 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001863 sp<FakeWindowHandle> secondWindow =
1864 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001865 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001866 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001867
1868 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001870
1871 PointF pointInFirst = {300, 200};
1872 PointF pointInSecond = {300, 600};
1873
1874 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001875 NotifyMotionArgs firstDownMotionArgs =
1876 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1877 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001878 mDispatcher->notifyMotion(&firstDownMotionArgs);
1879 // Only the first window should get the down event
1880 firstWindow->consumeMotionDown();
1881 secondWindow->assertNoEvents();
1882
1883 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001884 NotifyMotionArgs secondDownMotionArgs =
1885 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1886 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1887 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1888 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001889 mDispatcher->notifyMotion(&secondDownMotionArgs);
1890 // The first window gets a move and the second a down
1891 firstWindow->consumeMotionMove();
1892 secondWindow->consumeMotionDown();
1893
1894 // Transfer touch focus to the second window
1895 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1896 // The first window gets cancel and the new gets pointer down (it already saw down)
1897 firstWindow->consumeMotionCancel();
1898 secondWindow->consumeMotionPointerDown(1);
1899
1900 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001901 NotifyMotionArgs pointerUpMotionArgs =
1902 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1903 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1904 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1905 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001906 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1907 // The first window gets nothing and the second gets pointer up
1908 firstWindow->assertNoEvents();
1909 secondWindow->consumeMotionPointerUp(1);
1910
1911 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001912 NotifyMotionArgs upMotionArgs =
1913 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1914 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001915 mDispatcher->notifyMotion(&upMotionArgs);
1916 // The first window gets nothing and the second gets up
1917 firstWindow->assertNoEvents();
1918 secondWindow->consumeMotionUp();
1919}
1920
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001921// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
1922// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
1923// touch is not supported, so the touch should continue on those windows and the transferred-to
1924// window should get nothing.
1925TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
1926 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1927
1928 // Create a non touch modal window that supports split touch
1929 sp<FakeWindowHandle> firstWindow =
1930 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1931 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05001932 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001933
1934 // Create a non touch modal window that supports split touch
1935 sp<FakeWindowHandle> secondWindow =
1936 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1937 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001938 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001939
1940 // Add the windows to the dispatcher
1941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1942
1943 PointF pointInFirst = {300, 200};
1944 PointF pointInSecond = {300, 600};
1945
1946 // Send down to the first window
1947 NotifyMotionArgs firstDownMotionArgs =
1948 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1949 ADISPLAY_ID_DEFAULT, {pointInFirst});
1950 mDispatcher->notifyMotion(&firstDownMotionArgs);
1951 // Only the first window should get the down event
1952 firstWindow->consumeMotionDown();
1953 secondWindow->assertNoEvents();
1954
1955 // Send down to the second window
1956 NotifyMotionArgs secondDownMotionArgs =
1957 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1958 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1959 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1960 {pointInFirst, pointInSecond});
1961 mDispatcher->notifyMotion(&secondDownMotionArgs);
1962 // The first window gets a move and the second a down
1963 firstWindow->consumeMotionMove();
1964 secondWindow->consumeMotionDown();
1965
1966 // Transfer touch focus to the second window
1967 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
1968 // The 'transferTouch' call should not succeed, because there are 2 touched windows
1969 ASSERT_FALSE(transferred);
1970 firstWindow->assertNoEvents();
1971 secondWindow->assertNoEvents();
1972
1973 // The rest of the dispatch should proceed as normal
1974 // Send pointer up to the second window
1975 NotifyMotionArgs pointerUpMotionArgs =
1976 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1977 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1978 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1979 {pointInFirst, pointInSecond});
1980 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1981 // The first window gets MOVE and the second gets pointer up
1982 firstWindow->consumeMotionMove();
1983 secondWindow->consumeMotionUp();
1984
1985 // Send up event to the first window
1986 NotifyMotionArgs upMotionArgs =
1987 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1988 ADISPLAY_ID_DEFAULT);
1989 mDispatcher->notifyMotion(&upMotionArgs);
1990 // The first window gets nothing and the second gets up
1991 firstWindow->consumeMotionUp();
1992 secondWindow->assertNoEvents();
1993}
1994
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001995TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001997 sp<FakeWindowHandle> window =
1998 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1999
Vishnu Nair47074b82020-08-14 11:54:47 -07002000 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002002 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002003
2004 window->consumeFocusEvent(true);
2005
2006 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2007 mDispatcher->notifyKey(&keyArgs);
2008
2009 // Window should receive key down event.
2010 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2011}
2012
2013TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002014 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002015 sp<FakeWindowHandle> window =
2016 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2017
Arthur Hung72d8dc32020-03-28 00:48:39 +00002018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002019
2020 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2021 mDispatcher->notifyKey(&keyArgs);
2022 mDispatcher->waitForIdle();
2023
2024 window->assertNoEvents();
2025}
2026
2027// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2028TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002029 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002030 sp<FakeWindowHandle> window =
2031 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2032
Arthur Hung72d8dc32020-03-28 00:48:39 +00002033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002034
2035 // Send key
2036 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2037 mDispatcher->notifyKey(&keyArgs);
2038 // Send motion
2039 NotifyMotionArgs motionArgs =
2040 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2041 ADISPLAY_ID_DEFAULT);
2042 mDispatcher->notifyMotion(&motionArgs);
2043
2044 // Window should receive only the motion event
2045 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2046 window->assertNoEvents(); // Key event or focus event will not be received
2047}
2048
arthurhungea3f4fc2020-12-21 23:18:53 +08002049TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2050 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2051
2052 // Create first non touch modal window that supports split touch
2053 sp<FakeWindowHandle> firstWindow =
2054 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2055 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002056 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002057
2058 // Create second non touch modal window that supports split touch
2059 sp<FakeWindowHandle> secondWindow =
2060 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2061 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002062 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002063
2064 // Add the windows to the dispatcher
2065 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2066
2067 PointF pointInFirst = {300, 200};
2068 PointF pointInSecond = {300, 600};
2069
2070 // Send down to the first window
2071 NotifyMotionArgs firstDownMotionArgs =
2072 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2073 ADISPLAY_ID_DEFAULT, {pointInFirst});
2074 mDispatcher->notifyMotion(&firstDownMotionArgs);
2075 // Only the first window should get the down event
2076 firstWindow->consumeMotionDown();
2077 secondWindow->assertNoEvents();
2078
2079 // Send down to the second window
2080 NotifyMotionArgs secondDownMotionArgs =
2081 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2082 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2083 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2084 {pointInFirst, pointInSecond});
2085 mDispatcher->notifyMotion(&secondDownMotionArgs);
2086 // The first window gets a move and the second a down
2087 firstWindow->consumeMotionMove();
2088 secondWindow->consumeMotionDown();
2089
2090 // Send pointer cancel to the second window
2091 NotifyMotionArgs pointerUpMotionArgs =
2092 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2093 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2094 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2095 {pointInFirst, pointInSecond});
2096 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2097 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2098 // The first window gets move and the second gets cancel.
2099 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2100 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2101
2102 // Send up event.
2103 NotifyMotionArgs upMotionArgs =
2104 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2105 ADISPLAY_ID_DEFAULT);
2106 mDispatcher->notifyMotion(&upMotionArgs);
2107 // The first window gets up and the second gets nothing.
2108 firstWindow->consumeMotionUp();
2109 secondWindow->assertNoEvents();
2110}
2111
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002112TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2113 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2114
2115 sp<FakeWindowHandle> window =
2116 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2117 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2118 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2119 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2120 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2121
2122 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2123 window->assertNoEvents();
2124 mDispatcher->waitForIdle();
2125}
2126
chaviwd1c23182019-12-20 18:44:56 -08002127class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002128public:
2129 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002130 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002131 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002132 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002133 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002134 }
2135
chaviwd1c23182019-12-20 18:44:56 -08002136 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2137
2138 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2139 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2140 expectedDisplayId, expectedFlags);
2141 }
2142
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002143 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2144
2145 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2146
chaviwd1c23182019-12-20 18:44:56 -08002147 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2148 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2149 expectedDisplayId, expectedFlags);
2150 }
2151
2152 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2153 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2154 expectedDisplayId, expectedFlags);
2155 }
2156
Evan Rosky84f07f02021-04-16 10:42:42 -07002157 MotionEvent* consumeMotion() {
2158 InputEvent* event = mInputReceiver->consume();
2159 if (!event) {
2160 ADD_FAILURE() << "No event was produced";
2161 return nullptr;
2162 }
2163 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2164 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2165 return nullptr;
2166 }
2167 return static_cast<MotionEvent*>(event);
2168 }
2169
chaviwd1c23182019-12-20 18:44:56 -08002170 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2171
2172private:
2173 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002174};
2175
2176// Tests for gesture monitors
2177TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002178 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002179 sp<FakeWindowHandle> window =
2180 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002182
chaviwd1c23182019-12-20 18:44:56 -08002183 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2184 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002185
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002186 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002187 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002188 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002189 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002190 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002191}
2192
2193TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002194 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002195 sp<FakeWindowHandle> window =
2196 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2197
2198 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002199 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002200
Arthur Hung72d8dc32020-03-28 00:48:39 +00002201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002202 setFocusedWindow(window);
2203
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002204 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002205
chaviwd1c23182019-12-20 18:44:56 -08002206 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2207 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002208
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002209 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2210 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002211 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002212 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002213}
2214
2215TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002216 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002217 sp<FakeWindowHandle> window =
2218 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002220
chaviwd1c23182019-12-20 18:44:56 -08002221 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2222 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002223
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002224 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002225 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002226 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002227 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002228 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002229
2230 window->releaseChannel();
2231
chaviwd1c23182019-12-20 18:44:56 -08002232 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002233
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002234 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002235 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002236 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002237 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002238}
2239
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002240TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2241 FakeMonitorReceiver monitor =
2242 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2243 true /*isGestureMonitor*/);
2244
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002246 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2247 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2248 ASSERT_TRUE(consumeSeq);
2249
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002250 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002251 monitor.finishEvent(*consumeSeq);
2252 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002253 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002254}
2255
Evan Rosky84f07f02021-04-16 10:42:42 -07002256// Tests for gesture monitors
2257TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2258 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2259 sp<FakeWindowHandle> window =
2260 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2261 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2262 window->setWindowOffset(20, 40);
2263 window->setWindowTransform(0, 1, -1, 0);
2264
2265 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2266 true /*isGestureMonitor*/);
2267
2268 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2269 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2270 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2271 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2272 MotionEvent* event = monitor.consumeMotion();
2273 // Even though window has transform, gesture monitor must not.
2274 ASSERT_EQ(ui::Transform(), event->getTransform());
2275}
2276
chaviw81e2bb92019-12-18 15:03:51 -08002277TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002278 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002279 sp<FakeWindowHandle> window =
2280 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2281
Arthur Hung72d8dc32020-03-28 00:48:39 +00002282 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002283
2284 NotifyMotionArgs motionArgs =
2285 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2286 ADISPLAY_ID_DEFAULT);
2287
2288 mDispatcher->notifyMotion(&motionArgs);
2289 // Window should receive motion down event.
2290 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2291
2292 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002293 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002294 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2295 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2296 motionArgs.pointerCoords[0].getX() - 10);
2297
2298 mDispatcher->notifyMotion(&motionArgs);
2299 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2300 0 /*expectedFlags*/);
2301}
2302
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002303/**
2304 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2305 * the device default right away. In the test scenario, we check both the default value,
2306 * and the action of enabling / disabling.
2307 */
2308TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002309 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002310 sp<FakeWindowHandle> window =
2311 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2312
2313 // Set focused application.
2314 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002315 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002316
2317 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002319 setFocusedWindow(window);
2320
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002321 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2322
2323 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002324 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002326 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2327
2328 SCOPED_TRACE("Disable touch mode");
2329 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002330 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002332 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002333 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2334
2335 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002336 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002338 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2339
2340 SCOPED_TRACE("Enable touch mode again");
2341 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002342 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002344 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002345 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2346
2347 window->assertNoEvents();
2348}
2349
Gang Wange9087892020-01-07 12:17:14 -05002350TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002351 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002352 sp<FakeWindowHandle> window =
2353 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2354
2355 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002356 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002357
Arthur Hung72d8dc32020-03-28 00:48:39 +00002358 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002359 setFocusedWindow(window);
2360
Gang Wange9087892020-01-07 12:17:14 -05002361 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2362
2363 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2364 mDispatcher->notifyKey(&keyArgs);
2365
2366 InputEvent* event = window->consume();
2367 ASSERT_NE(event, nullptr);
2368
2369 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2370 ASSERT_NE(verified, nullptr);
2371 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2372
2373 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2374 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2375 ASSERT_EQ(keyArgs.source, verified->source);
2376 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2377
2378 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2379
2380 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2381 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002382 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2383 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2384 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2385 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2386 ASSERT_EQ(0, verifiedKey.repeatCount);
2387}
2388
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002389TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002390 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002391 sp<FakeWindowHandle> window =
2392 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2393
2394 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2395
Arthur Hung72d8dc32020-03-28 00:48:39 +00002396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002397
2398 NotifyMotionArgs motionArgs =
2399 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2400 ADISPLAY_ID_DEFAULT);
2401 mDispatcher->notifyMotion(&motionArgs);
2402
2403 InputEvent* event = window->consume();
2404 ASSERT_NE(event, nullptr);
2405
2406 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2407 ASSERT_NE(verified, nullptr);
2408 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2409
2410 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2411 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2412 EXPECT_EQ(motionArgs.source, verified->source);
2413 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2414
2415 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2416
2417 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2418 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2419 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2420 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2421 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2422 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2423 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2424}
2425
Prabir Pradhan664834b2021-05-20 16:00:42 -07002426TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002427 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2428 sp<FakeWindowHandle> window =
2429 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2430 const std::string name = window->getName();
2431
2432 // Window gets transformed by offset values.
2433 window->setWindowOffset(500.0f, 500.0f);
2434
2435 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2436 window->setFocusable(true);
2437
2438 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2439
2440 // First, we set focused window so that focusedWindowHandle is not null.
2441 setFocusedWindow(window);
2442
2443 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2444 window->consumeFocusEvent(true);
2445
Prabir Pradhan664834b2021-05-20 16:00:42 -07002446 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
2447 AMOTION_EVENT_ACTION_DOWN),
2448 std::pair(AINPUT_SOURCE_JOYSTICK,
2449 AMOTION_EVENT_ACTION_MOVE)};
2450 for (const auto& [source, action] : nonTransformedSources) {
2451 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
Prabir Pradhanbd527712021-03-09 19:17:09 -08002452 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09002453
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002454 MotionEvent* event = window->consumeMotion();
Prabir Pradhanbd527712021-03-09 19:17:09 -08002455 ASSERT_NE(event, nullptr);
yunho.shinf4a80b82020-11-16 21:13:57 +09002456
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002457 const MotionEvent& motionEvent = *event;
Prabir Pradhan664834b2021-05-20 16:00:42 -07002458 EXPECT_EQ(action, motionEvent.getAction());
Prabir Pradhanbd527712021-03-09 19:17:09 -08002459 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09002460
Prabir Pradhanbd527712021-03-09 19:17:09 -08002461 float expectedX = motionArgs.pointerCoords[0].getX();
2462 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09002463
Prabir Pradhanbd527712021-03-09 19:17:09 -08002464 // Ensure the axis values from the final motion event are not transformed.
2465 EXPECT_EQ(expectedX, motionEvent.getX(0))
2466 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2467 << motionEvent.getX(0);
2468 EXPECT_EQ(expectedY, motionEvent.getY(0))
2469 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2470 << motionEvent.getY(0);
2471 // Ensure the raw and transformed axis values for the motion event are the same.
2472 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2473 << "expected raw and transformed X-axis values to be equal";
2474 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2475 << "expected raw and transformed Y-axis values to be equal";
2476 }
yunho.shinf4a80b82020-11-16 21:13:57 +09002477}
2478
chaviw09c8d2d2020-08-24 15:48:26 -07002479/**
2480 * Ensure that separate calls to sign the same data are generating the same key.
2481 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2482 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2483 * tests.
2484 */
2485TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2486 KeyEvent event = getTestKeyEvent();
2487 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2488
2489 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2490 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2491 ASSERT_EQ(hmac1, hmac2);
2492}
2493
2494/**
2495 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2496 */
2497TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2498 KeyEvent event = getTestKeyEvent();
2499 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2500 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2501
2502 verifiedEvent.deviceId += 1;
2503 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2504
2505 verifiedEvent.source += 1;
2506 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2507
2508 verifiedEvent.eventTimeNanos += 1;
2509 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2510
2511 verifiedEvent.displayId += 1;
2512 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2513
2514 verifiedEvent.action += 1;
2515 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2516
2517 verifiedEvent.downTimeNanos += 1;
2518 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2519
2520 verifiedEvent.flags += 1;
2521 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2522
2523 verifiedEvent.keyCode += 1;
2524 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2525
2526 verifiedEvent.scanCode += 1;
2527 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2528
2529 verifiedEvent.metaState += 1;
2530 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2531
2532 verifiedEvent.repeatCount += 1;
2533 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2534}
2535
Vishnu Nair958da932020-08-21 17:12:37 -07002536TEST_F(InputDispatcherTest, SetFocusedWindow) {
2537 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2538 sp<FakeWindowHandle> windowTop =
2539 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2540 sp<FakeWindowHandle> windowSecond =
2541 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2542 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2543
2544 // Top window is also focusable but is not granted focus.
2545 windowTop->setFocusable(true);
2546 windowSecond->setFocusable(true);
2547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2548 setFocusedWindow(windowSecond);
2549
2550 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2552 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002553
2554 // Focused window should receive event.
2555 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2556 windowTop->assertNoEvents();
2557}
2558
2559TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2560 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2561 sp<FakeWindowHandle> window =
2562 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2563 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2564
2565 window->setFocusable(true);
2566 // Release channel for window is no longer valid.
2567 window->releaseChannel();
2568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2569 setFocusedWindow(window);
2570
2571 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002572 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2573 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002574
2575 // window channel is invalid, so it should not receive any input event.
2576 window->assertNoEvents();
2577}
2578
2579TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2580 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2581 sp<FakeWindowHandle> window =
2582 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2583 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2584
2585 // Window is not focusable.
2586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2587 setFocusedWindow(window);
2588
2589 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002590 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2591 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002592
2593 // window is invalid, so it should not receive any input event.
2594 window->assertNoEvents();
2595}
2596
2597TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2598 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2599 sp<FakeWindowHandle> windowTop =
2600 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2601 sp<FakeWindowHandle> windowSecond =
2602 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2603 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2604
2605 windowTop->setFocusable(true);
2606 windowSecond->setFocusable(true);
2607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2608 setFocusedWindow(windowTop);
2609 windowTop->consumeFocusEvent(true);
2610
2611 setFocusedWindow(windowSecond, windowTop);
2612 windowSecond->consumeFocusEvent(true);
2613 windowTop->consumeFocusEvent(false);
2614
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2616 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002617
2618 // Focused window should receive event.
2619 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2620}
2621
2622TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2623 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2624 sp<FakeWindowHandle> windowTop =
2625 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2626 sp<FakeWindowHandle> windowSecond =
2627 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2628 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2629
2630 windowTop->setFocusable(true);
2631 windowSecond->setFocusable(true);
2632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2633 setFocusedWindow(windowSecond, windowTop);
2634
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002635 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2636 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002637
2638 // Event should be dropped.
2639 windowTop->assertNoEvents();
2640 windowSecond->assertNoEvents();
2641}
2642
2643TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2644 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2645 sp<FakeWindowHandle> window =
2646 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2647 sp<FakeWindowHandle> previousFocusedWindow =
2648 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2649 ADISPLAY_ID_DEFAULT);
2650 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2651
2652 window->setFocusable(true);
2653 previousFocusedWindow->setFocusable(true);
2654 window->setVisible(false);
2655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2656 setFocusedWindow(previousFocusedWindow);
2657 previousFocusedWindow->consumeFocusEvent(true);
2658
2659 // Requesting focus on invisible window takes focus from currently focused window.
2660 setFocusedWindow(window);
2661 previousFocusedWindow->consumeFocusEvent(false);
2662
2663 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002665 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002666 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002667
2668 // Window does not get focus event or key down.
2669 window->assertNoEvents();
2670
2671 // Window becomes visible.
2672 window->setVisible(true);
2673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2674
2675 // Window receives focus event.
2676 window->consumeFocusEvent(true);
2677 // Focused window receives key down.
2678 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2679}
2680
Vishnu Nair599f1412021-06-21 10:39:58 -07002681TEST_F(InputDispatcherTest, DisplayRemoved) {
2682 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2683 sp<FakeWindowHandle> window =
2684 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
2685 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2686
2687 // window is granted focus.
2688 window->setFocusable(true);
2689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2690 setFocusedWindow(window);
2691 window->consumeFocusEvent(true);
2692
2693 // When a display is removed window loses focus.
2694 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
2695 window->consumeFocusEvent(false);
2696}
2697
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002698/**
2699 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2700 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2701 * of the 'slipperyEnterWindow'.
2702 *
2703 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2704 * a way so that the touched location is no longer covered by the top window.
2705 *
2706 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2707 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2708 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2709 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2710 * with ACTION_DOWN).
2711 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2712 * window moved itself away from the touched location and had Flag::SLIPPERY.
2713 *
2714 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2715 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2716 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2717 *
2718 * In this test, we ensure that the event received by the bottom window has
2719 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2720 */
2721TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2722 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2723 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2724
2725 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2726 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2727
2728 sp<FakeWindowHandle> slipperyExitWindow =
2729 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05002730 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002731 // Make sure this one overlaps the bottom window
2732 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2733 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2734 // one. Windows with the same owner are not considered to be occluding each other.
2735 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2736
2737 sp<FakeWindowHandle> slipperyEnterWindow =
2738 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2739 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2740
2741 mDispatcher->setInputWindows(
2742 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2743
2744 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2745 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2746 ADISPLAY_ID_DEFAULT, {{50, 50}});
2747 mDispatcher->notifyMotion(&args);
2748 slipperyExitWindow->consumeMotionDown();
2749 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2750 mDispatcher->setInputWindows(
2751 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2752
2753 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2754 ADISPLAY_ID_DEFAULT, {{51, 51}});
2755 mDispatcher->notifyMotion(&args);
2756
2757 slipperyExitWindow->consumeMotionCancel();
2758
2759 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2760 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2761}
2762
Garfield Tan1c7bc862020-01-28 13:24:04 -08002763class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2764protected:
2765 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2766 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2767
Chris Yea209fde2020-07-22 13:54:51 -07002768 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002769 sp<FakeWindowHandle> mWindow;
2770
2771 virtual void SetUp() override {
2772 mFakePolicy = new FakeInputDispatcherPolicy();
2773 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2774 mDispatcher = new InputDispatcher(mFakePolicy);
2775 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2776 ASSERT_EQ(OK, mDispatcher->start());
2777
2778 setUpWindow();
2779 }
2780
2781 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002782 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002783 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2784
Vishnu Nair47074b82020-08-14 11:54:47 -07002785 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002787 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002788 mWindow->consumeFocusEvent(true);
2789 }
2790
Chris Ye2ad95392020-09-01 13:44:44 -07002791 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002792 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002793 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002794 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2795 mDispatcher->notifyKey(&keyArgs);
2796
2797 // Window should receive key down event.
2798 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2799 }
2800
2801 void expectKeyRepeatOnce(int32_t repeatCount) {
2802 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2803 InputEvent* repeatEvent = mWindow->consume();
2804 ASSERT_NE(nullptr, repeatEvent);
2805
2806 uint32_t eventType = repeatEvent->getType();
2807 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2808
2809 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2810 uint32_t eventAction = repeatKeyEvent->getAction();
2811 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2812 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2813 }
2814
Chris Ye2ad95392020-09-01 13:44:44 -07002815 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002816 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002817 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002818 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2819 mDispatcher->notifyKey(&keyArgs);
2820
2821 // Window should receive key down event.
2822 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2823 0 /*expectedFlags*/);
2824 }
2825};
2826
2827TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002828 sendAndConsumeKeyDown(1 /* deviceId */);
2829 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2830 expectKeyRepeatOnce(repeatCount);
2831 }
2832}
2833
2834TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2835 sendAndConsumeKeyDown(1 /* deviceId */);
2836 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2837 expectKeyRepeatOnce(repeatCount);
2838 }
2839 sendAndConsumeKeyDown(2 /* deviceId */);
2840 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002841 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2842 expectKeyRepeatOnce(repeatCount);
2843 }
2844}
2845
2846TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002847 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002848 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002849 sendAndConsumeKeyUp(1 /* deviceId */);
2850 mWindow->assertNoEvents();
2851}
2852
2853TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2854 sendAndConsumeKeyDown(1 /* deviceId */);
2855 expectKeyRepeatOnce(1 /*repeatCount*/);
2856 sendAndConsumeKeyDown(2 /* deviceId */);
2857 expectKeyRepeatOnce(1 /*repeatCount*/);
2858 // Stale key up from device 1.
2859 sendAndConsumeKeyUp(1 /* deviceId */);
2860 // Device 2 is still down, keep repeating
2861 expectKeyRepeatOnce(2 /*repeatCount*/);
2862 expectKeyRepeatOnce(3 /*repeatCount*/);
2863 // Device 2 key up
2864 sendAndConsumeKeyUp(2 /* deviceId */);
2865 mWindow->assertNoEvents();
2866}
2867
2868TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2869 sendAndConsumeKeyDown(1 /* deviceId */);
2870 expectKeyRepeatOnce(1 /*repeatCount*/);
2871 sendAndConsumeKeyDown(2 /* deviceId */);
2872 expectKeyRepeatOnce(1 /*repeatCount*/);
2873 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2874 sendAndConsumeKeyUp(2 /* deviceId */);
2875 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002876 mWindow->assertNoEvents();
2877}
2878
2879TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002880 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002881 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2882 InputEvent* repeatEvent = mWindow->consume();
2883 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2884 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2885 IdGenerator::getSource(repeatEvent->getId()));
2886 }
2887}
2888
2889TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002890 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002891
2892 std::unordered_set<int32_t> idSet;
2893 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2894 InputEvent* repeatEvent = mWindow->consume();
2895 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2896 int32_t id = repeatEvent->getId();
2897 EXPECT_EQ(idSet.end(), idSet.find(id));
2898 idSet.insert(id);
2899 }
2900}
2901
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002902/* Test InputDispatcher for MultiDisplay */
2903class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2904public:
2905 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002906 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002907 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002908
Chris Yea209fde2020-07-22 13:54:51 -07002909 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002910 windowInPrimary =
2911 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002912
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002913 // Set focus window for primary display, but focused display would be second one.
2914 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002915 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002917 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002918 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002919
Chris Yea209fde2020-07-22 13:54:51 -07002920 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002921 windowInSecondary =
2922 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002923 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002924 // Set focus display to second one.
2925 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2926 // Set focus window for second display.
2927 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002928 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002929 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002930 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002931 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002932 }
2933
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002934 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002935 InputDispatcherTest::TearDown();
2936
Chris Yea209fde2020-07-22 13:54:51 -07002937 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002938 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002939 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002940 windowInSecondary.clear();
2941 }
2942
2943protected:
Chris Yea209fde2020-07-22 13:54:51 -07002944 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002945 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002946 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002947 sp<FakeWindowHandle> windowInSecondary;
2948};
2949
2950TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2951 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2953 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002955 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002956 windowInSecondary->assertNoEvents();
2957
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002958 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2961 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002962 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002963 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002964}
2965
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002966TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002967 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2969 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002970 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002971 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002972 windowInSecondary->assertNoEvents();
2973
2974 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002976 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002977 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002978 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002979
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002980 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002981 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002982
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002983 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002984 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2985 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002986
2987 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002988 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002989 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08002990 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002991 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002992 windowInSecondary->assertNoEvents();
2993}
2994
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002995// Test per-display input monitors for motion event.
2996TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002997 FakeMonitorReceiver monitorInPrimary =
2998 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2999 FakeMonitorReceiver monitorInSecondary =
3000 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003001
3002 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3004 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3005 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003006 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003007 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003008 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003009 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003010
3011 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003012 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3013 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3014 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003015 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003016 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003017 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003018 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003019
3020 // Test inject a non-pointer motion event.
3021 // If specific a display, it will dispatch to the focused window of particular display,
3022 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3024 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3025 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003026 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003027 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003028 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003029 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003030}
3031
3032// Test per-display input monitors for key event.
3033TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003034 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003035 FakeMonitorReceiver monitorInPrimary =
3036 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3037 FakeMonitorReceiver monitorInSecondary =
3038 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003039
3040 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003041 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3042 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003043 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003044 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003045 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003046 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003047}
3048
Vishnu Nair958da932020-08-21 17:12:37 -07003049TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3050 sp<FakeWindowHandle> secondWindowInPrimary =
3051 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3052 secondWindowInPrimary->setFocusable(true);
3053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3054 setFocusedWindow(secondWindowInPrimary);
3055 windowInPrimary->consumeFocusEvent(false);
3056 secondWindowInPrimary->consumeFocusEvent(true);
3057
3058 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3060 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003061 windowInPrimary->assertNoEvents();
3062 windowInSecondary->assertNoEvents();
3063 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3064}
3065
Jackal Guof9696682018-10-05 12:23:23 +08003066class InputFilterTest : public InputDispatcherTest {
3067protected:
3068 static constexpr int32_t SECOND_DISPLAY_ID = 1;
3069
3070 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
3071 NotifyMotionArgs motionArgs;
3072
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003073 motionArgs =
3074 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003075 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003076 motionArgs =
3077 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003078 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003079 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003080 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003081 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003082 } else {
3083 mFakePolicy->assertFilterInputEventWasNotCalled();
3084 }
3085 }
3086
3087 void testNotifyKey(bool expectToBeFiltered) {
3088 NotifyKeyArgs keyArgs;
3089
3090 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3091 mDispatcher->notifyKey(&keyArgs);
3092 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3093 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003094 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003095
3096 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003097 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003098 } else {
3099 mFakePolicy->assertFilterInputEventWasNotCalled();
3100 }
3101 }
3102};
3103
3104// Test InputFilter for MotionEvent
3105TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3106 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3107 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3108 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3109
3110 // Enable InputFilter
3111 mDispatcher->setInputFilterEnabled(true);
3112 // Test touch on both primary and second display, and check if both events are filtered.
3113 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3114 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3115
3116 // Disable InputFilter
3117 mDispatcher->setInputFilterEnabled(false);
3118 // Test touch on both primary and second display, and check if both events aren't filtered.
3119 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3120 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3121}
3122
3123// Test InputFilter for KeyEvent
3124TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3125 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3126 testNotifyKey(/*expectToBeFiltered*/ false);
3127
3128 // Enable InputFilter
3129 mDispatcher->setInputFilterEnabled(true);
3130 // Send a key event, and check if it is filtered.
3131 testNotifyKey(/*expectToBeFiltered*/ true);
3132
3133 // Disable InputFilter
3134 mDispatcher->setInputFilterEnabled(false);
3135 // Send a key event, and check if it isn't filtered.
3136 testNotifyKey(/*expectToBeFiltered*/ false);
3137}
3138
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003139class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3140protected:
3141 virtual void SetUp() override {
3142 InputDispatcherTest::SetUp();
3143
3144 /**
3145 * We don't need to enable input filter to test the injected event policy, but we enabled it
3146 * here to make the tests more realistic, since this policy only matters when inputfilter is
3147 * on.
3148 */
3149 mDispatcher->setInputFilterEnabled(true);
3150
3151 std::shared_ptr<InputApplicationHandle> application =
3152 std::make_shared<FakeApplicationHandle>();
3153 mWindow =
3154 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3155
3156 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3157 mWindow->setFocusable(true);
3158 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3159 setFocusedWindow(mWindow);
3160 mWindow->consumeFocusEvent(true);
3161 }
3162
3163 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId) {
3164 KeyEvent event;
3165
3166 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3167 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3168 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3169 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3170 const int32_t additionalPolicyFlags =
3171 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3172 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3173 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3174 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3175 policyFlags | additionalPolicyFlags));
3176
3177 InputEvent* received = mWindow->consume();
3178 ASSERT_NE(nullptr, received);
3179 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3180 }
3181
3182private:
3183 sp<FakeWindowHandle> mWindow;
3184};
3185
3186TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
3187 // We don't need POLICY_FLAG_FILTERED here, but it will be set in practice, so keep it to make
3188 // the test more closely resemble the real usage
3189 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INPUTFILTER_TRUSTED, 3 /*injectedDeviceId*/,
3190 3 /*resolvedDeviceId*/);
3191}
3192
3193TEST_F(InputFilterInjectionPolicyTest, EventsInjectedFromAccessibility_HaveAccessibilityDeviceId) {
3194 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3195 3 /*injectedDeviceId*/, ACCESSIBILITY_DEVICE_ID /*resolvedDeviceId*/);
3196}
3197
3198TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3199 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
3200 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/);
3201}
3202
chaviwfd6d3512019-03-25 13:23:49 -07003203class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003204 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003205 InputDispatcherTest::SetUp();
3206
Chris Yea209fde2020-07-22 13:54:51 -07003207 std::shared_ptr<FakeApplicationHandle> application =
3208 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003209 mUnfocusedWindow =
3210 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003211 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3212 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3213 // window.
chaviw3277faf2021-05-19 16:45:23 -05003214 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003215
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003216 mFocusedWindow =
3217 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3218 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003219 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003220
3221 // Set focused application.
3222 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003223 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003224
3225 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003227 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003228 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003229 }
3230
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003231 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003232 InputDispatcherTest::TearDown();
3233
3234 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003235 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003236 }
3237
3238protected:
3239 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003240 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003241 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003242};
3243
3244// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3245// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3246// the onPointerDownOutsideFocus callback.
3247TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003248 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003249 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3250 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003251 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003252 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003253
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003254 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003255 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3256}
3257
3258// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3259// DOWN on the window that doesn't have focus. Ensure no window received the
3260// onPointerDownOutsideFocus callback.
3261TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003263 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003264 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003265 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003266
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003267 ASSERT_TRUE(mDispatcher->waitForIdle());
3268 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003269}
3270
3271// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3272// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3273TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003274 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3275 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003276 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003277 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003278
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003279 ASSERT_TRUE(mDispatcher->waitForIdle());
3280 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003281}
3282
3283// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3284// DOWN on the window that already has focus. Ensure no window received the
3285// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003286TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003288 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003289 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003290 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003291 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003292
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003293 ASSERT_TRUE(mDispatcher->waitForIdle());
3294 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003295}
3296
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003297// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3298// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3299TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3300 const MotionEvent event =
3301 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3302 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3303 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3304 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3305 .build();
3306 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3307 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3308 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3309
3310 ASSERT_TRUE(mDispatcher->waitForIdle());
3311 mFakePolicy->assertOnPointerDownWasNotCalled();
3312 // Ensure that the unfocused window did not receive any FOCUS events.
3313 mUnfocusedWindow->assertNoEvents();
3314}
3315
chaviwaf87b3e2019-10-01 16:59:28 -07003316// These tests ensures we can send touch events to a single client when there are multiple input
3317// windows that point to the same client token.
3318class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3319 virtual void SetUp() override {
3320 InputDispatcherTest::SetUp();
3321
Chris Yea209fde2020-07-22 13:54:51 -07003322 std::shared_ptr<FakeApplicationHandle> application =
3323 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003324 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3325 ADISPLAY_ID_DEFAULT);
3326 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3327 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003328 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003329 mWindow1->setFrame(Rect(0, 0, 100, 100));
3330
3331 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3332 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003333 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003334 mWindow2->setFrame(Rect(100, 100, 200, 200));
3335
Arthur Hung72d8dc32020-03-28 00:48:39 +00003336 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003337 }
3338
3339protected:
3340 sp<FakeWindowHandle> mWindow1;
3341 sp<FakeWindowHandle> mWindow2;
3342
3343 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05003344 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003345 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3346 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003347 }
3348
3349 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3350 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003351 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003352 InputEvent* event = window->consume();
3353
3354 ASSERT_NE(nullptr, event) << name.c_str()
3355 << ": consumer should have returned non-NULL event.";
3356
3357 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3358 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3359 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3360
3361 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3362 EXPECT_EQ(expectedAction, motionEvent.getAction());
3363
3364 for (size_t i = 0; i < points.size(); i++) {
3365 float expectedX = points[i].x;
3366 float expectedY = points[i].y;
3367
3368 EXPECT_EQ(expectedX, motionEvent.getX(i))
3369 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3370 << ", got " << motionEvent.getX(i);
3371 EXPECT_EQ(expectedY, motionEvent.getY(i))
3372 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3373 << ", got " << motionEvent.getY(i);
3374 }
3375 }
chaviw9eaa22c2020-07-01 16:21:27 -07003376
3377 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3378 std::vector<PointF> expectedPoints) {
3379 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3380 ADISPLAY_ID_DEFAULT, touchedPoints);
3381 mDispatcher->notifyMotion(&motionArgs);
3382
3383 // Always consume from window1 since it's the window that has the InputReceiver
3384 consumeMotionEvent(mWindow1, action, expectedPoints);
3385 }
chaviwaf87b3e2019-10-01 16:59:28 -07003386};
3387
3388TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3389 // Touch Window 1
3390 PointF touchedPoint = {10, 10};
3391 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003392 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003393
3394 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003395 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003396
3397 // Touch Window 2
3398 touchedPoint = {150, 150};
3399 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003400 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003401}
3402
chaviw9eaa22c2020-07-01 16:21:27 -07003403TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3404 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003405 mWindow2->setWindowScale(0.5f, 0.5f);
3406
3407 // Touch Window 1
3408 PointF touchedPoint = {10, 10};
3409 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003410 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003411 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003412 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003413
3414 // Touch Window 2
3415 touchedPoint = {150, 150};
3416 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003417 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3418 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003419
chaviw9eaa22c2020-07-01 16:21:27 -07003420 // Update the transform so rotation is set
3421 mWindow2->setWindowTransform(0, -1, 1, 0);
3422 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3423 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003424}
3425
chaviw9eaa22c2020-07-01 16:21:27 -07003426TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003427 mWindow2->setWindowScale(0.5f, 0.5f);
3428
3429 // Touch Window 1
3430 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3431 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003432 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003433
3434 // Touch Window 2
3435 int32_t actionPointerDown =
3436 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003437 touchedPoints.push_back(PointF{150, 150});
3438 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3439 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003440
chaviw9eaa22c2020-07-01 16:21:27 -07003441 // Release Window 2
3442 int32_t actionPointerUp =
3443 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3444 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3445 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003446
chaviw9eaa22c2020-07-01 16:21:27 -07003447 // Update the transform so rotation is set for Window 2
3448 mWindow2->setWindowTransform(0, -1, 1, 0);
3449 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3450 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003451}
3452
chaviw9eaa22c2020-07-01 16:21:27 -07003453TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003454 mWindow2->setWindowScale(0.5f, 0.5f);
3455
3456 // Touch Window 1
3457 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3458 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003459 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003460
3461 // Touch Window 2
3462 int32_t actionPointerDown =
3463 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003464 touchedPoints.push_back(PointF{150, 150});
3465 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003466
chaviw9eaa22c2020-07-01 16:21:27 -07003467 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003468
3469 // Move both windows
3470 touchedPoints = {{20, 20}, {175, 175}};
3471 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3472 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3473
chaviw9eaa22c2020-07-01 16:21:27 -07003474 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003475
chaviw9eaa22c2020-07-01 16:21:27 -07003476 // Release Window 2
3477 int32_t actionPointerUp =
3478 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3479 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3480 expectedPoints.pop_back();
3481
3482 // Touch Window 2
3483 mWindow2->setWindowTransform(0, -1, 1, 0);
3484 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3485 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3486
3487 // Move both windows
3488 touchedPoints = {{20, 20}, {175, 175}};
3489 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3490 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3491
3492 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003493}
3494
3495TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3496 mWindow1->setWindowScale(0.5f, 0.5f);
3497
3498 // Touch Window 1
3499 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3500 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003501 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003502
3503 // Touch Window 2
3504 int32_t actionPointerDown =
3505 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003506 touchedPoints.push_back(PointF{150, 150});
3507 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003508
chaviw9eaa22c2020-07-01 16:21:27 -07003509 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003510
3511 // Move both windows
3512 touchedPoints = {{20, 20}, {175, 175}};
3513 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3514 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3515
chaviw9eaa22c2020-07-01 16:21:27 -07003516 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003517}
3518
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003519class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3520 virtual void SetUp() override {
3521 InputDispatcherTest::SetUp();
3522
Chris Yea209fde2020-07-22 13:54:51 -07003523 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003524 mApplication->setDispatchingTimeout(20ms);
3525 mWindow =
3526 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3527 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003528 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003529 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003530 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3531 // window.
chaviw3277faf2021-05-19 16:45:23 -05003532 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003533
3534 // Set focused application.
3535 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3536
3537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003538 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003539 mWindow->consumeFocusEvent(true);
3540 }
3541
3542 virtual void TearDown() override {
3543 InputDispatcherTest::TearDown();
3544 mWindow.clear();
3545 }
3546
3547protected:
Chris Yea209fde2020-07-22 13:54:51 -07003548 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003549 sp<FakeWindowHandle> mWindow;
3550 static constexpr PointF WINDOW_LOCATION = {20, 20};
3551
3552 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003554 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3555 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003557 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3558 WINDOW_LOCATION));
3559 }
3560};
3561
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003562// Send a tap and respond, which should not cause an ANR.
3563TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3564 tapOnWindow();
3565 mWindow->consumeMotionDown();
3566 mWindow->consumeMotionUp();
3567 ASSERT_TRUE(mDispatcher->waitForIdle());
3568 mFakePolicy->assertNotifyAnrWasNotCalled();
3569}
3570
3571// Send a regular key and respond, which should not cause an ANR.
3572TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003573 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003574 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3575 ASSERT_TRUE(mDispatcher->waitForIdle());
3576 mFakePolicy->assertNotifyAnrWasNotCalled();
3577}
3578
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003579TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3580 mWindow->setFocusable(false);
3581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3582 mWindow->consumeFocusEvent(false);
3583
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003584 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003585 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003586 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3587 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003589 // Key will not go to window because we have no focused window.
3590 // The 'no focused window' ANR timer should start instead.
3591
3592 // Now, the focused application goes away.
3593 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3594 // The key should get dropped and there should be no ANR.
3595
3596 ASSERT_TRUE(mDispatcher->waitForIdle());
3597 mFakePolicy->assertNotifyAnrWasNotCalled();
3598}
3599
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003600// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003601// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3602// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003603TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003605 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3606 WINDOW_LOCATION));
3607
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003608 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3609 ASSERT_TRUE(sequenceNum);
3610 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003611 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003612
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003613 mWindow->finishEvent(*sequenceNum);
3614 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3615 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003616 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003617 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003618}
3619
3620// Send a key to the app and have the app not respond right away.
3621TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3622 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003624 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3625 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003626 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003627 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003628 ASSERT_TRUE(mDispatcher->waitForIdle());
3629}
3630
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003631// We have a focused application, but no focused window
3632TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003633 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3635 mWindow->consumeFocusEvent(false);
3636
3637 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003639 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3640 WINDOW_LOCATION));
3641 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3642 mDispatcher->waitForIdle();
3643 mFakePolicy->assertNotifyAnrWasNotCalled();
3644
3645 // Once a focused event arrives, we get an ANR for this application
3646 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3647 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003648 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003649 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003650 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003651 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003652 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003653 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003654 ASSERT_TRUE(mDispatcher->waitForIdle());
3655}
3656
3657// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003658// Make sure that we don't notify policy twice about the same ANR.
3659TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003660 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3662 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003663
3664 // Once a focused event arrives, we get an ANR for this application
3665 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3666 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003667 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003668 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003669 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003670 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003671 const std::chrono::duration appTimeout =
3672 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003673 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003674
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003675 std::this_thread::sleep_for(appTimeout);
3676 // ANR should not be raised again. It is up to policy to do that if it desires.
3677 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003678
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003679 // If we now get a focused window, the ANR should stop, but the policy handles that via
3680 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003681 ASSERT_TRUE(mDispatcher->waitForIdle());
3682}
3683
3684// We have a focused application, but no focused window
3685TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003686 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3688 mWindow->consumeFocusEvent(false);
3689
3690 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003691 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003692 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003693 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3694 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003695
3696 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003697 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003698
3699 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003700 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003701 ASSERT_TRUE(mDispatcher->waitForIdle());
3702 mWindow->assertNoEvents();
3703}
3704
3705/**
3706 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3707 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3708 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3709 * the ANR mechanism should still work.
3710 *
3711 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3712 * DOWN event, while not responding on the second one.
3713 */
3714TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3715 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3716 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3717 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3718 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3719 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003720 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003721
3722 // Now send ACTION_UP, with identical timestamp
3723 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3724 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3725 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3726 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003727 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003728
3729 // We have now sent down and up. Let's consume first event and then ANR on the second.
3730 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3731 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003732 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003733}
3734
3735// If an app is not responding to a key event, gesture monitors should continue to receive
3736// new motion events
3737TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3738 FakeMonitorReceiver monitor =
3739 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3740 true /*isGestureMonitor*/);
3741
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003742 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3743 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003744 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003746
3747 // Stuck on the ACTION_UP
3748 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003749 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003750
3751 // New tap will go to the gesture monitor, but not to the window
3752 tapOnWindow();
3753 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3754 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3755
3756 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3757 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003758 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003759 mWindow->assertNoEvents();
3760 monitor.assertNoEvents();
3761}
3762
3763// If an app is not responding to a motion event, gesture monitors should continue to receive
3764// new motion events
3765TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3766 FakeMonitorReceiver monitor =
3767 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3768 true /*isGestureMonitor*/);
3769
3770 tapOnWindow();
3771 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3772 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3773
3774 mWindow->consumeMotionDown();
3775 // Stuck on the ACTION_UP
3776 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003777 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003778
3779 // New tap will go to the gesture monitor, but not to the window
3780 tapOnWindow();
3781 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3782 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3783
3784 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3785 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003786 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003787 mWindow->assertNoEvents();
3788 monitor.assertNoEvents();
3789}
3790
3791// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3792// process events, you don't get an anr. When the window later becomes unresponsive again, you
3793// get an ANR again.
3794// 1. tap -> block on ACTION_UP -> receive ANR
3795// 2. consume all pending events (= queue becomes healthy again)
3796// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3797TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3798 tapOnWindow();
3799
3800 mWindow->consumeMotionDown();
3801 // Block on ACTION_UP
3802 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003803 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003804 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3805 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003806 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003807 mWindow->assertNoEvents();
3808
3809 tapOnWindow();
3810 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003811 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003812 mWindow->consumeMotionUp();
3813
3814 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003815 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003816 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003817 mWindow->assertNoEvents();
3818}
3819
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003820// If a connection remains unresponsive for a while, make sure policy is only notified once about
3821// it.
3822TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003824 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3825 WINDOW_LOCATION));
3826
3827 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003828 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003829 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003830 // 'notifyConnectionUnresponsive' should only be called once per connection
3831 mFakePolicy->assertNotifyAnrWasNotCalled();
3832 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003833 mWindow->consumeMotionDown();
3834 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3835 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3836 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003837 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003838 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003839 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003840}
3841
3842/**
3843 * If a window is processing a motion event, and then a key event comes in, the key event should
3844 * not to to the focused window until the motion is processed.
3845 *
3846 * Warning!!!
3847 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3848 * and the injection timeout that we specify when injecting the key.
3849 * We must have the injection timeout (10ms) be smaller than
3850 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3851 *
3852 * If that value changes, this test should also change.
3853 */
3854TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3855 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3856 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3857
3858 tapOnWindow();
3859 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3860 ASSERT_TRUE(downSequenceNum);
3861 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3862 ASSERT_TRUE(upSequenceNum);
3863 // Don't finish the events yet, and send a key
3864 // Injection will "succeed" because we will eventually give up and send the key to the focused
3865 // window even if motions are still being processed. But because the injection timeout is short,
3866 // we will receive INJECTION_TIMED_OUT as the result.
3867
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003868 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003869 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003870 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3871 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003872 // Key will not be sent to the window, yet, because the window is still processing events
3873 // and the key remains pending, waiting for the touch events to be processed
3874 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3875 ASSERT_FALSE(keySequenceNum);
3876
3877 std::this_thread::sleep_for(500ms);
3878 // if we wait long enough though, dispatcher will give up, and still send the key
3879 // to the focused window, even though we have not yet finished the motion event
3880 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3881 mWindow->finishEvent(*downSequenceNum);
3882 mWindow->finishEvent(*upSequenceNum);
3883}
3884
3885/**
3886 * If a window is processing a motion event, and then a key event comes in, the key event should
3887 * not go to the focused window until the motion is processed.
3888 * If then a new motion comes in, then the pending key event should be going to the currently
3889 * focused window right away.
3890 */
3891TEST_F(InputDispatcherSingleWindowAnr,
3892 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3893 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3895
3896 tapOnWindow();
3897 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3898 ASSERT_TRUE(downSequenceNum);
3899 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3900 ASSERT_TRUE(upSequenceNum);
3901 // Don't finish the events yet, and send a key
3902 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003904 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003905 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003906 // At this point, key is still pending, and should not be sent to the application yet.
3907 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3908 ASSERT_FALSE(keySequenceNum);
3909
3910 // Now tap down again. It should cause the pending key to go to the focused window right away.
3911 tapOnWindow();
3912 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3913 // the other events yet. We can finish events in any order.
3914 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3915 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3916 mWindow->consumeMotionDown();
3917 mWindow->consumeMotionUp();
3918 mWindow->assertNoEvents();
3919}
3920
3921class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3922 virtual void SetUp() override {
3923 InputDispatcherTest::SetUp();
3924
Chris Yea209fde2020-07-22 13:54:51 -07003925 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003926 mApplication->setDispatchingTimeout(10ms);
3927 mUnfocusedWindow =
3928 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3929 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3930 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3931 // window.
3932 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05003933 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
3934 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3935 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003936
3937 mFocusedWindow =
3938 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003939 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003940 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003941 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003942
3943 // Set focused application.
3944 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003945 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003946
3947 // Expect one focus window exist in display.
3948 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003949 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003950 mFocusedWindow->consumeFocusEvent(true);
3951 }
3952
3953 virtual void TearDown() override {
3954 InputDispatcherTest::TearDown();
3955
3956 mUnfocusedWindow.clear();
3957 mFocusedWindow.clear();
3958 }
3959
3960protected:
Chris Yea209fde2020-07-22 13:54:51 -07003961 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003962 sp<FakeWindowHandle> mUnfocusedWindow;
3963 sp<FakeWindowHandle> mFocusedWindow;
3964 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3965 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3966 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3967
3968 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3969
3970 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3971
3972private:
3973 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003975 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3976 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003977 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003978 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3979 location));
3980 }
3981};
3982
3983// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3984// should be ANR'd first.
3985TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003986 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003987 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3988 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003989 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003990 mFocusedWindow->consumeMotionDown();
3991 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3992 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3993 // We consumed all events, so no ANR
3994 ASSERT_TRUE(mDispatcher->waitForIdle());
3995 mFakePolicy->assertNotifyAnrWasNotCalled();
3996
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003997 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003998 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3999 FOCUSED_WINDOW_LOCATION));
4000 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4001 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004002
4003 const std::chrono::duration timeout =
4004 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004005 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004006 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4007 // sequence to make it consistent
4008 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004009 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004010 mFocusedWindow->consumeMotionDown();
4011 // This cancel is generated because the connection was unresponsive
4012 mFocusedWindow->consumeMotionCancel();
4013 mFocusedWindow->assertNoEvents();
4014 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004015 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004016 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004017 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004018}
4019
4020// If we have 2 windows with identical timeouts that are both unresponsive,
4021// it doesn't matter which order they should have ANR.
4022// But we should receive ANR for both.
4023TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4024 // Set the timeout for unfocused window to match the focused window
4025 mUnfocusedWindow->setDispatchingTimeout(10ms);
4026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4027
4028 tapOnFocusedWindow();
4029 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004030 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4031 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004032
4033 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004034 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4035 mFocusedWindow->getToken() == anrConnectionToken2);
4036 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4037 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004038
4039 ASSERT_TRUE(mDispatcher->waitForIdle());
4040 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004041
4042 mFocusedWindow->consumeMotionDown();
4043 mFocusedWindow->consumeMotionUp();
4044 mUnfocusedWindow->consumeMotionOutside();
4045
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004046 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4047 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004048
4049 // Both applications should be marked as responsive, in any order
4050 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4051 mFocusedWindow->getToken() == responsiveToken2);
4052 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4053 mUnfocusedWindow->getToken() == responsiveToken2);
4054 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004055}
4056
4057// If a window is already not responding, the second tap on the same window should be ignored.
4058// We should also log an error to account for the dropped event (not tested here).
4059// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4060TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4061 tapOnFocusedWindow();
4062 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4063 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4064 // Receive the events, but don't respond
4065 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4066 ASSERT_TRUE(downEventSequenceNum);
4067 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4068 ASSERT_TRUE(upEventSequenceNum);
4069 const std::chrono::duration timeout =
4070 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004071 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004072
4073 // Tap once again
4074 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004075 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004076 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4077 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004078 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004079 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4080 FOCUSED_WINDOW_LOCATION));
4081 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4082 // valid touch target
4083 mUnfocusedWindow->assertNoEvents();
4084
4085 // Consume the first tap
4086 mFocusedWindow->finishEvent(*downEventSequenceNum);
4087 mFocusedWindow->finishEvent(*upEventSequenceNum);
4088 ASSERT_TRUE(mDispatcher->waitForIdle());
4089 // The second tap did not go to the focused window
4090 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004091 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004092 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004093 mFakePolicy->assertNotifyAnrWasNotCalled();
4094}
4095
4096// If you tap outside of all windows, there will not be ANR
4097TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004098 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004099 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4100 LOCATION_OUTSIDE_ALL_WINDOWS));
4101 ASSERT_TRUE(mDispatcher->waitForIdle());
4102 mFakePolicy->assertNotifyAnrWasNotCalled();
4103}
4104
4105// Since the focused window is paused, tapping on it should not produce any events
4106TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4107 mFocusedWindow->setPaused(true);
4108 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4109
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004110 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004111 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4112 FOCUSED_WINDOW_LOCATION));
4113
4114 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4115 ASSERT_TRUE(mDispatcher->waitForIdle());
4116 // Should not ANR because the window is paused, and touches shouldn't go to it
4117 mFakePolicy->assertNotifyAnrWasNotCalled();
4118
4119 mFocusedWindow->assertNoEvents();
4120 mUnfocusedWindow->assertNoEvents();
4121}
4122
4123/**
4124 * If a window is processing a motion event, and then a key event comes in, the key event should
4125 * not to to the focused window until the motion is processed.
4126 * If a different window becomes focused at this time, the key should go to that window instead.
4127 *
4128 * Warning!!!
4129 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4130 * and the injection timeout that we specify when injecting the key.
4131 * We must have the injection timeout (10ms) be smaller than
4132 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4133 *
4134 * If that value changes, this test should also change.
4135 */
4136TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4137 // Set a long ANR timeout to prevent it from triggering
4138 mFocusedWindow->setDispatchingTimeout(2s);
4139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4140
4141 tapOnUnfocusedWindow();
4142 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4143 ASSERT_TRUE(downSequenceNum);
4144 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4145 ASSERT_TRUE(upSequenceNum);
4146 // Don't finish the events yet, and send a key
4147 // Injection will succeed because we will eventually give up and send the key to the focused
4148 // window even if motions are still being processed.
4149
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004150 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004151 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004152 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004154 // Key will not be sent to the window, yet, because the window is still processing events
4155 // and the key remains pending, waiting for the touch events to be processed
4156 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4157 ASSERT_FALSE(keySequenceNum);
4158
4159 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004160 mFocusedWindow->setFocusable(false);
4161 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004162 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004163 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004164
4165 // Focus events should precede the key events
4166 mUnfocusedWindow->consumeFocusEvent(true);
4167 mFocusedWindow->consumeFocusEvent(false);
4168
4169 // Finish the tap events, which should unblock dispatcher
4170 mUnfocusedWindow->finishEvent(*downSequenceNum);
4171 mUnfocusedWindow->finishEvent(*upSequenceNum);
4172
4173 // Now that all queues are cleared and no backlog in the connections, the key event
4174 // can finally go to the newly focused "mUnfocusedWindow".
4175 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4176 mFocusedWindow->assertNoEvents();
4177 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004178 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004179}
4180
4181// When the touch stream is split across 2 windows, and one of them does not respond,
4182// then ANR should be raised and the touch should be canceled for the unresponsive window.
4183// The other window should not be affected by that.
4184TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4185 // Touch Window 1
4186 NotifyMotionArgs motionArgs =
4187 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4188 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4189 mDispatcher->notifyMotion(&motionArgs);
4190 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4191 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4192
4193 // Touch Window 2
4194 int32_t actionPointerDown =
4195 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4196
4197 motionArgs =
4198 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4199 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4200 mDispatcher->notifyMotion(&motionArgs);
4201
4202 const std::chrono::duration timeout =
4203 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004204 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004205
4206 mUnfocusedWindow->consumeMotionDown();
4207 mFocusedWindow->consumeMotionDown();
4208 // Focused window may or may not receive ACTION_MOVE
4209 // But it should definitely receive ACTION_CANCEL due to the ANR
4210 InputEvent* event;
4211 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4212 ASSERT_TRUE(moveOrCancelSequenceNum);
4213 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4214 ASSERT_NE(nullptr, event);
4215 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4216 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4217 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4218 mFocusedWindow->consumeMotionCancel();
4219 } else {
4220 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4221 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004222 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004223 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004224
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004225 mUnfocusedWindow->assertNoEvents();
4226 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004227 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004228}
4229
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004230/**
4231 * If we have no focused window, and a key comes in, we start the ANR timer.
4232 * The focused application should add a focused window before the timer runs out to prevent ANR.
4233 *
4234 * If the user touches another application during this time, the key should be dropped.
4235 * Next, if a new focused window comes in, without toggling the focused application,
4236 * then no ANR should occur.
4237 *
4238 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4239 * but in some cases the policy may not update the focused application.
4240 */
4241TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4242 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4243 std::make_shared<FakeApplicationHandle>();
4244 focusedApplication->setDispatchingTimeout(60ms);
4245 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4246 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4247 mFocusedWindow->setFocusable(false);
4248
4249 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4250 mFocusedWindow->consumeFocusEvent(false);
4251
4252 // Send a key. The ANR timer should start because there is no focused window.
4253 // 'focusedApplication' will get blamed if this timer completes.
4254 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004255 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004256 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004257 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4258 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004259 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004260
4261 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4262 // then the injected touches won't cause the focused event to get dropped.
4263 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4264 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4265 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4266 // For this test, it means that the key would get delivered to the window once it becomes
4267 // focused.
4268 std::this_thread::sleep_for(10ms);
4269
4270 // Touch unfocused window. This should force the pending key to get dropped.
4271 NotifyMotionArgs motionArgs =
4272 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4273 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4274 mDispatcher->notifyMotion(&motionArgs);
4275
4276 // We do not consume the motion right away, because that would require dispatcher to first
4277 // process (== drop) the key event, and by that time, ANR will be raised.
4278 // Set the focused window first.
4279 mFocusedWindow->setFocusable(true);
4280 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4281 setFocusedWindow(mFocusedWindow);
4282 mFocusedWindow->consumeFocusEvent(true);
4283 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4284 // to another application. This could be a bug / behaviour in the policy.
4285
4286 mUnfocusedWindow->consumeMotionDown();
4287
4288 ASSERT_TRUE(mDispatcher->waitForIdle());
4289 // Should not ANR because we actually have a focused window. It was just added too slowly.
4290 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4291}
4292
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004293// These tests ensure we cannot send touch events to a window that's positioned behind a window
4294// that has feature NO_INPUT_CHANNEL.
4295// Layout:
4296// Top (closest to user)
4297// mNoInputWindow (above all windows)
4298// mBottomWindow
4299// Bottom (furthest from user)
4300class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4301 virtual void SetUp() override {
4302 InputDispatcherTest::SetUp();
4303
4304 mApplication = std::make_shared<FakeApplicationHandle>();
4305 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4306 "Window without input channel", ADISPLAY_ID_DEFAULT,
4307 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4308
chaviw3277faf2021-05-19 16:45:23 -05004309 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004310 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4311 // It's perfectly valid for this window to not have an associated input channel
4312
4313 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4314 ADISPLAY_ID_DEFAULT);
4315 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4316
4317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4318 }
4319
4320protected:
4321 std::shared_ptr<FakeApplicationHandle> mApplication;
4322 sp<FakeWindowHandle> mNoInputWindow;
4323 sp<FakeWindowHandle> mBottomWindow;
4324};
4325
4326TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4327 PointF touchedPoint = {10, 10};
4328
4329 NotifyMotionArgs motionArgs =
4330 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4331 ADISPLAY_ID_DEFAULT, {touchedPoint});
4332 mDispatcher->notifyMotion(&motionArgs);
4333
4334 mNoInputWindow->assertNoEvents();
4335 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4336 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4337 // and therefore should prevent mBottomWindow from receiving touches
4338 mBottomWindow->assertNoEvents();
4339}
4340
4341/**
4342 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4343 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4344 */
4345TEST_F(InputDispatcherMultiWindowOcclusionTests,
4346 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4347 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4348 "Window with input channel and NO_INPUT_CHANNEL",
4349 ADISPLAY_ID_DEFAULT);
4350
chaviw3277faf2021-05-19 16:45:23 -05004351 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004352 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4353 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4354
4355 PointF touchedPoint = {10, 10};
4356
4357 NotifyMotionArgs motionArgs =
4358 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4359 ADISPLAY_ID_DEFAULT, {touchedPoint});
4360 mDispatcher->notifyMotion(&motionArgs);
4361
4362 mNoInputWindow->assertNoEvents();
4363 mBottomWindow->assertNoEvents();
4364}
4365
Vishnu Nair958da932020-08-21 17:12:37 -07004366class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4367protected:
4368 std::shared_ptr<FakeApplicationHandle> mApp;
4369 sp<FakeWindowHandle> mWindow;
4370 sp<FakeWindowHandle> mMirror;
4371
4372 virtual void SetUp() override {
4373 InputDispatcherTest::SetUp();
4374 mApp = std::make_shared<FakeApplicationHandle>();
4375 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4376 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4377 mWindow->getToken());
4378 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4379 mWindow->setFocusable(true);
4380 mMirror->setFocusable(true);
4381 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4382 }
4383};
4384
4385TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4386 // Request focus on a mirrored window
4387 setFocusedWindow(mMirror);
4388
4389 // window gets focused
4390 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4392 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004393 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4394}
4395
4396// A focused & mirrored window remains focused only if the window and its mirror are both
4397// focusable.
4398TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4399 setFocusedWindow(mMirror);
4400
4401 // window gets focused
4402 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4404 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004405 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4407 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004408 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4409
4410 mMirror->setFocusable(false);
4411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4412
4413 // window loses focus since one of the windows associated with the token in not focusable
4414 mWindow->consumeFocusEvent(false);
4415
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4417 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004418 mWindow->assertNoEvents();
4419}
4420
4421// A focused & mirrored window remains focused until the window and its mirror both become
4422// invisible.
4423TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4424 setFocusedWindow(mMirror);
4425
4426 // window gets focused
4427 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4429 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004430 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4432 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004433 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4434
4435 mMirror->setVisible(false);
4436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4437
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4439 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004440 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4442 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004443 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4444
4445 mWindow->setVisible(false);
4446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4447
4448 // window loses focus only after all windows associated with the token become invisible.
4449 mWindow->consumeFocusEvent(false);
4450
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4452 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004453 mWindow->assertNoEvents();
4454}
4455
4456// A focused & mirrored window remains focused until both windows are removed.
4457TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4458 setFocusedWindow(mMirror);
4459
4460 // window gets focused
4461 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004462 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4463 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004464 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004465 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4466 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004467 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4468
4469 // single window is removed but the window token remains focused
4470 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4471
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4473 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004474 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004475 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4476 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004477 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4478
4479 // Both windows are removed
4480 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4481 mWindow->consumeFocusEvent(false);
4482
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004483 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4484 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004485 mWindow->assertNoEvents();
4486}
4487
4488// Focus request can be pending until one window becomes visible.
4489TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4490 // Request focus on an invisible mirror.
4491 mWindow->setVisible(false);
4492 mMirror->setVisible(false);
4493 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4494 setFocusedWindow(mMirror);
4495
4496 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004497 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004498 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004499 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004500
4501 mMirror->setVisible(true);
4502 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4503
4504 // window gets focused
4505 mWindow->consumeFocusEvent(true);
4506 // window gets the pending key event
4507 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4508}
Prabir Pradhan99987712020-11-10 18:43:05 -08004509
4510class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4511protected:
4512 std::shared_ptr<FakeApplicationHandle> mApp;
4513 sp<FakeWindowHandle> mWindow;
4514 sp<FakeWindowHandle> mSecondWindow;
4515
4516 void SetUp() override {
4517 InputDispatcherTest::SetUp();
4518 mApp = std::make_shared<FakeApplicationHandle>();
4519 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4520 mWindow->setFocusable(true);
4521 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4522 mSecondWindow->setFocusable(true);
4523
4524 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4526
4527 setFocusedWindow(mWindow);
4528 mWindow->consumeFocusEvent(true);
4529 }
4530
4531 void notifyPointerCaptureChanged(bool enabled) {
4532 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
4533 mDispatcher->notifyPointerCaptureChanged(&args);
4534 }
4535
4536 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
4537 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4538 mFakePolicy->waitForSetPointerCapture(enabled);
4539 notifyPointerCaptureChanged(enabled);
4540 window->consumeCaptureEvent(enabled);
4541 }
4542};
4543
4544TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4545 // Ensure that capture cannot be obtained for unfocused windows.
4546 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4547 mFakePolicy->assertSetPointerCaptureNotCalled();
4548 mSecondWindow->assertNoEvents();
4549
4550 // Ensure that capture can be enabled from the focus window.
4551 requestAndVerifyPointerCapture(mWindow, true);
4552
4553 // Ensure that capture cannot be disabled from a window that does not have capture.
4554 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4555 mFakePolicy->assertSetPointerCaptureNotCalled();
4556
4557 // Ensure that capture can be disabled from the window with capture.
4558 requestAndVerifyPointerCapture(mWindow, false);
4559}
4560
4561TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4562 requestAndVerifyPointerCapture(mWindow, true);
4563
4564 setFocusedWindow(mSecondWindow);
4565
4566 // Ensure that the capture disabled event was sent first.
4567 mWindow->consumeCaptureEvent(false);
4568 mWindow->consumeFocusEvent(false);
4569 mSecondWindow->consumeFocusEvent(true);
4570 mFakePolicy->waitForSetPointerCapture(false);
4571
4572 // Ensure that additional state changes from InputReader are not sent to the window.
4573 notifyPointerCaptureChanged(false);
4574 notifyPointerCaptureChanged(true);
4575 notifyPointerCaptureChanged(false);
4576 mWindow->assertNoEvents();
4577 mSecondWindow->assertNoEvents();
4578 mFakePolicy->assertSetPointerCaptureNotCalled();
4579}
4580
4581TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4582 requestAndVerifyPointerCapture(mWindow, true);
4583
4584 // InputReader unexpectedly disables and enables pointer capture.
4585 notifyPointerCaptureChanged(false);
4586 notifyPointerCaptureChanged(true);
4587
4588 // Ensure that Pointer Capture is disabled.
Prabir Pradhan7d030382020-12-21 07:58:35 -08004589 mFakePolicy->waitForSetPointerCapture(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004590 mWindow->consumeCaptureEvent(false);
4591 mWindow->assertNoEvents();
4592}
4593
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004594TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4595 requestAndVerifyPointerCapture(mWindow, true);
4596
4597 // The first window loses focus.
4598 setFocusedWindow(mSecondWindow);
4599 mFakePolicy->waitForSetPointerCapture(false);
4600 mWindow->consumeCaptureEvent(false);
4601
4602 // Request Pointer Capture from the second window before the notification from InputReader
4603 // arrives.
4604 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4605 mFakePolicy->waitForSetPointerCapture(true);
4606
4607 // InputReader notifies Pointer Capture was disabled (because of the focus change).
4608 notifyPointerCaptureChanged(false);
4609
4610 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
4611 notifyPointerCaptureChanged(true);
4612
4613 mSecondWindow->consumeFocusEvent(true);
4614 mSecondWindow->consumeCaptureEvent(true);
4615}
4616
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004617class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4618protected:
4619 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00004620
4621 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4622 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4623
4624 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4625 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4626
4627 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4628 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4629 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4630 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4631 MAXIMUM_OBSCURING_OPACITY);
4632
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004633 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004634 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004635 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004636
4637 sp<FakeWindowHandle> mTouchWindow;
4638
4639 virtual void SetUp() override {
4640 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004641 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004642 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4643 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4644 }
4645
4646 virtual void TearDown() override {
4647 InputDispatcherTest::TearDown();
4648 mTouchWindow.clear();
4649 }
4650
chaviw3277faf2021-05-19 16:45:23 -05004651 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
4652 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004653 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05004654 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004655 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004656 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004657 return window;
4658 }
4659
4660 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4661 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4662 sp<FakeWindowHandle> window =
4663 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4664 // Generate an arbitrary PID based on the UID
4665 window->setOwnerInfo(1777 + (uid % 10000), uid);
4666 return window;
4667 }
4668
4669 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4670 NotifyMotionArgs args =
4671 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4672 ADISPLAY_ID_DEFAULT, points);
4673 mDispatcher->notifyMotion(&args);
4674 }
4675};
4676
4677TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004678 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004679 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004681
4682 touch();
4683
4684 mTouchWindow->assertNoEvents();
4685}
4686
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004687TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00004688 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
4689 const sp<FakeWindowHandle>& w =
4690 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
4691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4692
4693 touch();
4694
4695 mTouchWindow->assertNoEvents();
4696}
4697
4698TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004699 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
4700 const sp<FakeWindowHandle>& w =
4701 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4703
4704 touch();
4705
4706 w->assertNoEvents();
4707}
4708
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004709TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004710 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
4711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004712
4713 touch();
4714
4715 mTouchWindow->consumeAnyMotionDown();
4716}
4717
4718TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004719 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004720 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004721 w->setFrame(Rect(0, 0, 50, 50));
4722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004723
4724 touch({PointF{100, 100}});
4725
4726 mTouchWindow->consumeAnyMotionDown();
4727}
4728
4729TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004730 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004731 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4733
4734 touch();
4735
4736 mTouchWindow->consumeAnyMotionDown();
4737}
4738
4739TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
4740 const sp<FakeWindowHandle>& w =
4741 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004743
4744 touch();
4745
4746 mTouchWindow->consumeAnyMotionDown();
4747}
4748
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004749TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
4750 const sp<FakeWindowHandle>& w =
4751 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4752 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4753
4754 touch();
4755
4756 w->assertNoEvents();
4757}
4758
4759/**
4760 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
4761 * inside) while letting them pass-through. Note that even though touch passes through the occluding
4762 * window, the occluding window will still receive ACTION_OUTSIDE event.
4763 */
4764TEST_F(InputDispatcherUntrustedTouchesTest,
4765 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
4766 const sp<FakeWindowHandle>& w =
4767 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05004768 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4770
4771 touch();
4772
4773 w->consumeMotionOutside();
4774}
4775
4776TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
4777 const sp<FakeWindowHandle>& w =
4778 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05004779 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004780 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4781
4782 touch();
4783
4784 InputEvent* event = w->consume();
4785 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
4786 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4787 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
4788 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
4789}
4790
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004791TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004792 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004793 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4794 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004795 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4796
4797 touch();
4798
4799 mTouchWindow->consumeAnyMotionDown();
4800}
4801
4802TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
4803 const sp<FakeWindowHandle>& w =
4804 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4805 MAXIMUM_OBSCURING_OPACITY);
4806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004807
4808 touch();
4809
4810 mTouchWindow->consumeAnyMotionDown();
4811}
4812
4813TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004814 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004815 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4816 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4818
4819 touch();
4820
4821 mTouchWindow->assertNoEvents();
4822}
4823
4824TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
4825 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
4826 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004827 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4828 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004829 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004830 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4831 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004832 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4833
4834 touch();
4835
4836 mTouchWindow->assertNoEvents();
4837}
4838
4839TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
4840 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
4841 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004842 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4843 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004844 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004845 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4846 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4848
4849 touch();
4850
4851 mTouchWindow->consumeAnyMotionDown();
4852}
4853
4854TEST_F(InputDispatcherUntrustedTouchesTest,
4855 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
4856 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004857 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4858 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004859 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004860 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4861 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004862 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4863
4864 touch();
4865
4866 mTouchWindow->consumeAnyMotionDown();
4867}
4868
4869TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
4870 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004871 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4872 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004873 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004874 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4875 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004877
4878 touch();
4879
4880 mTouchWindow->assertNoEvents();
4881}
4882
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004883TEST_F(InputDispatcherUntrustedTouchesTest,
4884 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
4885 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004886 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4887 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004888 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004889 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4890 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004891 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4892
4893 touch();
4894
4895 mTouchWindow->assertNoEvents();
4896}
4897
4898TEST_F(InputDispatcherUntrustedTouchesTest,
4899 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
4900 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004901 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4902 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004903 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004904 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4905 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004906 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4907
4908 touch();
4909
4910 mTouchWindow->consumeAnyMotionDown();
4911}
4912
4913TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
4914 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004915 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4916 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004917 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4918
4919 touch();
4920
4921 mTouchWindow->consumeAnyMotionDown();
4922}
4923
4924TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
4925 const sp<FakeWindowHandle>& w =
4926 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
4927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4928
4929 touch();
4930
4931 mTouchWindow->consumeAnyMotionDown();
4932}
4933
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004934TEST_F(InputDispatcherUntrustedTouchesTest,
4935 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
4936 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4937 const sp<FakeWindowHandle>& w =
4938 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
4939 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4940
4941 touch();
4942
4943 mTouchWindow->assertNoEvents();
4944}
4945
4946TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
4947 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4948 const sp<FakeWindowHandle>& w =
4949 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
4950 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4951
4952 touch();
4953
4954 mTouchWindow->consumeAnyMotionDown();
4955}
4956
4957TEST_F(InputDispatcherUntrustedTouchesTest,
4958 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
4959 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
4960 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004961 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4962 OPACITY_ABOVE_THRESHOLD);
4963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4964
4965 touch();
4966
4967 mTouchWindow->consumeAnyMotionDown();
4968}
4969
4970TEST_F(InputDispatcherUntrustedTouchesTest,
4971 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
4972 const sp<FakeWindowHandle>& w1 =
4973 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4974 OPACITY_BELOW_THRESHOLD);
4975 const sp<FakeWindowHandle>& w2 =
4976 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4977 OPACITY_BELOW_THRESHOLD);
4978 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4979
4980 touch();
4981
4982 mTouchWindow->assertNoEvents();
4983}
4984
4985/**
4986 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
4987 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
4988 * (which alone would result in allowing touches) does not affect the blocking behavior.
4989 */
4990TEST_F(InputDispatcherUntrustedTouchesTest,
4991 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
4992 const sp<FakeWindowHandle>& wB =
4993 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4994 OPACITY_BELOW_THRESHOLD);
4995 const sp<FakeWindowHandle>& wC =
4996 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4997 OPACITY_BELOW_THRESHOLD);
4998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4999
5000 touch();
5001
5002 mTouchWindow->assertNoEvents();
5003}
5004
5005/**
5006 * This test is testing that a window from a different UID but with same application token doesn't
5007 * block the touch. Apps can share the application token for close UI collaboration for example.
5008 */
5009TEST_F(InputDispatcherUntrustedTouchesTest,
5010 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5011 const sp<FakeWindowHandle>& w =
5012 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5013 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005014 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5015
5016 touch();
5017
5018 mTouchWindow->consumeAnyMotionDown();
5019}
5020
arthurhungb89ccb02020-12-30 16:19:01 +08005021class InputDispatcherDragTests : public InputDispatcherTest {
5022protected:
5023 std::shared_ptr<FakeApplicationHandle> mApp;
5024 sp<FakeWindowHandle> mWindow;
5025 sp<FakeWindowHandle> mSecondWindow;
5026 sp<FakeWindowHandle> mDragWindow;
5027
5028 void SetUp() override {
5029 InputDispatcherTest::SetUp();
5030 mApp = std::make_shared<FakeApplicationHandle>();
5031 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5032 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005033 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005034
5035 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5036 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005037 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005038
5039 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5041 }
5042
5043 // Start performing drag, we will create a drag window and transfer touch to it.
5044 void performDrag() {
5045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5046 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5047 {50, 50}))
5048 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5049
5050 // Window should receive motion event.
5051 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5052
5053 // The drag window covers the entire display
5054 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5055 mDispatcher->setInputWindows(
5056 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5057
5058 // Transfer touch focus to the drag window
5059 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5060 true /* isDragDrop */);
5061 mWindow->consumeMotionCancel();
5062 mDragWindow->consumeMotionDown();
5063 }
arthurhung6d4bed92021-03-17 11:59:33 +08005064
5065 // Start performing drag, we will create a drag window and transfer touch to it.
5066 void performStylusDrag() {
5067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5068 injectMotionEvent(mDispatcher,
5069 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5070 AINPUT_SOURCE_STYLUS)
5071 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5072 .pointer(PointerBuilder(0,
5073 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5074 .x(50)
5075 .y(50))
5076 .build()));
5077 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5078
5079 // The drag window covers the entire display
5080 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5081 mDispatcher->setInputWindows(
5082 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5083
5084 // Transfer touch focus to the drag window
5085 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5086 true /* isDragDrop */);
5087 mWindow->consumeMotionCancel();
5088 mDragWindow->consumeMotionDown();
5089 }
arthurhungb89ccb02020-12-30 16:19:01 +08005090};
5091
5092TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5093 performDrag();
5094
5095 // Move on window.
5096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5097 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5098 ADISPLAY_ID_DEFAULT, {50, 50}))
5099 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5100 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5101 mWindow->consumeDragEvent(false, 50, 50);
5102 mSecondWindow->assertNoEvents();
5103
5104 // Move to another window.
5105 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5106 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5107 ADISPLAY_ID_DEFAULT, {150, 50}))
5108 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5109 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5110 mWindow->consumeDragEvent(true, 150, 50);
5111 mSecondWindow->consumeDragEvent(false, 50, 50);
5112
5113 // Move back to original window.
5114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5115 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5116 ADISPLAY_ID_DEFAULT, {50, 50}))
5117 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5118 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5119 mWindow->consumeDragEvent(false, 50, 50);
5120 mSecondWindow->consumeDragEvent(true, -50, 50);
5121
5122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5123 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5124 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5125 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5126 mWindow->assertNoEvents();
5127 mSecondWindow->assertNoEvents();
5128}
5129
arthurhungf452d0b2021-01-06 00:19:52 +08005130TEST_F(InputDispatcherDragTests, DragAndDrop) {
5131 performDrag();
5132
5133 // Move on window.
5134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5135 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5136 ADISPLAY_ID_DEFAULT, {50, 50}))
5137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5138 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5139 mWindow->consumeDragEvent(false, 50, 50);
5140 mSecondWindow->assertNoEvents();
5141
5142 // Move to another window.
5143 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5144 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5145 ADISPLAY_ID_DEFAULT, {150, 50}))
5146 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5147 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5148 mWindow->consumeDragEvent(true, 150, 50);
5149 mSecondWindow->consumeDragEvent(false, 50, 50);
5150
5151 // drop to another window.
5152 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5153 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5154 {150, 50}))
5155 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5156 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5157 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5158 mWindow->assertNoEvents();
5159 mSecondWindow->assertNoEvents();
5160}
5161
arthurhung6d4bed92021-03-17 11:59:33 +08005162TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5163 performStylusDrag();
5164
5165 // Move on window and keep button pressed.
5166 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5167 injectMotionEvent(mDispatcher,
5168 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5169 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5170 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5171 .x(50)
5172 .y(50))
5173 .build()))
5174 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5175 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5176 mWindow->consumeDragEvent(false, 50, 50);
5177 mSecondWindow->assertNoEvents();
5178
5179 // Move to another window and release button, expect to drop item.
5180 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5181 injectMotionEvent(mDispatcher,
5182 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5183 .buttonState(0)
5184 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5185 .x(150)
5186 .y(50))
5187 .build()))
5188 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5189 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5190 mWindow->assertNoEvents();
5191 mSecondWindow->assertNoEvents();
5192 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5193
5194 // nothing to the window.
5195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5196 injectMotionEvent(mDispatcher,
5197 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5198 .buttonState(0)
5199 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5200 .x(150)
5201 .y(50))
5202 .build()))
5203 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5204 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5205 mWindow->assertNoEvents();
5206 mSecondWindow->assertNoEvents();
5207}
5208
Arthur Hung6d0571e2021-04-09 20:18:16 +08005209TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5210 performDrag();
5211
5212 // Set second window invisible.
5213 mSecondWindow->setVisible(false);
5214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5215
5216 // Move on window.
5217 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5218 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5219 ADISPLAY_ID_DEFAULT, {50, 50}))
5220 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5221 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5222 mWindow->consumeDragEvent(false, 50, 50);
5223 mSecondWindow->assertNoEvents();
5224
5225 // Move to another window.
5226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5227 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5228 ADISPLAY_ID_DEFAULT, {150, 50}))
5229 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5230 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5231 mWindow->consumeDragEvent(true, 150, 50);
5232 mSecondWindow->assertNoEvents();
5233
5234 // drop to another window.
5235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5236 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5237 {150, 50}))
5238 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5239 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5240 mFakePolicy->assertDropTargetEquals(nullptr);
5241 mWindow->assertNoEvents();
5242 mSecondWindow->assertNoEvents();
5243}
5244
Garfield Tane84e6f92019-08-29 17:28:41 -07005245} // namespace android::inputdispatcher