blob: e2688433e0a439e5c458d85617625d2cc2e6e056 [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;
chaviw98318de2021-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
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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,
chaviw98318de2021-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
chaviw98318de2021-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;
chaviw98318de2021-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
chaviw98318de2021-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
chaviw98318de2021-05-19 16:45:23 -0500964 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000965
chaviw98318de2021-05-19 16:45:23 -0500966 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800967
chaviw98318de2021-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 &&
chaviw98318de2021-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};
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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));
chaviw98318de2021-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);
chaviw98318de2021-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
liushenxiang97b0d3b2021-05-21 20:24:09 +08002879TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
2880 sendAndConsumeKeyDown(DEVICE_ID);
2881 expectKeyRepeatOnce(1 /*repeatCount*/);
2882 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
2883 mDispatcher->notifyDeviceReset(&args);
2884 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
2885 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
2886 mWindow->assertNoEvents();
2887}
2888
Garfield Tan1c7bc862020-01-28 13:24:04 -08002889TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002890 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002891 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2892 InputEvent* repeatEvent = mWindow->consume();
2893 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2894 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2895 IdGenerator::getSource(repeatEvent->getId()));
2896 }
2897}
2898
2899TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002900 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002901
2902 std::unordered_set<int32_t> idSet;
2903 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2904 InputEvent* repeatEvent = mWindow->consume();
2905 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2906 int32_t id = repeatEvent->getId();
2907 EXPECT_EQ(idSet.end(), idSet.find(id));
2908 idSet.insert(id);
2909 }
2910}
2911
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002912/* Test InputDispatcher for MultiDisplay */
2913class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2914public:
2915 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002916 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002917 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002918
Chris Yea209fde2020-07-22 13:54:51 -07002919 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002920 windowInPrimary =
2921 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002922
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002923 // Set focus window for primary display, but focused display would be second one.
2924 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002925 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002927 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002928 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002929
Chris Yea209fde2020-07-22 13:54:51 -07002930 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002931 windowInSecondary =
2932 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002933 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002934 // Set focus display to second one.
2935 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2936 // Set focus window for second display.
2937 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002938 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002939 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002940 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002941 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002942 }
2943
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002944 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002945 InputDispatcherTest::TearDown();
2946
Chris Yea209fde2020-07-22 13:54:51 -07002947 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002948 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002949 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002950 windowInSecondary.clear();
2951 }
2952
2953protected:
Chris Yea209fde2020-07-22 13:54:51 -07002954 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002955 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002956 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002957 sp<FakeWindowHandle> windowInSecondary;
2958};
2959
2960TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2961 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2963 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002965 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002966 windowInSecondary->assertNoEvents();
2967
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002968 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2970 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2971 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002972 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002973 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002974}
2975
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002976TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002977 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002978 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2979 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002980 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002981 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002982 windowInSecondary->assertNoEvents();
2983
2984 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002986 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002987 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002988 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002989
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002990 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002991 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002992
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002993 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002994 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2995 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002996
2997 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002998 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002999 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003000 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003001 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003002 windowInSecondary->assertNoEvents();
3003}
3004
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003005// Test per-display input monitors for motion event.
3006TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003007 FakeMonitorReceiver monitorInPrimary =
3008 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3009 FakeMonitorReceiver monitorInSecondary =
3010 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003011
3012 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3014 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3015 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003016 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003017 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003018 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003019 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003020
3021 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3023 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3024 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003025 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003026 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003027 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003028 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003029
3030 // Test inject a non-pointer motion event.
3031 // If specific a display, it will dispatch to the focused window of particular display,
3032 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003033 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3034 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3035 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003036 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003037 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003038 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003039 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003040}
3041
3042// Test per-display input monitors for key event.
3043TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003044 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003045 FakeMonitorReceiver monitorInPrimary =
3046 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3047 FakeMonitorReceiver monitorInSecondary =
3048 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003049
3050 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3052 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003053 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003054 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003055 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003056 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003057}
3058
Vishnu Nair958da932020-08-21 17:12:37 -07003059TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3060 sp<FakeWindowHandle> secondWindowInPrimary =
3061 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3062 secondWindowInPrimary->setFocusable(true);
3063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3064 setFocusedWindow(secondWindowInPrimary);
3065 windowInPrimary->consumeFocusEvent(false);
3066 secondWindowInPrimary->consumeFocusEvent(true);
3067
3068 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3070 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003071 windowInPrimary->assertNoEvents();
3072 windowInSecondary->assertNoEvents();
3073 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3074}
3075
Jackal Guof9696682018-10-05 12:23:23 +08003076class InputFilterTest : public InputDispatcherTest {
3077protected:
3078 static constexpr int32_t SECOND_DISPLAY_ID = 1;
3079
3080 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
3081 NotifyMotionArgs motionArgs;
3082
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003083 motionArgs =
3084 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003085 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003086 motionArgs =
3087 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003088 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003089 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003090 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003091 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003092 } else {
3093 mFakePolicy->assertFilterInputEventWasNotCalled();
3094 }
3095 }
3096
3097 void testNotifyKey(bool expectToBeFiltered) {
3098 NotifyKeyArgs keyArgs;
3099
3100 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3101 mDispatcher->notifyKey(&keyArgs);
3102 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3103 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003104 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003105
3106 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003107 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003108 } else {
3109 mFakePolicy->assertFilterInputEventWasNotCalled();
3110 }
3111 }
3112};
3113
3114// Test InputFilter for MotionEvent
3115TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3116 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3117 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3118 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3119
3120 // Enable InputFilter
3121 mDispatcher->setInputFilterEnabled(true);
3122 // Test touch on both primary and second display, and check if both events are filtered.
3123 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3124 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3125
3126 // Disable InputFilter
3127 mDispatcher->setInputFilterEnabled(false);
3128 // Test touch on both primary and second display, and check if both events aren't filtered.
3129 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3130 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3131}
3132
3133// Test InputFilter for KeyEvent
3134TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3135 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3136 testNotifyKey(/*expectToBeFiltered*/ false);
3137
3138 // Enable InputFilter
3139 mDispatcher->setInputFilterEnabled(true);
3140 // Send a key event, and check if it is filtered.
3141 testNotifyKey(/*expectToBeFiltered*/ true);
3142
3143 // Disable InputFilter
3144 mDispatcher->setInputFilterEnabled(false);
3145 // Send a key event, and check if it isn't filtered.
3146 testNotifyKey(/*expectToBeFiltered*/ false);
3147}
3148
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003149class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3150protected:
3151 virtual void SetUp() override {
3152 InputDispatcherTest::SetUp();
3153
3154 /**
3155 * We don't need to enable input filter to test the injected event policy, but we enabled it
3156 * here to make the tests more realistic, since this policy only matters when inputfilter is
3157 * on.
3158 */
3159 mDispatcher->setInputFilterEnabled(true);
3160
3161 std::shared_ptr<InputApplicationHandle> application =
3162 std::make_shared<FakeApplicationHandle>();
3163 mWindow =
3164 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3165
3166 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3167 mWindow->setFocusable(true);
3168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3169 setFocusedWindow(mWindow);
3170 mWindow->consumeFocusEvent(true);
3171 }
3172
3173 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId) {
3174 KeyEvent event;
3175
3176 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3177 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3178 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3179 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3180 const int32_t additionalPolicyFlags =
3181 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3183 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3184 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3185 policyFlags | additionalPolicyFlags));
3186
3187 InputEvent* received = mWindow->consume();
3188 ASSERT_NE(nullptr, received);
3189 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3190 }
3191
3192private:
3193 sp<FakeWindowHandle> mWindow;
3194};
3195
3196TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
3197 // We don't need POLICY_FLAG_FILTERED here, but it will be set in practice, so keep it to make
3198 // the test more closely resemble the real usage
3199 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INPUTFILTER_TRUSTED, 3 /*injectedDeviceId*/,
3200 3 /*resolvedDeviceId*/);
3201}
3202
3203TEST_F(InputFilterInjectionPolicyTest, EventsInjectedFromAccessibility_HaveAccessibilityDeviceId) {
3204 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3205 3 /*injectedDeviceId*/, ACCESSIBILITY_DEVICE_ID /*resolvedDeviceId*/);
3206}
3207
3208TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3209 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
3210 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/);
3211}
3212
chaviwfd6d3512019-03-25 13:23:49 -07003213class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003214 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003215 InputDispatcherTest::SetUp();
3216
Chris Yea209fde2020-07-22 13:54:51 -07003217 std::shared_ptr<FakeApplicationHandle> application =
3218 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003219 mUnfocusedWindow =
3220 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003221 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3222 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3223 // window.
chaviw98318de2021-05-19 16:45:23 -05003224 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003225
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003226 mFocusedWindow =
3227 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3228 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw98318de2021-05-19 16:45:23 -05003229 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003230
3231 // Set focused application.
3232 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003233 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003234
3235 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003236 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003237 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003238 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003239 }
3240
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003241 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003242 InputDispatcherTest::TearDown();
3243
3244 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003245 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003246 }
3247
3248protected:
3249 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003250 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003251 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003252};
3253
3254// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3255// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3256// the onPointerDownOutsideFocus callback.
3257TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003258 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003259 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3260 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003261 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003262 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003263
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003264 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003265 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3266}
3267
3268// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3269// DOWN on the window that doesn't have focus. Ensure no window received the
3270// onPointerDownOutsideFocus callback.
3271TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003272 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003273 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003274 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003275 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003276
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003277 ASSERT_TRUE(mDispatcher->waitForIdle());
3278 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003279}
3280
3281// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3282// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3283TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3285 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003286 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003287 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003288
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003289 ASSERT_TRUE(mDispatcher->waitForIdle());
3290 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003291}
3292
3293// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3294// DOWN on the window that already has focus. Ensure no window received the
3295// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003296TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003298 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003299 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003300 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003301 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003302
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003303 ASSERT_TRUE(mDispatcher->waitForIdle());
3304 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003305}
3306
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003307// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3308// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3309TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3310 const MotionEvent event =
3311 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3312 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3313 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3314 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3315 .build();
3316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3317 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3318 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3319
3320 ASSERT_TRUE(mDispatcher->waitForIdle());
3321 mFakePolicy->assertOnPointerDownWasNotCalled();
3322 // Ensure that the unfocused window did not receive any FOCUS events.
3323 mUnfocusedWindow->assertNoEvents();
3324}
3325
chaviwaf87b3e2019-10-01 16:59:28 -07003326// These tests ensures we can send touch events to a single client when there are multiple input
3327// windows that point to the same client token.
3328class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3329 virtual void SetUp() override {
3330 InputDispatcherTest::SetUp();
3331
Chris Yea209fde2020-07-22 13:54:51 -07003332 std::shared_ptr<FakeApplicationHandle> application =
3333 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003334 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3335 ADISPLAY_ID_DEFAULT);
3336 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3337 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw98318de2021-05-19 16:45:23 -05003338 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003339 mWindow1->setFrame(Rect(0, 0, 100, 100));
3340
3341 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3342 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw98318de2021-05-19 16:45:23 -05003343 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003344 mWindow2->setFrame(Rect(100, 100, 200, 200));
3345
Arthur Hung72d8dc32020-03-28 00:48:39 +00003346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003347 }
3348
3349protected:
3350 sp<FakeWindowHandle> mWindow1;
3351 sp<FakeWindowHandle> mWindow2;
3352
3353 // Helper function to convert the point from screen coordinates into the window's space
chaviw98318de2021-05-19 16:45:23 -05003354 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003355 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3356 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003357 }
3358
3359 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3360 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003361 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003362 InputEvent* event = window->consume();
3363
3364 ASSERT_NE(nullptr, event) << name.c_str()
3365 << ": consumer should have returned non-NULL event.";
3366
3367 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3368 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3369 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3370
3371 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3372 EXPECT_EQ(expectedAction, motionEvent.getAction());
3373
3374 for (size_t i = 0; i < points.size(); i++) {
3375 float expectedX = points[i].x;
3376 float expectedY = points[i].y;
3377
3378 EXPECT_EQ(expectedX, motionEvent.getX(i))
3379 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3380 << ", got " << motionEvent.getX(i);
3381 EXPECT_EQ(expectedY, motionEvent.getY(i))
3382 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3383 << ", got " << motionEvent.getY(i);
3384 }
3385 }
chaviw9eaa22c2020-07-01 16:21:27 -07003386
3387 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3388 std::vector<PointF> expectedPoints) {
3389 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3390 ADISPLAY_ID_DEFAULT, touchedPoints);
3391 mDispatcher->notifyMotion(&motionArgs);
3392
3393 // Always consume from window1 since it's the window that has the InputReceiver
3394 consumeMotionEvent(mWindow1, action, expectedPoints);
3395 }
chaviwaf87b3e2019-10-01 16:59:28 -07003396};
3397
3398TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3399 // Touch Window 1
3400 PointF touchedPoint = {10, 10};
3401 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003402 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003403
3404 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003405 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003406
3407 // Touch Window 2
3408 touchedPoint = {150, 150};
3409 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003410 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003411}
3412
chaviw9eaa22c2020-07-01 16:21:27 -07003413TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3414 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003415 mWindow2->setWindowScale(0.5f, 0.5f);
3416
3417 // Touch Window 1
3418 PointF touchedPoint = {10, 10};
3419 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003420 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003421 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003422 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003423
3424 // Touch Window 2
3425 touchedPoint = {150, 150};
3426 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003427 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3428 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003429
chaviw9eaa22c2020-07-01 16:21:27 -07003430 // Update the transform so rotation is set
3431 mWindow2->setWindowTransform(0, -1, 1, 0);
3432 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3433 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003434}
3435
chaviw9eaa22c2020-07-01 16:21:27 -07003436TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003437 mWindow2->setWindowScale(0.5f, 0.5f);
3438
3439 // Touch Window 1
3440 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3441 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003442 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003443
3444 // Touch Window 2
3445 int32_t actionPointerDown =
3446 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003447 touchedPoints.push_back(PointF{150, 150});
3448 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3449 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003450
chaviw9eaa22c2020-07-01 16:21:27 -07003451 // Release Window 2
3452 int32_t actionPointerUp =
3453 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3454 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3455 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003456
chaviw9eaa22c2020-07-01 16:21:27 -07003457 // Update the transform so rotation is set for Window 2
3458 mWindow2->setWindowTransform(0, -1, 1, 0);
3459 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3460 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003461}
3462
chaviw9eaa22c2020-07-01 16:21:27 -07003463TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003464 mWindow2->setWindowScale(0.5f, 0.5f);
3465
3466 // Touch Window 1
3467 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3468 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003469 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003470
3471 // Touch Window 2
3472 int32_t actionPointerDown =
3473 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003474 touchedPoints.push_back(PointF{150, 150});
3475 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003476
chaviw9eaa22c2020-07-01 16:21:27 -07003477 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003478
3479 // Move both windows
3480 touchedPoints = {{20, 20}, {175, 175}};
3481 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3482 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3483
chaviw9eaa22c2020-07-01 16:21:27 -07003484 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003485
chaviw9eaa22c2020-07-01 16:21:27 -07003486 // Release Window 2
3487 int32_t actionPointerUp =
3488 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3489 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3490 expectedPoints.pop_back();
3491
3492 // Touch Window 2
3493 mWindow2->setWindowTransform(0, -1, 1, 0);
3494 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3495 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3496
3497 // Move both windows
3498 touchedPoints = {{20, 20}, {175, 175}};
3499 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3500 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3501
3502 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003503}
3504
3505TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3506 mWindow1->setWindowScale(0.5f, 0.5f);
3507
3508 // Touch Window 1
3509 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3510 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003511 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003512
3513 // Touch Window 2
3514 int32_t actionPointerDown =
3515 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003516 touchedPoints.push_back(PointF{150, 150});
3517 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003518
chaviw9eaa22c2020-07-01 16:21:27 -07003519 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003520
3521 // Move both windows
3522 touchedPoints = {{20, 20}, {175, 175}};
3523 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3524 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3525
chaviw9eaa22c2020-07-01 16:21:27 -07003526 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003527}
3528
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003529class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3530 virtual void SetUp() override {
3531 InputDispatcherTest::SetUp();
3532
Chris Yea209fde2020-07-22 13:54:51 -07003533 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003534 mApplication->setDispatchingTimeout(20ms);
3535 mWindow =
3536 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3537 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003538 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003539 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003540 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3541 // window.
chaviw98318de2021-05-19 16:45:23 -05003542 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003543
3544 // Set focused application.
3545 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3546
3547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003548 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003549 mWindow->consumeFocusEvent(true);
3550 }
3551
3552 virtual void TearDown() override {
3553 InputDispatcherTest::TearDown();
3554 mWindow.clear();
3555 }
3556
3557protected:
Chris Yea209fde2020-07-22 13:54:51 -07003558 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003559 sp<FakeWindowHandle> mWindow;
3560 static constexpr PointF WINDOW_LOCATION = {20, 20};
3561
3562 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003564 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3565 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003567 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3568 WINDOW_LOCATION));
3569 }
3570};
3571
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003572// Send a tap and respond, which should not cause an ANR.
3573TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3574 tapOnWindow();
3575 mWindow->consumeMotionDown();
3576 mWindow->consumeMotionUp();
3577 ASSERT_TRUE(mDispatcher->waitForIdle());
3578 mFakePolicy->assertNotifyAnrWasNotCalled();
3579}
3580
3581// Send a regular key and respond, which should not cause an ANR.
3582TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003584 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3585 ASSERT_TRUE(mDispatcher->waitForIdle());
3586 mFakePolicy->assertNotifyAnrWasNotCalled();
3587}
3588
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003589TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3590 mWindow->setFocusable(false);
3591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3592 mWindow->consumeFocusEvent(false);
3593
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003594 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003595 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003596 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3597 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003599 // Key will not go to window because we have no focused window.
3600 // The 'no focused window' ANR timer should start instead.
3601
3602 // Now, the focused application goes away.
3603 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3604 // The key should get dropped and there should be no ANR.
3605
3606 ASSERT_TRUE(mDispatcher->waitForIdle());
3607 mFakePolicy->assertNotifyAnrWasNotCalled();
3608}
3609
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003610// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003611// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3612// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003613TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003615 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3616 WINDOW_LOCATION));
3617
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003618 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3619 ASSERT_TRUE(sequenceNum);
3620 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003621 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003622
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003623 mWindow->finishEvent(*sequenceNum);
3624 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3625 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003626 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003627 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003628}
3629
3630// Send a key to the app and have the app not respond right away.
3631TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3632 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003634 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3635 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003636 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003637 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003638 ASSERT_TRUE(mDispatcher->waitForIdle());
3639}
3640
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003641// We have a focused application, but no focused window
3642TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003643 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3645 mWindow->consumeFocusEvent(false);
3646
3647 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003649 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3650 WINDOW_LOCATION));
3651 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3652 mDispatcher->waitForIdle();
3653 mFakePolicy->assertNotifyAnrWasNotCalled();
3654
3655 // Once a focused event arrives, we get an ANR for this application
3656 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3657 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003658 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003659 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003660 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003661 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003662 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003663 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003664 ASSERT_TRUE(mDispatcher->waitForIdle());
3665}
3666
3667// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003668// Make sure that we don't notify policy twice about the same ANR.
3669TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003670 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3672 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003673
3674 // Once a focused event arrives, we get an ANR for this application
3675 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3676 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003677 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003678 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003679 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003680 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003681 const std::chrono::duration appTimeout =
3682 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003683 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003684
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003685 std::this_thread::sleep_for(appTimeout);
3686 // ANR should not be raised again. It is up to policy to do that if it desires.
3687 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003688
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003689 // If we now get a focused window, the ANR should stop, but the policy handles that via
3690 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003691 ASSERT_TRUE(mDispatcher->waitForIdle());
3692}
3693
3694// We have a focused application, but no focused window
3695TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003696 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3698 mWindow->consumeFocusEvent(false);
3699
3700 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003701 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003702 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003703 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3704 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003705
3706 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003707 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003708
3709 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003710 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003711 ASSERT_TRUE(mDispatcher->waitForIdle());
3712 mWindow->assertNoEvents();
3713}
3714
3715/**
3716 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3717 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3718 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3719 * the ANR mechanism should still work.
3720 *
3721 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3722 * DOWN event, while not responding on the second one.
3723 */
3724TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3725 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3726 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3727 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3728 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3729 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003730 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003731
3732 // Now send ACTION_UP, with identical timestamp
3733 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3734 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3735 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3736 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003737 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003738
3739 // We have now sent down and up. Let's consume first event and then ANR on the second.
3740 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3741 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003742 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003743}
3744
3745// If an app is not responding to a key event, gesture monitors should continue to receive
3746// new motion events
3747TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3748 FakeMonitorReceiver monitor =
3749 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3750 true /*isGestureMonitor*/);
3751
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003752 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3753 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003754 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003755 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003756
3757 // Stuck on the ACTION_UP
3758 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003759 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003760
3761 // New tap will go to the gesture monitor, but not to the window
3762 tapOnWindow();
3763 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3764 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3765
3766 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3767 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003768 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003769 mWindow->assertNoEvents();
3770 monitor.assertNoEvents();
3771}
3772
3773// If an app is not responding to a motion event, gesture monitors should continue to receive
3774// new motion events
3775TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3776 FakeMonitorReceiver monitor =
3777 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3778 true /*isGestureMonitor*/);
3779
3780 tapOnWindow();
3781 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3782 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3783
3784 mWindow->consumeMotionDown();
3785 // Stuck on the ACTION_UP
3786 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003787 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003788
3789 // New tap will go to the gesture monitor, but not to the window
3790 tapOnWindow();
3791 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3792 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3793
3794 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3795 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003796 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003797 mWindow->assertNoEvents();
3798 monitor.assertNoEvents();
3799}
3800
3801// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3802// process events, you don't get an anr. When the window later becomes unresponsive again, you
3803// get an ANR again.
3804// 1. tap -> block on ACTION_UP -> receive ANR
3805// 2. consume all pending events (= queue becomes healthy again)
3806// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3807TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3808 tapOnWindow();
3809
3810 mWindow->consumeMotionDown();
3811 // Block on ACTION_UP
3812 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003813 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003814 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3815 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003816 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003817 mWindow->assertNoEvents();
3818
3819 tapOnWindow();
3820 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003821 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003822 mWindow->consumeMotionUp();
3823
3824 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003825 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003826 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003827 mWindow->assertNoEvents();
3828}
3829
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003830// If a connection remains unresponsive for a while, make sure policy is only notified once about
3831// it.
3832TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003834 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3835 WINDOW_LOCATION));
3836
3837 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003838 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003839 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003840 // 'notifyConnectionUnresponsive' should only be called once per connection
3841 mFakePolicy->assertNotifyAnrWasNotCalled();
3842 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003843 mWindow->consumeMotionDown();
3844 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3845 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3846 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003847 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003848 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003849 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003850}
3851
3852/**
3853 * If a window is processing a motion event, and then a key event comes in, the key event should
3854 * not to to the focused window until the motion is processed.
3855 *
3856 * Warning!!!
3857 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3858 * and the injection timeout that we specify when injecting the key.
3859 * We must have the injection timeout (10ms) be smaller than
3860 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3861 *
3862 * If that value changes, this test should also change.
3863 */
3864TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3865 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3867
3868 tapOnWindow();
3869 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3870 ASSERT_TRUE(downSequenceNum);
3871 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3872 ASSERT_TRUE(upSequenceNum);
3873 // Don't finish the events yet, and send a key
3874 // Injection will "succeed" because we will eventually give up and send the key to the focused
3875 // window even if motions are still being processed. But because the injection timeout is short,
3876 // we will receive INJECTION_TIMED_OUT as the result.
3877
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003878 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003879 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003880 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3881 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003882 // Key will not be sent to the window, yet, because the window is still processing events
3883 // and the key remains pending, waiting for the touch events to be processed
3884 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3885 ASSERT_FALSE(keySequenceNum);
3886
3887 std::this_thread::sleep_for(500ms);
3888 // if we wait long enough though, dispatcher will give up, and still send the key
3889 // to the focused window, even though we have not yet finished the motion event
3890 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3891 mWindow->finishEvent(*downSequenceNum);
3892 mWindow->finishEvent(*upSequenceNum);
3893}
3894
3895/**
3896 * If a window is processing a motion event, and then a key event comes in, the key event should
3897 * not go to the focused window until the motion is processed.
3898 * If then a new motion comes in, then the pending key event should be going to the currently
3899 * focused window right away.
3900 */
3901TEST_F(InputDispatcherSingleWindowAnr,
3902 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3903 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3905
3906 tapOnWindow();
3907 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3908 ASSERT_TRUE(downSequenceNum);
3909 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3910 ASSERT_TRUE(upSequenceNum);
3911 // Don't finish the events yet, and send a key
3912 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003913 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003914 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003915 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003916 // At this point, key is still pending, and should not be sent to the application yet.
3917 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3918 ASSERT_FALSE(keySequenceNum);
3919
3920 // Now tap down again. It should cause the pending key to go to the focused window right away.
3921 tapOnWindow();
3922 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3923 // the other events yet. We can finish events in any order.
3924 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3925 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3926 mWindow->consumeMotionDown();
3927 mWindow->consumeMotionUp();
3928 mWindow->assertNoEvents();
3929}
3930
3931class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3932 virtual void SetUp() override {
3933 InputDispatcherTest::SetUp();
3934
Chris Yea209fde2020-07-22 13:54:51 -07003935 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003936 mApplication->setDispatchingTimeout(10ms);
3937 mUnfocusedWindow =
3938 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3939 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3940 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3941 // window.
3942 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw98318de2021-05-19 16:45:23 -05003943 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
3944 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3945 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003946
3947 mFocusedWindow =
3948 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003949 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003950 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw98318de2021-05-19 16:45:23 -05003951 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003952
3953 // Set focused application.
3954 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003955 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003956
3957 // Expect one focus window exist in display.
3958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003959 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003960 mFocusedWindow->consumeFocusEvent(true);
3961 }
3962
3963 virtual void TearDown() override {
3964 InputDispatcherTest::TearDown();
3965
3966 mUnfocusedWindow.clear();
3967 mFocusedWindow.clear();
3968 }
3969
3970protected:
Chris Yea209fde2020-07-22 13:54:51 -07003971 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003972 sp<FakeWindowHandle> mUnfocusedWindow;
3973 sp<FakeWindowHandle> mFocusedWindow;
3974 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3975 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3976 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3977
3978 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3979
3980 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3981
3982private:
3983 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003984 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003985 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3986 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003988 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3989 location));
3990 }
3991};
3992
3993// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3994// should be ANR'd first.
3995TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003997 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3998 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003999 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004000 mFocusedWindow->consumeMotionDown();
4001 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4002 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4003 // We consumed all events, so no ANR
4004 ASSERT_TRUE(mDispatcher->waitForIdle());
4005 mFakePolicy->assertNotifyAnrWasNotCalled();
4006
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004008 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4009 FOCUSED_WINDOW_LOCATION));
4010 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4011 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004012
4013 const std::chrono::duration timeout =
4014 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004015 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004016 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4017 // sequence to make it consistent
4018 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004019 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004020 mFocusedWindow->consumeMotionDown();
4021 // This cancel is generated because the connection was unresponsive
4022 mFocusedWindow->consumeMotionCancel();
4023 mFocusedWindow->assertNoEvents();
4024 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004025 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004026 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004027 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004028}
4029
4030// If we have 2 windows with identical timeouts that are both unresponsive,
4031// it doesn't matter which order they should have ANR.
4032// But we should receive ANR for both.
4033TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4034 // Set the timeout for unfocused window to match the focused window
4035 mUnfocusedWindow->setDispatchingTimeout(10ms);
4036 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4037
4038 tapOnFocusedWindow();
4039 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004040 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4041 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004042
4043 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004044 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4045 mFocusedWindow->getToken() == anrConnectionToken2);
4046 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4047 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004048
4049 ASSERT_TRUE(mDispatcher->waitForIdle());
4050 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004051
4052 mFocusedWindow->consumeMotionDown();
4053 mFocusedWindow->consumeMotionUp();
4054 mUnfocusedWindow->consumeMotionOutside();
4055
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004056 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4057 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004058
4059 // Both applications should be marked as responsive, in any order
4060 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4061 mFocusedWindow->getToken() == responsiveToken2);
4062 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4063 mUnfocusedWindow->getToken() == responsiveToken2);
4064 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004065}
4066
4067// If a window is already not responding, the second tap on the same window should be ignored.
4068// We should also log an error to account for the dropped event (not tested here).
4069// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4070TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4071 tapOnFocusedWindow();
4072 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4073 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4074 // Receive the events, but don't respond
4075 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4076 ASSERT_TRUE(downEventSequenceNum);
4077 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4078 ASSERT_TRUE(upEventSequenceNum);
4079 const std::chrono::duration timeout =
4080 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004081 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004082
4083 // Tap once again
4084 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004085 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004086 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4087 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004088 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004089 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4090 FOCUSED_WINDOW_LOCATION));
4091 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4092 // valid touch target
4093 mUnfocusedWindow->assertNoEvents();
4094
4095 // Consume the first tap
4096 mFocusedWindow->finishEvent(*downEventSequenceNum);
4097 mFocusedWindow->finishEvent(*upEventSequenceNum);
4098 ASSERT_TRUE(mDispatcher->waitForIdle());
4099 // The second tap did not go to the focused window
4100 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004101 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004102 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004103 mFakePolicy->assertNotifyAnrWasNotCalled();
4104}
4105
4106// If you tap outside of all windows, there will not be ANR
4107TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004108 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004109 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4110 LOCATION_OUTSIDE_ALL_WINDOWS));
4111 ASSERT_TRUE(mDispatcher->waitForIdle());
4112 mFakePolicy->assertNotifyAnrWasNotCalled();
4113}
4114
4115// Since the focused window is paused, tapping on it should not produce any events
4116TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4117 mFocusedWindow->setPaused(true);
4118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4119
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004120 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004121 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4122 FOCUSED_WINDOW_LOCATION));
4123
4124 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4125 ASSERT_TRUE(mDispatcher->waitForIdle());
4126 // Should not ANR because the window is paused, and touches shouldn't go to it
4127 mFakePolicy->assertNotifyAnrWasNotCalled();
4128
4129 mFocusedWindow->assertNoEvents();
4130 mUnfocusedWindow->assertNoEvents();
4131}
4132
4133/**
4134 * If a window is processing a motion event, and then a key event comes in, the key event should
4135 * not to to the focused window until the motion is processed.
4136 * If a different window becomes focused at this time, the key should go to that window instead.
4137 *
4138 * Warning!!!
4139 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4140 * and the injection timeout that we specify when injecting the key.
4141 * We must have the injection timeout (10ms) be smaller than
4142 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4143 *
4144 * If that value changes, this test should also change.
4145 */
4146TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4147 // Set a long ANR timeout to prevent it from triggering
4148 mFocusedWindow->setDispatchingTimeout(2s);
4149 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4150
4151 tapOnUnfocusedWindow();
4152 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4153 ASSERT_TRUE(downSequenceNum);
4154 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4155 ASSERT_TRUE(upSequenceNum);
4156 // Don't finish the events yet, and send a key
4157 // Injection will succeed because we will eventually give up and send the key to the focused
4158 // window even if motions are still being processed.
4159
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004160 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004161 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004162 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004164 // Key will not be sent to the window, yet, because the window is still processing events
4165 // and the key remains pending, waiting for the touch events to be processed
4166 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4167 ASSERT_FALSE(keySequenceNum);
4168
4169 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004170 mFocusedWindow->setFocusable(false);
4171 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004173 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004174
4175 // Focus events should precede the key events
4176 mUnfocusedWindow->consumeFocusEvent(true);
4177 mFocusedWindow->consumeFocusEvent(false);
4178
4179 // Finish the tap events, which should unblock dispatcher
4180 mUnfocusedWindow->finishEvent(*downSequenceNum);
4181 mUnfocusedWindow->finishEvent(*upSequenceNum);
4182
4183 // Now that all queues are cleared and no backlog in the connections, the key event
4184 // can finally go to the newly focused "mUnfocusedWindow".
4185 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4186 mFocusedWindow->assertNoEvents();
4187 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004188 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004189}
4190
4191// When the touch stream is split across 2 windows, and one of them does not respond,
4192// then ANR should be raised and the touch should be canceled for the unresponsive window.
4193// The other window should not be affected by that.
4194TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4195 // Touch Window 1
4196 NotifyMotionArgs motionArgs =
4197 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4198 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4199 mDispatcher->notifyMotion(&motionArgs);
4200 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4201 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4202
4203 // Touch Window 2
4204 int32_t actionPointerDown =
4205 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4206
4207 motionArgs =
4208 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4209 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4210 mDispatcher->notifyMotion(&motionArgs);
4211
4212 const std::chrono::duration timeout =
4213 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004214 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004215
4216 mUnfocusedWindow->consumeMotionDown();
4217 mFocusedWindow->consumeMotionDown();
4218 // Focused window may or may not receive ACTION_MOVE
4219 // But it should definitely receive ACTION_CANCEL due to the ANR
4220 InputEvent* event;
4221 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4222 ASSERT_TRUE(moveOrCancelSequenceNum);
4223 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4224 ASSERT_NE(nullptr, event);
4225 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4226 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4227 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4228 mFocusedWindow->consumeMotionCancel();
4229 } else {
4230 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4231 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004232 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004233 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004234
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004235 mUnfocusedWindow->assertNoEvents();
4236 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004237 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004238}
4239
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004240/**
4241 * If we have no focused window, and a key comes in, we start the ANR timer.
4242 * The focused application should add a focused window before the timer runs out to prevent ANR.
4243 *
4244 * If the user touches another application during this time, the key should be dropped.
4245 * Next, if a new focused window comes in, without toggling the focused application,
4246 * then no ANR should occur.
4247 *
4248 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4249 * but in some cases the policy may not update the focused application.
4250 */
4251TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4252 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4253 std::make_shared<FakeApplicationHandle>();
4254 focusedApplication->setDispatchingTimeout(60ms);
4255 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4256 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4257 mFocusedWindow->setFocusable(false);
4258
4259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4260 mFocusedWindow->consumeFocusEvent(false);
4261
4262 // Send a key. The ANR timer should start because there is no focused window.
4263 // 'focusedApplication' will get blamed if this timer completes.
4264 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004265 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004266 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004267 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4268 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004270
4271 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4272 // then the injected touches won't cause the focused event to get dropped.
4273 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4274 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4275 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4276 // For this test, it means that the key would get delivered to the window once it becomes
4277 // focused.
4278 std::this_thread::sleep_for(10ms);
4279
4280 // Touch unfocused window. This should force the pending key to get dropped.
4281 NotifyMotionArgs motionArgs =
4282 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4283 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4284 mDispatcher->notifyMotion(&motionArgs);
4285
4286 // We do not consume the motion right away, because that would require dispatcher to first
4287 // process (== drop) the key event, and by that time, ANR will be raised.
4288 // Set the focused window first.
4289 mFocusedWindow->setFocusable(true);
4290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4291 setFocusedWindow(mFocusedWindow);
4292 mFocusedWindow->consumeFocusEvent(true);
4293 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4294 // to another application. This could be a bug / behaviour in the policy.
4295
4296 mUnfocusedWindow->consumeMotionDown();
4297
4298 ASSERT_TRUE(mDispatcher->waitForIdle());
4299 // Should not ANR because we actually have a focused window. It was just added too slowly.
4300 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4301}
4302
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004303// These tests ensure we cannot send touch events to a window that's positioned behind a window
4304// that has feature NO_INPUT_CHANNEL.
4305// Layout:
4306// Top (closest to user)
4307// mNoInputWindow (above all windows)
4308// mBottomWindow
4309// Bottom (furthest from user)
4310class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4311 virtual void SetUp() override {
4312 InputDispatcherTest::SetUp();
4313
4314 mApplication = std::make_shared<FakeApplicationHandle>();
4315 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4316 "Window without input channel", ADISPLAY_ID_DEFAULT,
4317 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4318
chaviw98318de2021-05-19 16:45:23 -05004319 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004320 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4321 // It's perfectly valid for this window to not have an associated input channel
4322
4323 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4324 ADISPLAY_ID_DEFAULT);
4325 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4326
4327 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4328 }
4329
4330protected:
4331 std::shared_ptr<FakeApplicationHandle> mApplication;
4332 sp<FakeWindowHandle> mNoInputWindow;
4333 sp<FakeWindowHandle> mBottomWindow;
4334};
4335
4336TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4337 PointF touchedPoint = {10, 10};
4338
4339 NotifyMotionArgs motionArgs =
4340 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4341 ADISPLAY_ID_DEFAULT, {touchedPoint});
4342 mDispatcher->notifyMotion(&motionArgs);
4343
4344 mNoInputWindow->assertNoEvents();
4345 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4346 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4347 // and therefore should prevent mBottomWindow from receiving touches
4348 mBottomWindow->assertNoEvents();
4349}
4350
4351/**
4352 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4353 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4354 */
4355TEST_F(InputDispatcherMultiWindowOcclusionTests,
4356 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4357 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4358 "Window with input channel and NO_INPUT_CHANNEL",
4359 ADISPLAY_ID_DEFAULT);
4360
chaviw98318de2021-05-19 16:45:23 -05004361 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004362 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4364
4365 PointF touchedPoint = {10, 10};
4366
4367 NotifyMotionArgs motionArgs =
4368 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4369 ADISPLAY_ID_DEFAULT, {touchedPoint});
4370 mDispatcher->notifyMotion(&motionArgs);
4371
4372 mNoInputWindow->assertNoEvents();
4373 mBottomWindow->assertNoEvents();
4374}
4375
Vishnu Nair958da932020-08-21 17:12:37 -07004376class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4377protected:
4378 std::shared_ptr<FakeApplicationHandle> mApp;
4379 sp<FakeWindowHandle> mWindow;
4380 sp<FakeWindowHandle> mMirror;
4381
4382 virtual void SetUp() override {
4383 InputDispatcherTest::SetUp();
4384 mApp = std::make_shared<FakeApplicationHandle>();
4385 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4386 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4387 mWindow->getToken());
4388 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4389 mWindow->setFocusable(true);
4390 mMirror->setFocusable(true);
4391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4392 }
4393};
4394
4395TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4396 // Request focus on a mirrored window
4397 setFocusedWindow(mMirror);
4398
4399 // window gets focused
4400 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4402 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004403 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4404}
4405
4406// A focused & mirrored window remains focused only if the window and its mirror are both
4407// focusable.
4408TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4409 setFocusedWindow(mMirror);
4410
4411 // window gets focused
4412 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004413 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4414 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004415 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4417 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004418 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4419
4420 mMirror->setFocusable(false);
4421 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4422
4423 // window loses focus since one of the windows associated with the token in not focusable
4424 mWindow->consumeFocusEvent(false);
4425
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004426 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4427 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004428 mWindow->assertNoEvents();
4429}
4430
4431// A focused & mirrored window remains focused until the window and its mirror both become
4432// invisible.
4433TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4434 setFocusedWindow(mMirror);
4435
4436 // window gets focused
4437 mWindow->consumeFocusEvent(true);
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 mMirror->setVisible(false);
4446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4447
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4449 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004450 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4452 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004453 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4454
4455 mWindow->setVisible(false);
4456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4457
4458 // window loses focus only after all windows associated with the token become invisible.
4459 mWindow->consumeFocusEvent(false);
4460
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004461 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4462 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004463 mWindow->assertNoEvents();
4464}
4465
4466// A focused & mirrored window remains focused until both windows are removed.
4467TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4468 setFocusedWindow(mMirror);
4469
4470 // window gets focused
4471 mWindow->consumeFocusEvent(true);
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 // single window is removed but the window token remains focused
4480 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4481
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4483 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004484 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4486 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004487 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4488
4489 // Both windows are removed
4490 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4491 mWindow->consumeFocusEvent(false);
4492
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004493 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4494 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004495 mWindow->assertNoEvents();
4496}
4497
4498// Focus request can be pending until one window becomes visible.
4499TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4500 // Request focus on an invisible mirror.
4501 mWindow->setVisible(false);
4502 mMirror->setVisible(false);
4503 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4504 setFocusedWindow(mMirror);
4505
4506 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004507 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004508 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004509 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004510
4511 mMirror->setVisible(true);
4512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4513
4514 // window gets focused
4515 mWindow->consumeFocusEvent(true);
4516 // window gets the pending key event
4517 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4518}
Prabir Pradhan99987712020-11-10 18:43:05 -08004519
4520class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4521protected:
4522 std::shared_ptr<FakeApplicationHandle> mApp;
4523 sp<FakeWindowHandle> mWindow;
4524 sp<FakeWindowHandle> mSecondWindow;
4525
4526 void SetUp() override {
4527 InputDispatcherTest::SetUp();
4528 mApp = std::make_shared<FakeApplicationHandle>();
4529 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4530 mWindow->setFocusable(true);
4531 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4532 mSecondWindow->setFocusable(true);
4533
4534 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4536
4537 setFocusedWindow(mWindow);
4538 mWindow->consumeFocusEvent(true);
4539 }
4540
4541 void notifyPointerCaptureChanged(bool enabled) {
4542 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
4543 mDispatcher->notifyPointerCaptureChanged(&args);
4544 }
4545
4546 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
4547 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4548 mFakePolicy->waitForSetPointerCapture(enabled);
4549 notifyPointerCaptureChanged(enabled);
4550 window->consumeCaptureEvent(enabled);
4551 }
4552};
4553
4554TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4555 // Ensure that capture cannot be obtained for unfocused windows.
4556 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4557 mFakePolicy->assertSetPointerCaptureNotCalled();
4558 mSecondWindow->assertNoEvents();
4559
4560 // Ensure that capture can be enabled from the focus window.
4561 requestAndVerifyPointerCapture(mWindow, true);
4562
4563 // Ensure that capture cannot be disabled from a window that does not have capture.
4564 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4565 mFakePolicy->assertSetPointerCaptureNotCalled();
4566
4567 // Ensure that capture can be disabled from the window with capture.
4568 requestAndVerifyPointerCapture(mWindow, false);
4569}
4570
4571TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4572 requestAndVerifyPointerCapture(mWindow, true);
4573
4574 setFocusedWindow(mSecondWindow);
4575
4576 // Ensure that the capture disabled event was sent first.
4577 mWindow->consumeCaptureEvent(false);
4578 mWindow->consumeFocusEvent(false);
4579 mSecondWindow->consumeFocusEvent(true);
4580 mFakePolicy->waitForSetPointerCapture(false);
4581
4582 // Ensure that additional state changes from InputReader are not sent to the window.
4583 notifyPointerCaptureChanged(false);
4584 notifyPointerCaptureChanged(true);
4585 notifyPointerCaptureChanged(false);
4586 mWindow->assertNoEvents();
4587 mSecondWindow->assertNoEvents();
4588 mFakePolicy->assertSetPointerCaptureNotCalled();
4589}
4590
4591TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4592 requestAndVerifyPointerCapture(mWindow, true);
4593
4594 // InputReader unexpectedly disables and enables pointer capture.
4595 notifyPointerCaptureChanged(false);
4596 notifyPointerCaptureChanged(true);
4597
4598 // Ensure that Pointer Capture is disabled.
Prabir Pradhan7d030382020-12-21 07:58:35 -08004599 mFakePolicy->waitForSetPointerCapture(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004600 mWindow->consumeCaptureEvent(false);
4601 mWindow->assertNoEvents();
4602}
4603
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004604TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4605 requestAndVerifyPointerCapture(mWindow, true);
4606
4607 // The first window loses focus.
4608 setFocusedWindow(mSecondWindow);
4609 mFakePolicy->waitForSetPointerCapture(false);
4610 mWindow->consumeCaptureEvent(false);
4611
4612 // Request Pointer Capture from the second window before the notification from InputReader
4613 // arrives.
4614 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4615 mFakePolicy->waitForSetPointerCapture(true);
4616
4617 // InputReader notifies Pointer Capture was disabled (because of the focus change).
4618 notifyPointerCaptureChanged(false);
4619
4620 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
4621 notifyPointerCaptureChanged(true);
4622
4623 mSecondWindow->consumeFocusEvent(true);
4624 mSecondWindow->consumeCaptureEvent(true);
4625}
4626
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004627class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4628protected:
4629 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00004630
4631 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4632 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4633
4634 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4635 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4636
4637 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4638 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4639 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4640 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4641 MAXIMUM_OBSCURING_OPACITY);
4642
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004643 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004644 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004645 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004646
4647 sp<FakeWindowHandle> mTouchWindow;
4648
4649 virtual void SetUp() override {
4650 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004651 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004652 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4653 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4654 }
4655
4656 virtual void TearDown() override {
4657 InputDispatcherTest::TearDown();
4658 mTouchWindow.clear();
4659 }
4660
chaviw98318de2021-05-19 16:45:23 -05004661 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
4662 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004663 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw98318de2021-05-19 16:45:23 -05004664 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004665 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004666 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004667 return window;
4668 }
4669
4670 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4671 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4672 sp<FakeWindowHandle> window =
4673 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4674 // Generate an arbitrary PID based on the UID
4675 window->setOwnerInfo(1777 + (uid % 10000), uid);
4676 return window;
4677 }
4678
4679 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4680 NotifyMotionArgs args =
4681 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4682 ADISPLAY_ID_DEFAULT, points);
4683 mDispatcher->notifyMotion(&args);
4684 }
4685};
4686
4687TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004688 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004689 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004690 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004691
4692 touch();
4693
4694 mTouchWindow->assertNoEvents();
4695}
4696
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004697TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00004698 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
4699 const sp<FakeWindowHandle>& w =
4700 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
4701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4702
4703 touch();
4704
4705 mTouchWindow->assertNoEvents();
4706}
4707
4708TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004709 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
4710 const sp<FakeWindowHandle>& w =
4711 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4713
4714 touch();
4715
4716 w->assertNoEvents();
4717}
4718
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004719TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004720 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
4721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004722
4723 touch();
4724
4725 mTouchWindow->consumeAnyMotionDown();
4726}
4727
4728TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004729 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004730 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004731 w->setFrame(Rect(0, 0, 50, 50));
4732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004733
4734 touch({PointF{100, 100}});
4735
4736 mTouchWindow->consumeAnyMotionDown();
4737}
4738
4739TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004740 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004741 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4743
4744 touch();
4745
4746 mTouchWindow->consumeAnyMotionDown();
4747}
4748
4749TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
4750 const sp<FakeWindowHandle>& w =
4751 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4752 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004753
4754 touch();
4755
4756 mTouchWindow->consumeAnyMotionDown();
4757}
4758
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004759TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
4760 const sp<FakeWindowHandle>& w =
4761 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4762 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4763
4764 touch();
4765
4766 w->assertNoEvents();
4767}
4768
4769/**
4770 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
4771 * inside) while letting them pass-through. Note that even though touch passes through the occluding
4772 * window, the occluding window will still receive ACTION_OUTSIDE event.
4773 */
4774TEST_F(InputDispatcherUntrustedTouchesTest,
4775 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
4776 const sp<FakeWindowHandle>& w =
4777 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw98318de2021-05-19 16:45:23 -05004778 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4780
4781 touch();
4782
4783 w->consumeMotionOutside();
4784}
4785
4786TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
4787 const sp<FakeWindowHandle>& w =
4788 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw98318de2021-05-19 16:45:23 -05004789 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004790 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4791
4792 touch();
4793
4794 InputEvent* event = w->consume();
4795 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
4796 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4797 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
4798 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
4799}
4800
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004801TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004802 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004803 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4804 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4806
4807 touch();
4808
4809 mTouchWindow->consumeAnyMotionDown();
4810}
4811
4812TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
4813 const sp<FakeWindowHandle>& w =
4814 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4815 MAXIMUM_OBSCURING_OPACITY);
4816 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004817
4818 touch();
4819
4820 mTouchWindow->consumeAnyMotionDown();
4821}
4822
4823TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004824 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004825 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4826 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4828
4829 touch();
4830
4831 mTouchWindow->assertNoEvents();
4832}
4833
4834TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
4835 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
4836 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004837 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4838 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004839 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004840 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4841 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004842 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4843
4844 touch();
4845
4846 mTouchWindow->assertNoEvents();
4847}
4848
4849TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
4850 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
4851 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004852 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4853 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004854 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004855 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4856 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004857 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4858
4859 touch();
4860
4861 mTouchWindow->consumeAnyMotionDown();
4862}
4863
4864TEST_F(InputDispatcherUntrustedTouchesTest,
4865 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
4866 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004867 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4868 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004869 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004870 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4871 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004872 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4873
4874 touch();
4875
4876 mTouchWindow->consumeAnyMotionDown();
4877}
4878
4879TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
4880 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004881 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4882 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004883 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004884 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4885 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004886 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004887
4888 touch();
4889
4890 mTouchWindow->assertNoEvents();
4891}
4892
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004893TEST_F(InputDispatcherUntrustedTouchesTest,
4894 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
4895 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004896 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4897 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004898 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004899 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4900 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4902
4903 touch();
4904
4905 mTouchWindow->assertNoEvents();
4906}
4907
4908TEST_F(InputDispatcherUntrustedTouchesTest,
4909 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
4910 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004911 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4912 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004913 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004914 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4915 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4917
4918 touch();
4919
4920 mTouchWindow->consumeAnyMotionDown();
4921}
4922
4923TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
4924 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004925 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4926 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4928
4929 touch();
4930
4931 mTouchWindow->consumeAnyMotionDown();
4932}
4933
4934TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
4935 const sp<FakeWindowHandle>& w =
4936 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
4937 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4938
4939 touch();
4940
4941 mTouchWindow->consumeAnyMotionDown();
4942}
4943
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004944TEST_F(InputDispatcherUntrustedTouchesTest,
4945 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
4946 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4947 const sp<FakeWindowHandle>& w =
4948 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
4949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4950
4951 touch();
4952
4953 mTouchWindow->assertNoEvents();
4954}
4955
4956TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
4957 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4958 const sp<FakeWindowHandle>& w =
4959 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
4960 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4961
4962 touch();
4963
4964 mTouchWindow->consumeAnyMotionDown();
4965}
4966
4967TEST_F(InputDispatcherUntrustedTouchesTest,
4968 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
4969 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
4970 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004971 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4972 OPACITY_ABOVE_THRESHOLD);
4973 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4974
4975 touch();
4976
4977 mTouchWindow->consumeAnyMotionDown();
4978}
4979
4980TEST_F(InputDispatcherUntrustedTouchesTest,
4981 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
4982 const sp<FakeWindowHandle>& w1 =
4983 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4984 OPACITY_BELOW_THRESHOLD);
4985 const sp<FakeWindowHandle>& w2 =
4986 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4987 OPACITY_BELOW_THRESHOLD);
4988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4989
4990 touch();
4991
4992 mTouchWindow->assertNoEvents();
4993}
4994
4995/**
4996 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
4997 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
4998 * (which alone would result in allowing touches) does not affect the blocking behavior.
4999 */
5000TEST_F(InputDispatcherUntrustedTouchesTest,
5001 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5002 const sp<FakeWindowHandle>& wB =
5003 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5004 OPACITY_BELOW_THRESHOLD);
5005 const sp<FakeWindowHandle>& wC =
5006 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5007 OPACITY_BELOW_THRESHOLD);
5008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5009
5010 touch();
5011
5012 mTouchWindow->assertNoEvents();
5013}
5014
5015/**
5016 * This test is testing that a window from a different UID but with same application token doesn't
5017 * block the touch. Apps can share the application token for close UI collaboration for example.
5018 */
5019TEST_F(InputDispatcherUntrustedTouchesTest,
5020 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5021 const sp<FakeWindowHandle>& w =
5022 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5023 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5025
5026 touch();
5027
5028 mTouchWindow->consumeAnyMotionDown();
5029}
5030
arthurhungb89ccb02020-12-30 16:19:01 +08005031class InputDispatcherDragTests : public InputDispatcherTest {
5032protected:
5033 std::shared_ptr<FakeApplicationHandle> mApp;
5034 sp<FakeWindowHandle> mWindow;
5035 sp<FakeWindowHandle> mSecondWindow;
5036 sp<FakeWindowHandle> mDragWindow;
5037
5038 void SetUp() override {
5039 InputDispatcherTest::SetUp();
5040 mApp = std::make_shared<FakeApplicationHandle>();
5041 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5042 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw98318de2021-05-19 16:45:23 -05005043 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005044
5045 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5046 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw98318de2021-05-19 16:45:23 -05005047 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005048
5049 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5050 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5051 }
5052
5053 // Start performing drag, we will create a drag window and transfer touch to it.
5054 void performDrag() {
5055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5056 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5057 {50, 50}))
5058 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5059
5060 // Window should receive motion event.
5061 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5062
5063 // The drag window covers the entire display
5064 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5065 mDispatcher->setInputWindows(
5066 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5067
5068 // Transfer touch focus to the drag window
5069 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5070 true /* isDragDrop */);
5071 mWindow->consumeMotionCancel();
5072 mDragWindow->consumeMotionDown();
5073 }
arthurhung6d4bed92021-03-17 11:59:33 +08005074
5075 // Start performing drag, we will create a drag window and transfer touch to it.
5076 void performStylusDrag() {
5077 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5078 injectMotionEvent(mDispatcher,
5079 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5080 AINPUT_SOURCE_STYLUS)
5081 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5082 .pointer(PointerBuilder(0,
5083 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5084 .x(50)
5085 .y(50))
5086 .build()));
5087 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5088
5089 // The drag window covers the entire display
5090 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5091 mDispatcher->setInputWindows(
5092 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5093
5094 // Transfer touch focus to the drag window
5095 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5096 true /* isDragDrop */);
5097 mWindow->consumeMotionCancel();
5098 mDragWindow->consumeMotionDown();
5099 }
arthurhungb89ccb02020-12-30 16:19:01 +08005100};
5101
5102TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5103 performDrag();
5104
5105 // Move on window.
5106 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5107 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5108 ADISPLAY_ID_DEFAULT, {50, 50}))
5109 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5110 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5111 mWindow->consumeDragEvent(false, 50, 50);
5112 mSecondWindow->assertNoEvents();
5113
5114 // Move to another window.
5115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5116 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5117 ADISPLAY_ID_DEFAULT, {150, 50}))
5118 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5119 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5120 mWindow->consumeDragEvent(true, 150, 50);
5121 mSecondWindow->consumeDragEvent(false, 50, 50);
5122
5123 // Move back to original window.
5124 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5125 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5126 ADISPLAY_ID_DEFAULT, {50, 50}))
5127 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5128 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5129 mWindow->consumeDragEvent(false, 50, 50);
5130 mSecondWindow->consumeDragEvent(true, -50, 50);
5131
5132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5133 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5134 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5135 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5136 mWindow->assertNoEvents();
5137 mSecondWindow->assertNoEvents();
5138}
5139
arthurhungf452d0b2021-01-06 00:19:52 +08005140TEST_F(InputDispatcherDragTests, DragAndDrop) {
5141 performDrag();
5142
5143 // Move on window.
5144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5145 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5146 ADISPLAY_ID_DEFAULT, {50, 50}))
5147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5148 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5149 mWindow->consumeDragEvent(false, 50, 50);
5150 mSecondWindow->assertNoEvents();
5151
5152 // Move to another window.
5153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5154 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5155 ADISPLAY_ID_DEFAULT, {150, 50}))
5156 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5157 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5158 mWindow->consumeDragEvent(true, 150, 50);
5159 mSecondWindow->consumeDragEvent(false, 50, 50);
5160
5161 // drop to another window.
5162 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5163 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5164 {150, 50}))
5165 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5166 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5167 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5168 mWindow->assertNoEvents();
5169 mSecondWindow->assertNoEvents();
5170}
5171
arthurhung6d4bed92021-03-17 11:59:33 +08005172TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5173 performStylusDrag();
5174
5175 // Move on window and keep button pressed.
5176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5177 injectMotionEvent(mDispatcher,
5178 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5179 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5180 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5181 .x(50)
5182 .y(50))
5183 .build()))
5184 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5185 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5186 mWindow->consumeDragEvent(false, 50, 50);
5187 mSecondWindow->assertNoEvents();
5188
5189 // Move to another window and release button, expect to drop item.
5190 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5191 injectMotionEvent(mDispatcher,
5192 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5193 .buttonState(0)
5194 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5195 .x(150)
5196 .y(50))
5197 .build()))
5198 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5199 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5200 mWindow->assertNoEvents();
5201 mSecondWindow->assertNoEvents();
5202 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5203
5204 // nothing to the window.
5205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5206 injectMotionEvent(mDispatcher,
5207 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5208 .buttonState(0)
5209 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5210 .x(150)
5211 .y(50))
5212 .build()))
5213 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5214 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5215 mWindow->assertNoEvents();
5216 mSecondWindow->assertNoEvents();
5217}
5218
Arthur Hung6d0571e2021-04-09 20:18:16 +08005219TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5220 performDrag();
5221
5222 // Set second window invisible.
5223 mSecondWindow->setVisible(false);
5224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5225
5226 // Move on window.
5227 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5228 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5229 ADISPLAY_ID_DEFAULT, {50, 50}))
5230 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5231 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5232 mWindow->consumeDragEvent(false, 50, 50);
5233 mSecondWindow->assertNoEvents();
5234
5235 // Move to another window.
5236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5237 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5238 ADISPLAY_ID_DEFAULT, {150, 50}))
5239 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5240 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5241 mWindow->consumeDragEvent(true, 150, 50);
5242 mSecondWindow->assertNoEvents();
5243
5244 // drop to another window.
5245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5246 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5247 {150, 50}))
5248 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5249 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5250 mFakePolicy->assertDropTargetEquals(nullptr);
5251 mWindow->assertNoEvents();
5252 mSecondWindow->assertNoEvents();
5253}
5254
Garfield Tane84e6f92019-08-29 17:28:41 -07005255} // namespace android::inputdispatcher