blob: b62fce4a1c00169c8b00355d95ba5197856c0565 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Garfield Tan1c7bc862020-01-28 13:24:04 -080019#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070020#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070021#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080022#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100023#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <linux/input.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100025
Garfield Tan1c7bc862020-01-28 13:24:04 -080026#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070027#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080028#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080029#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080030
Garfield Tan1c7bc862020-01-28 13:24:04 -080031using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080032using android::os::InputEventInjectionResult;
33using android::os::InputEventInjectionSync;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +000034using android::os::TouchOcclusionMode;
Michael Wright44753b12020-07-08 13:48:11 +010035using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080036
Garfield Tane84e6f92019-08-29 17:28:41 -070037namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
39// An arbitrary time value.
40static const nsecs_t ARBITRARY_TIME = 1234;
41
42// An arbitrary device id.
43static const int32_t DEVICE_ID = 1;
44
Jeff Brownf086ddb2014-02-11 14:28:48 -080045// An arbitrary display id.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -080046static const int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
Jeff Brownf086ddb2014-02-11 14:28:48 -080047
Michael Wrightd02c5b62014-02-10 15:10:22 -080048// An arbitrary injector pid / uid pair that has permission to inject events.
49static const int32_t INJECTOR_PID = 999;
50static const int32_t INJECTOR_UID = 1001;
51
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000052// An arbitrary pid of the gesture monitor window
53static constexpr int32_t MONITOR_PID = 2001;
54
chaviwd1c23182019-12-20 18:44:56 -080055struct PointF {
56 float x;
57 float y;
58};
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
Gang Wang342c9272020-01-13 13:15:04 -050060/**
61 * Return a DOWN key event with KEYCODE_A.
62 */
63static KeyEvent getTestKeyEvent() {
64 KeyEvent event;
65
Garfield Tanfbe732e2020-01-24 11:26:14 -080066 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
67 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
68 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050069 return event;
70}
71
Michael Wrightd02c5b62014-02-10 15:10:22 -080072// --- FakeInputDispatcherPolicy ---
73
74class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
75 InputDispatcherConfiguration mConfig;
76
77protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100078 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100081 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080082
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080083 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080084 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
85 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080086 }
87
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080088 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080089 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
90 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080091 }
92
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070093 void assertFilterInputEventWasNotCalled() {
94 std::scoped_lock lock(mLock);
95 ASSERT_EQ(nullptr, mFilteredEvent);
96 }
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080098 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070099 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800100 ASSERT_TRUE(mConfigurationChangedTime)
101 << "Timed out waiting for configuration changed call";
102 ASSERT_EQ(*mConfigurationChangedTime, when);
103 mConfigurationChangedTime = std::nullopt;
104 }
105
106 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700107 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800108 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800109 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800110 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
111 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
112 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
113 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
114 mLastNotifySwitch = std::nullopt;
115 }
116
chaviwfd6d3512019-03-25 13:23:49 -0700117 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700118 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800119 ASSERT_EQ(touchedToken, mOnPointerDownToken);
120 mOnPointerDownToken.clear();
121 }
122
123 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700124 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800125 ASSERT_TRUE(mOnPointerDownToken == nullptr)
126 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700127 }
128
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700129 // This function must be called soon after the expected ANR timer starts,
130 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500131 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700132 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500133 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
134 std::shared_ptr<InputApplicationHandle> application;
135 { // acquire lock
136 std::unique_lock lock(mLock);
137 android::base::ScopedLockAssertion assumeLocked(mLock);
138 ASSERT_NO_FATAL_FAILURE(
139 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
140 } // release lock
141 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700142 }
143
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000144 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
145 const sp<IBinder>& expectedConnectionToken) {
146 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500147 ASSERT_EQ(expectedConnectionToken, connectionToken);
148 }
149
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000150 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
151 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500152 ASSERT_EQ(expectedConnectionToken, connectionToken);
153 }
154
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000155 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
156 int32_t pid = getUnresponsiveMonitorPid(timeout);
157 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500158 }
159
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000160 void assertNotifyMonitorResponsiveWasCalled() {
161 int32_t pid = getResponsiveMonitorPid();
162 ASSERT_EQ(MONITOR_PID, pid);
163 }
164
165 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500166 std::unique_lock lock(mLock);
167 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000168 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
169 }
170
171 sp<IBinder> getResponsiveWindowToken() {
172 std::unique_lock lock(mLock);
173 android::base::ScopedLockAssertion assumeLocked(mLock);
174 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
175 }
176
177 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
178 std::unique_lock lock(mLock);
179 android::base::ScopedLockAssertion assumeLocked(mLock);
180 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
181 }
182
183 int32_t getResponsiveMonitorPid() {
184 std::unique_lock lock(mLock);
185 android::base::ScopedLockAssertion assumeLocked(mLock);
186 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500187 }
188
189 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
190 // for a specific container to become non-empty. When the container is non-empty, return the
191 // first entry from the container and erase it.
192 template <class T>
193 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
194 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
195 const std::chrono::time_point start = std::chrono::steady_clock::now();
196 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700197
198 // If there is an ANR, Dispatcher won't be idle because there are still events
199 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
200 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500201 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
202 // to provide it some time to act. 100ms seems reasonable.
203 mNotifyAnr.wait_for(lock, timeToWait,
204 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700205 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500206 if (storage.empty()) {
207 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000208 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700209 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700210 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
211 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700212 if (std::chrono::abs(timeout - waited) > 100ms) {
213 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
214 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
215 << "ms, but waited "
216 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
217 << "ms instead";
218 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500219 T token = storage.front();
220 storage.pop();
221 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700222 }
223
224 void assertNotifyAnrWasNotCalled() {
225 std::scoped_lock lock(mLock);
226 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000227 ASSERT_TRUE(mAnrWindowTokens.empty());
228 ASSERT_TRUE(mAnrMonitorPids.empty());
229 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500230 << "ANR was not called, but please also consume the 'connection is responsive' "
231 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000232 ASSERT_TRUE(mResponsiveMonitorPids.empty())
233 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
234 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700235 }
236
Garfield Tan1c7bc862020-01-28 13:24:04 -0800237 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
238 mConfig.keyRepeatTimeout = timeout;
239 mConfig.keyRepeatDelay = delay;
240 }
241
Prabir Pradhan99987712020-11-10 18:43:05 -0800242 void waitForSetPointerCapture(bool enabled) {
243 std::unique_lock lock(mLock);
244 base::ScopedLockAssertion assumeLocked(mLock);
245
246 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
247 [this, enabled]() REQUIRES(mLock) {
248 return mPointerCaptureEnabled &&
249 *mPointerCaptureEnabled ==
250 enabled;
251 })) {
252 FAIL() << "Timed out waiting for setPointerCapture(" << enabled << ") to be called.";
253 }
254 mPointerCaptureEnabled.reset();
255 }
256
257 void assertSetPointerCaptureNotCalled() {
258 std::unique_lock lock(mLock);
259 base::ScopedLockAssertion assumeLocked(mLock);
260
261 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
262 FAIL() << "Expected setPointerCapture(enabled) to not be called, but was called. "
263 "enabled = "
264 << *mPointerCaptureEnabled;
265 }
266 mPointerCaptureEnabled.reset();
267 }
268
arthurhungf452d0b2021-01-06 00:19:52 +0800269 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
270 std::scoped_lock lock(mLock);
271 ASSERT_EQ(targetToken, mDropTargetWindowToken);
272 }
273
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700275 std::mutex mLock;
276 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
277 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
278 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
279 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800280
Prabir Pradhan99987712020-11-10 18:43:05 -0800281 std::condition_variable mPointerCaptureChangedCondition;
282 std::optional<bool> mPointerCaptureEnabled GUARDED_BY(mLock);
283
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700284 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700285 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000286 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
287 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
288 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
289 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700290 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700291
arthurhungf452d0b2021-01-06 00:19:52 +0800292 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
293
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600294 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700295 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800296 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800297 }
298
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000299 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700300 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000301 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700302 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500303 }
304
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000305 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500306 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000307 mAnrMonitorPids.push(pid);
308 mNotifyAnr.notify_all();
309 }
310
311 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
312 std::scoped_lock lock(mLock);
313 mResponsiveWindowTokens.push(connectionToken);
314 mNotifyAnr.notify_all();
315 }
316
317 void notifyMonitorResponsive(int32_t pid) override {
318 std::scoped_lock lock(mLock);
319 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500320 mNotifyAnr.notify_all();
321 }
322
323 void notifyNoFocusedWindowAnr(
324 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
325 std::scoped_lock lock(mLock);
326 mAnrApplications.push(applicationHandle);
327 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800328 }
329
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600330 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600332 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700333
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600334 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700335 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
336 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
337 const std::vector<float>& values) override {}
338
339 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
340 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000341
Chris Yefb552902021-02-03 17:18:37 -0800342 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
343
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600344 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800345 *outConfig = mConfig;
346 }
347
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600348 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700349 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800350 switch (inputEvent->getType()) {
351 case AINPUT_EVENT_TYPE_KEY: {
352 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800353 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800354 break;
355 }
356
357 case AINPUT_EVENT_TYPE_MOTION: {
358 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800359 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800360 break;
361 }
362 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800363 return true;
364 }
365
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600366 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800367
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600368 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800369
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600370 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800371 return 0;
372 }
373
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600374 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800375 return false;
376 }
377
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600378 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
379 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700380 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800381 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
382 * essentially a passthrough for notifySwitch.
383 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800384 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385 }
386
Sean Stoutb4e0a592021-02-23 07:34:53 -0800387 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800389 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
390 return pid == INJECTOR_PID && uid == INJECTOR_UID;
391 }
Jackal Guof9696682018-10-05 12:23:23 +0800392
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600393 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700394 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700395 mOnPointerDownToken = newToken;
396 }
397
Prabir Pradhan99987712020-11-10 18:43:05 -0800398 void setPointerCapture(bool enabled) override {
399 std::scoped_lock lock(mLock);
400 mPointerCaptureEnabled = {enabled};
401 mPointerCaptureChangedCondition.notify_all();
402 }
403
arthurhungf452d0b2021-01-06 00:19:52 +0800404 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
405 std::scoped_lock lock(mLock);
406 mDropTargetWindowToken = token;
407 }
408
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800409 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
410 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700411 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800412 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
413 ASSERT_EQ(mFilteredEvent->getType(), type);
414
415 if (type == AINPUT_EVENT_TYPE_KEY) {
416 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
417 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
418 EXPECT_EQ(keyEvent.getAction(), action);
419 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
420 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
421 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
422 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
423 EXPECT_EQ(motionEvent.getAction(), action);
424 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
425 } else {
426 FAIL() << "Unknown type: " << type;
427 }
428
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800429 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431};
432
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433// --- InputDispatcherTest ---
434
435class InputDispatcherTest : public testing::Test {
436protected:
437 sp<FakeInputDispatcherPolicy> mFakePolicy;
438 sp<InputDispatcher> mDispatcher;
439
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700440 virtual void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441 mFakePolicy = new FakeInputDispatcherPolicy();
442 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800443 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000444 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700445 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800446 }
447
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700448 virtual void TearDown() override {
449 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 mFakePolicy.clear();
451 mDispatcher.clear();
452 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700453
454 /**
455 * Used for debugging when writing the test
456 */
457 void dumpDispatcherState() {
458 std::string dump;
459 mDispatcher->dump(dump);
460 std::stringstream ss(dump);
461 std::string to;
462
463 while (std::getline(ss, to, '\n')) {
464 ALOGE("%s", to.c_str());
465 }
466 }
Vishnu Nair958da932020-08-21 17:12:37 -0700467
468 void setFocusedWindow(const sp<InputWindowHandle>& window,
469 const sp<InputWindowHandle>& focusedWindow = nullptr) {
470 FocusRequest request;
471 request.token = window->getToken();
472 if (focusedWindow) {
473 request.focusedToken = focusedWindow->getToken();
474 }
475 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
476 request.displayId = window->getInfo()->displayId;
477 mDispatcher->setFocusedWindow(request);
478 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479};
480
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
482 KeyEvent event;
483
484 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800485 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
486 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600487 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
488 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800489 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700490 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800491 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 << "Should reject key events with undefined action.";
493
494 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800495 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
496 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600497 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800498 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700499 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800500 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501 << "Should reject key events with ACTION_MULTIPLE.";
502}
503
504TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
505 MotionEvent event;
506 PointerProperties pointerProperties[MAX_POINTERS + 1];
507 PointerCoords pointerCoords[MAX_POINTERS + 1];
508 for (int i = 0; i <= MAX_POINTERS; i++) {
509 pointerProperties[i].clear();
510 pointerProperties[i].id = i;
511 pointerCoords[i].clear();
512 }
513
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800514 // Some constants commonly used below
515 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
516 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
517 constexpr int32_t metaState = AMETA_NONE;
518 constexpr MotionClassification classification = MotionClassification::NONE;
519
chaviw9eaa22c2020-07-01 16:21:27 -0700520 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800522 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700523 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
524 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600525 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700526 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800527 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700528 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800529 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 << "Should reject motion events with undefined action.";
531
532 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800533 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700534 AMOTION_EVENT_ACTION_POINTER_DOWN |
535 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700536 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
537 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
538 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
539 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800540 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700541 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800542 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 << "Should reject motion events with pointer down index too large.";
544
Garfield Tanfbe732e2020-01-24 11:26:14 -0800545 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700546 AMOTION_EVENT_ACTION_POINTER_DOWN |
547 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700548 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
549 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
550 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
551 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800552 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700553 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800554 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800555 << "Should reject motion events with pointer down index too small.";
556
557 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800558 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700559 AMOTION_EVENT_ACTION_POINTER_UP |
560 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700561 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
562 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
563 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
564 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800565 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700566 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800567 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800568 << "Should reject motion events with pointer up index too large.";
569
Garfield Tanfbe732e2020-01-24 11:26:14 -0800570 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700571 AMOTION_EVENT_ACTION_POINTER_UP |
572 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700573 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
574 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
575 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
576 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800577 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700578 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800579 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 << "Should reject motion events with pointer up index too small.";
581
582 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800583 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
584 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700585 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
586 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700587 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800588 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700589 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800590 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 << "Should reject motion events with 0 pointers.";
592
Garfield Tanfbe732e2020-01-24 11:26:14 -0800593 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
594 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700595 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
596 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700597 /*pointerCount*/ MAX_POINTERS + 1, 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 more than MAX_POINTERS pointers.";
602
603 // Rejects motion events with invalid pointer ids.
604 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800605 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
606 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700607 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
608 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700609 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800610 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700611 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800612 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613 << "Should reject motion events with pointer ids less than 0.";
614
615 pointerProperties[0].id = MAX_POINTER_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,
619 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700620 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800621 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700622 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800623 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
625
626 // Rejects motion events with duplicate pointer ids.
627 pointerProperties[0].id = 1;
628 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800629 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
630 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700631 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
632 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700633 /*pointerCount*/ 2, 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 duplicate pointer ids.";
638}
639
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800640/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
641
642TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
643 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800644 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800645 mDispatcher->notifyConfigurationChanged(&args);
646 ASSERT_TRUE(mDispatcher->waitForIdle());
647
648 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
649}
650
651TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800652 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
653 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800654 mDispatcher->notifySwitch(&args);
655
656 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
657 args.policyFlags |= POLICY_FLAG_TRUSTED;
658 mFakePolicy->assertNotifySwitchWasCalled(args);
659}
660
Arthur Hungb92218b2018-08-14 12:00:21 +0800661// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700662static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700663static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800664
665class FakeApplicationHandle : public InputApplicationHandle {
666public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700667 FakeApplicationHandle() {
668 mInfo.name = "Fake Application";
669 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500670 mInfo.dispatchingTimeoutMillis =
671 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700672 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800673 virtual ~FakeApplicationHandle() {}
674
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000675 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700676
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500677 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
678 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700679 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800680};
681
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800682class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800683public:
Garfield Tan15601662020-09-22 15:32:38 -0700684 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800685 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700686 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800687 }
688
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800689 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700690 InputEvent* event;
691 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
692 if (!consumeSeq) {
693 return nullptr;
694 }
695 finishEvent(*consumeSeq);
696 return event;
697 }
698
699 /**
700 * Receive an event without acknowledging it.
701 * Return the sequence number that could later be used to send finished signal.
702 */
703 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800704 uint32_t consumeSeq;
705 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800706
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800707 std::chrono::time_point start = std::chrono::steady_clock::now();
708 status_t status = WOULD_BLOCK;
709 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800710 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800711 &event);
712 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
713 if (elapsed > 100ms) {
714 break;
715 }
716 }
717
718 if (status == WOULD_BLOCK) {
719 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700720 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800721 }
722
723 if (status != OK) {
724 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700725 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800726 }
727 if (event == nullptr) {
728 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700729 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800730 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700731 if (outEvent != nullptr) {
732 *outEvent = event;
733 }
734 return consumeSeq;
735 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800736
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700737 /**
738 * To be used together with "receiveEvent" to complete the consumption of an event.
739 */
740 void finishEvent(uint32_t consumeSeq) {
741 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
742 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800743 }
744
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000745 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
746 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
747 ASSERT_EQ(OK, status);
748 }
749
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000750 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
751 std::optional<int32_t> expectedDisplayId,
752 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800753 InputEvent* event = consume();
754
755 ASSERT_NE(nullptr, event) << mName.c_str()
756 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800757 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700758 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800759 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800760
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000761 if (expectedDisplayId.has_value()) {
762 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
763 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800764
Tiger Huang8664f8c2018-10-11 19:14:35 +0800765 switch (expectedEventType) {
766 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800767 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
768 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000769 if (expectedFlags.has_value()) {
770 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
771 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800772 break;
773 }
774 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800775 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
776 EXPECT_EQ(expectedAction, motionEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000777 if (expectedFlags.has_value()) {
778 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
779 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800780 break;
781 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100782 case AINPUT_EVENT_TYPE_FOCUS: {
783 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
784 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800785 case AINPUT_EVENT_TYPE_CAPTURE: {
786 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
787 }
arthurhungb89ccb02020-12-30 16:19:01 +0800788 case AINPUT_EVENT_TYPE_DRAG: {
789 FAIL() << "Use 'consumeDragEvent' for DRAG events";
790 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800791 default: {
792 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
793 }
794 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800795 }
796
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100797 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
798 InputEvent* event = consume();
799 ASSERT_NE(nullptr, event) << mName.c_str()
800 << ": consumer should have returned non-NULL event.";
801 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
802 << "Got " << inputEventTypeToString(event->getType())
803 << " event instead of FOCUS event";
804
805 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
806 << mName.c_str() << ": event displayId should always be NONE.";
807
808 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
809 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
810 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
811 }
812
Prabir Pradhan99987712020-11-10 18:43:05 -0800813 void consumeCaptureEvent(bool hasCapture) {
814 const InputEvent* event = consume();
815 ASSERT_NE(nullptr, event) << mName.c_str()
816 << ": consumer should have returned non-NULL event.";
817 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
818 << "Got " << inputEventTypeToString(event->getType())
819 << " event instead of CAPTURE event";
820
821 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
822 << mName.c_str() << ": event displayId should always be NONE.";
823
824 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
825 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
826 }
827
arthurhungb89ccb02020-12-30 16:19:01 +0800828 void consumeDragEvent(bool isExiting, float x, float y) {
829 const InputEvent* event = consume();
830 ASSERT_NE(nullptr, event) << mName.c_str()
831 << ": consumer should have returned non-NULL event.";
832 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
833 << "Got " << inputEventTypeToString(event->getType())
834 << " event instead of DRAG event";
835
836 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
837 << mName.c_str() << ": event displayId should always be NONE.";
838
839 const auto& dragEvent = static_cast<const DragEvent&>(*event);
840 EXPECT_EQ(isExiting, dragEvent.isExiting());
841 EXPECT_EQ(x, dragEvent.getX());
842 EXPECT_EQ(y, dragEvent.getY());
843 }
844
chaviwd1c23182019-12-20 18:44:56 -0800845 void assertNoEvents() {
846 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700847 if (event == nullptr) {
848 return;
849 }
850 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
851 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
852 ADD_FAILURE() << "Received key event "
853 << KeyEvent::actionToString(keyEvent.getAction());
854 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
855 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
856 ADD_FAILURE() << "Received motion event "
857 << MotionEvent::actionToString(motionEvent.getAction());
858 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
859 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
860 ADD_FAILURE() << "Received focus event, hasFocus = "
861 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800862 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
863 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
864 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
865 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700866 }
867 FAIL() << mName.c_str()
868 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800869 }
870
871 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
872
873protected:
874 std::unique_ptr<InputConsumer> mConsumer;
875 PreallocatedInputEventFactory mEventFactory;
876
877 std::string mName;
878};
879
880class FakeWindowHandle : public InputWindowHandle {
881public:
882 static const int32_t WIDTH = 600;
883 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800884
Chris Yea209fde2020-07-22 13:54:51 -0700885 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800886 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500887 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800888 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500889 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700890 base::Result<std::unique_ptr<InputChannel>> channel =
891 dispatcher->createInputChannel(name);
892 token = (*channel)->getConnectionToken();
893 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800894 }
895
896 inputApplicationHandle->updateInfo();
897 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
898
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500899 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700900 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800901 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100902 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500903 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000904 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800905 mInfo.frameLeft = 0;
906 mInfo.frameTop = 0;
907 mInfo.frameRight = WIDTH;
908 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700909 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800910 mInfo.globalScaleFactor = 1.0;
911 mInfo.touchableRegion.clear();
912 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
913 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700914 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800915 mInfo.hasWallpaper = false;
916 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800917 mInfo.ownerPid = INJECTOR_PID;
918 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800919 mInfo.displayId = displayId;
920 }
921
922 virtual bool updateInfo() { return true; }
923
Vishnu Nair47074b82020-08-14 11:54:47 -0700924 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800925
Vishnu Nair958da932020-08-21 17:12:37 -0700926 void setVisible(bool visible) { mInfo.visible = visible; }
927
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700928 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500929 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700930 }
931
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700932 void setPaused(bool paused) { mInfo.paused = paused; }
933
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000934 void setAlpha(float alpha) { mInfo.alpha = alpha; }
935
936 void setTouchOcclusionMode(android::os::TouchOcclusionMode mode) {
937 mInfo.touchOcclusionMode = mode;
938 }
939
Bernardo Rufino7393d172021-02-26 13:56:11 +0000940 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
941
chaviwd1c23182019-12-20 18:44:56 -0800942 void setFrame(const Rect& frame) {
943 mInfo.frameLeft = frame.left;
944 mInfo.frameTop = frame.top;
945 mInfo.frameRight = frame.right;
946 mInfo.frameBottom = frame.bottom;
arthurhungb89ccb02020-12-30 16:19:01 +0800947 mInfo.transform.set(-frame.left, -frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800948 mInfo.touchableRegion.clear();
949 mInfo.addTouchableRegion(frame);
950 }
951
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000952 void addFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags |= flags; }
953
Michael Wright44753b12020-07-08 13:48:11 +0100954 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800955
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500956 void setInputFeatures(InputWindowInfo::Feature features) { mInfo.inputFeatures = features; }
957
chaviw9eaa22c2020-07-01 16:21:27 -0700958 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
959 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
960 }
961
962 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700963
yunho.shinf4a80b82020-11-16 21:13:57 +0900964 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
965
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800966 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
967 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
968 expectedFlags);
969 }
970
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700971 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
972 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
973 }
974
Svet Ganov5d3bc372020-01-26 23:11:07 -0800975 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000976 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800977 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
978 expectedFlags);
979 }
980
981 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000982 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800983 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
984 expectedFlags);
985 }
986
987 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000988 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000989 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
990 }
991
992 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
993 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800994 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
995 expectedFlags);
996 }
997
Svet Ganov5d3bc372020-01-26 23:11:07 -0800998 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000999 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1000 int32_t expectedFlags = 0) {
1001 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1002 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001003 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1004 }
1005
1006 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001007 int32_t expectedFlags = 0) {
1008 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1009 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001010 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1011 }
1012
1013 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001014 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001015 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1016 expectedFlags);
1017 }
1018
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001019 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1020 int32_t expectedFlags = 0) {
1021 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1022 expectedFlags);
1023 }
1024
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001025 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1026 ASSERT_NE(mInputReceiver, nullptr)
1027 << "Cannot consume events from a window with no receiver";
1028 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1029 }
1030
Prabir Pradhan99987712020-11-10 18:43:05 -08001031 void consumeCaptureEvent(bool hasCapture) {
1032 ASSERT_NE(mInputReceiver, nullptr)
1033 << "Cannot consume events from a window with no receiver";
1034 mInputReceiver->consumeCaptureEvent(hasCapture);
1035 }
1036
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001037 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1038 std::optional<int32_t> expectedDisplayId,
1039 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001040 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1041 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1042 expectedFlags);
1043 }
1044
arthurhungb89ccb02020-12-30 16:19:01 +08001045 void consumeDragEvent(bool isExiting, float x, float y) {
1046 mInputReceiver->consumeDragEvent(isExiting, x, y);
1047 }
1048
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001049 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001050 if (mInputReceiver == nullptr) {
1051 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1052 return std::nullopt;
1053 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001054 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001055 }
1056
1057 void finishEvent(uint32_t sequenceNum) {
1058 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1059 mInputReceiver->finishEvent(sequenceNum);
1060 }
1061
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001062 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1063 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1064 mInputReceiver->sendTimeline(inputEventId, timeline);
1065 }
1066
chaviwaf87b3e2019-10-01 16:59:28 -07001067 InputEvent* consume() {
1068 if (mInputReceiver == nullptr) {
1069 return nullptr;
1070 }
1071 return mInputReceiver->consume();
1072 }
1073
Arthur Hungb92218b2018-08-14 12:00:21 +08001074 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001075 if (mInputReceiver == nullptr &&
1076 mInfo.inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL)) {
1077 return; // Can't receive events if the window does not have input channel
1078 }
1079 ASSERT_NE(nullptr, mInputReceiver)
1080 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001081 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001082 }
1083
chaviwaf87b3e2019-10-01 16:59:28 -07001084 sp<IBinder> getToken() { return mInfo.token; }
1085
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001086 const std::string& getName() { return mName; }
1087
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001088 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1089 mInfo.ownerPid = ownerPid;
1090 mInfo.ownerUid = ownerUid;
1091 }
1092
chaviwd1c23182019-12-20 18:44:56 -08001093private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001094 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001095 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001096 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001097};
1098
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001099std::atomic<int32_t> FakeWindowHandle::sId{1};
1100
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001101static InputEventInjectionResult injectKey(
1102 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1103 int32_t displayId = ADISPLAY_ID_NONE,
1104 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001105 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1106 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001107 KeyEvent event;
1108 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1109
1110 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001111 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001112 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1113 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001114
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001115 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1116 if (!allowKeyRepeat) {
1117 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1118 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001119 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001120 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001121 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001122}
1123
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001124static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1125 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001126 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1127}
1128
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001129// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1130// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1131// has to be woken up to process the repeating key.
1132static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1133 int32_t displayId = ADISPLAY_ID_NONE) {
1134 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1135 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1136 /* allowKeyRepeat */ false);
1137}
1138
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001139static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1140 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001141 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1142}
1143
Garfield Tandf26e862020-07-01 20:18:19 -07001144class PointerBuilder {
1145public:
1146 PointerBuilder(int32_t id, int32_t toolType) {
1147 mProperties.clear();
1148 mProperties.id = id;
1149 mProperties.toolType = toolType;
1150 mCoords.clear();
1151 }
1152
1153 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1154
1155 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1156
1157 PointerBuilder& axis(int32_t axis, float value) {
1158 mCoords.setAxisValue(axis, value);
1159 return *this;
1160 }
1161
1162 PointerProperties buildProperties() const { return mProperties; }
1163
1164 PointerCoords buildCoords() const { return mCoords; }
1165
1166private:
1167 PointerProperties mProperties;
1168 PointerCoords mCoords;
1169};
1170
1171class MotionEventBuilder {
1172public:
1173 MotionEventBuilder(int32_t action, int32_t source) {
1174 mAction = action;
1175 mSource = source;
1176 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1177 }
1178
1179 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1180 mEventTime = eventTime;
1181 return *this;
1182 }
1183
1184 MotionEventBuilder& displayId(int32_t displayId) {
1185 mDisplayId = displayId;
1186 return *this;
1187 }
1188
1189 MotionEventBuilder& actionButton(int32_t actionButton) {
1190 mActionButton = actionButton;
1191 return *this;
1192 }
1193
arthurhung6d4bed92021-03-17 11:59:33 +08001194 MotionEventBuilder& buttonState(int32_t buttonState) {
1195 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001196 return *this;
1197 }
1198
1199 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1200 mRawXCursorPosition = rawXCursorPosition;
1201 return *this;
1202 }
1203
1204 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1205 mRawYCursorPosition = rawYCursorPosition;
1206 return *this;
1207 }
1208
1209 MotionEventBuilder& pointer(PointerBuilder pointer) {
1210 mPointers.push_back(pointer);
1211 return *this;
1212 }
1213
1214 MotionEvent build() {
1215 std::vector<PointerProperties> pointerProperties;
1216 std::vector<PointerCoords> pointerCoords;
1217 for (const PointerBuilder& pointer : mPointers) {
1218 pointerProperties.push_back(pointer.buildProperties());
1219 pointerCoords.push_back(pointer.buildCoords());
1220 }
1221
1222 // Set mouse cursor position for the most common cases to avoid boilerplate.
1223 if (mSource == AINPUT_SOURCE_MOUSE &&
1224 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1225 mPointers.size() == 1) {
1226 mRawXCursorPosition = pointerCoords[0].getX();
1227 mRawYCursorPosition = pointerCoords[0].getY();
1228 }
1229
1230 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001231 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001232 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
1233 mAction, mActionButton, /* flags */ 0, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001234 mButtonState, MotionClassification::NONE, identityTransform,
1235 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
1236 mRawYCursorPosition, mEventTime, mEventTime, mPointers.size(),
1237 pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001238
1239 return event;
1240 }
1241
1242private:
1243 int32_t mAction;
1244 int32_t mSource;
1245 nsecs_t mEventTime;
1246 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1247 int32_t mActionButton{0};
1248 int32_t mButtonState{0};
1249 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1250 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1251
1252 std::vector<PointerBuilder> mPointers;
1253};
1254
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001255static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001256 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1257 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001258 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001259 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1260 injectionTimeout,
1261 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1262}
1263
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001264static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001265 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1266 const PointF& position,
1267 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001268 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1269 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001270 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001271 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001272 MotionEvent event = MotionEventBuilder(action, source)
1273 .displayId(displayId)
1274 .eventTime(eventTime)
1275 .rawXCursorPosition(cursorPosition.x)
1276 .rawYCursorPosition(cursorPosition.y)
1277 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1278 .x(position.x)
1279 .y(position.y))
1280 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001281
1282 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001283 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001284}
1285
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001286static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1287 int32_t source, int32_t displayId,
1288 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001289 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001290}
1291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1293 int32_t source, int32_t displayId,
1294 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001295 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001296}
1297
Jackal Guof9696682018-10-05 12:23:23 +08001298static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1299 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1300 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001301 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1302 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1303 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001304
1305 return args;
1306}
1307
chaviwd1c23182019-12-20 18:44:56 -08001308static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1309 const std::vector<PointF>& points) {
1310 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001311 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1312 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1313 }
1314
chaviwd1c23182019-12-20 18:44:56 -08001315 PointerProperties pointerProperties[pointerCount];
1316 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001317
chaviwd1c23182019-12-20 18:44:56 -08001318 for (size_t i = 0; i < pointerCount; i++) {
1319 pointerProperties[i].clear();
1320 pointerProperties[i].id = i;
1321 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001322
chaviwd1c23182019-12-20 18:44:56 -08001323 pointerCoords[i].clear();
1324 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1325 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1326 }
Jackal Guof9696682018-10-05 12:23:23 +08001327
1328 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1329 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001330 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001331 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1332 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001333 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1334 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001335 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1336 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001337
1338 return args;
1339}
1340
chaviwd1c23182019-12-20 18:44:56 -08001341static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1342 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1343}
1344
Prabir Pradhan99987712020-11-10 18:43:05 -08001345static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(bool enabled) {
1346 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), enabled);
1347}
1348
Arthur Hungb92218b2018-08-14 12:00:21 +08001349TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001350 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001351 sp<FakeWindowHandle> window =
1352 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001353
Arthur Hung72d8dc32020-03-28 00:48:39 +00001354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1356 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1357 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001358
1359 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001360 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001361}
1362
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001363/**
1364 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1365 * To ensure that window receives only events that were directly inside of it, add
1366 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1367 * when finding touched windows.
1368 * This test serves as a sanity check for the next test, where setInputWindows is
1369 * called twice.
1370 */
1371TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001372 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001373 sp<FakeWindowHandle> window =
1374 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1375 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001376 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001377
1378 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001380 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1381 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001382 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001383
1384 // Window should receive motion event.
1385 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1386}
1387
1388/**
1389 * Calling setInputWindows twice, with the same info, should not cause any issues.
1390 * To ensure that window receives only events that were directly inside of it, add
1391 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1392 * when finding touched windows.
1393 */
1394TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001395 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001396 sp<FakeWindowHandle> window =
1397 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1398 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001399 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001400
1401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001404 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1405 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001407
1408 // Window should receive motion event.
1409 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1410}
1411
Arthur Hungb92218b2018-08-14 12:00:21 +08001412// The foreground window should receive the first touch down event.
1413TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001414 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001415 sp<FakeWindowHandle> windowTop =
1416 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1417 sp<FakeWindowHandle> windowSecond =
1418 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001419
Arthur Hung72d8dc32020-03-28 00:48:39 +00001420 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001421 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1422 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1423 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001424
1425 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001426 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001427 windowSecond->assertNoEvents();
1428}
1429
Garfield Tandf26e862020-07-01 20:18:19 -07001430TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001431 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001432 sp<FakeWindowHandle> windowLeft =
1433 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1434 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001435 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001436 sp<FakeWindowHandle> windowRight =
1437 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1438 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001439 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001440
1441 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1442
1443 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1444
1445 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001447 injectMotionEvent(mDispatcher,
1448 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1449 AINPUT_SOURCE_MOUSE)
1450 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1451 .x(900)
1452 .y(400))
1453 .build()));
1454 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1455 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1456 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1457 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1458
1459 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001460 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001461 injectMotionEvent(mDispatcher,
1462 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1463 AINPUT_SOURCE_MOUSE)
1464 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1465 .x(300)
1466 .y(400))
1467 .build()));
1468 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1469 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1470 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1471 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1472 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1473 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1474
1475 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001476 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001477 injectMotionEvent(mDispatcher,
1478 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1479 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1480 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1481 .x(300)
1482 .y(400))
1483 .build()));
1484 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1485
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001487 injectMotionEvent(mDispatcher,
1488 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1489 AINPUT_SOURCE_MOUSE)
1490 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1491 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1492 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1493 .x(300)
1494 .y(400))
1495 .build()));
1496 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1497 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1498
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001500 injectMotionEvent(mDispatcher,
1501 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1502 AINPUT_SOURCE_MOUSE)
1503 .buttonState(0)
1504 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1505 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1506 .x(300)
1507 .y(400))
1508 .build()));
1509 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1510 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1511
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001512 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001513 injectMotionEvent(mDispatcher,
1514 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1515 .buttonState(0)
1516 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1517 .x(300)
1518 .y(400))
1519 .build()));
1520 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1521
1522 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001524 injectMotionEvent(mDispatcher,
1525 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1526 AINPUT_SOURCE_MOUSE)
1527 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1528 .x(900)
1529 .y(400))
1530 .build()));
1531 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1532 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1533 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1534 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1535 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1536 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1537}
1538
1539// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1540// directly in this test.
1541TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001542 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001543 sp<FakeWindowHandle> window =
1544 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1545 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001546 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001547
1548 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1549
1550 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1551
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001553 injectMotionEvent(mDispatcher,
1554 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1555 AINPUT_SOURCE_MOUSE)
1556 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1557 .x(300)
1558 .y(400))
1559 .build()));
1560 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1561 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1562
1563 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001565 injectMotionEvent(mDispatcher,
1566 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1567 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1568 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1569 .x(300)
1570 .y(400))
1571 .build()));
1572 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1573
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001575 injectMotionEvent(mDispatcher,
1576 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1577 AINPUT_SOURCE_MOUSE)
1578 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1579 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1580 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1581 .x(300)
1582 .y(400))
1583 .build()));
1584 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1585 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1586
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001587 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001588 injectMotionEvent(mDispatcher,
1589 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1590 AINPUT_SOURCE_MOUSE)
1591 .buttonState(0)
1592 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1593 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1594 .x(300)
1595 .y(400))
1596 .build()));
1597 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1598 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1599
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001601 injectMotionEvent(mDispatcher,
1602 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1603 .buttonState(0)
1604 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1605 .x(300)
1606 .y(400))
1607 .build()));
1608 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1609
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001611 injectMotionEvent(mDispatcher,
1612 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1613 AINPUT_SOURCE_MOUSE)
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_HOVER_EXIT,
1619 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1620}
1621
Garfield Tan00f511d2019-06-12 16:55:40 -07001622TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001623 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001624
1625 sp<FakeWindowHandle> windowLeft =
1626 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1627 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001628 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001629 sp<FakeWindowHandle> windowRight =
1630 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1631 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001632 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001633
1634 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1635
Arthur Hung72d8dc32020-03-28 00:48:39 +00001636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001637
1638 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1639 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001641 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001642 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001643 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001644 windowRight->assertNoEvents();
1645}
1646
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001647TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001648 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001649 sp<FakeWindowHandle> window =
1650 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001651 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001652
Arthur Hung72d8dc32020-03-28 00:48:39 +00001653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001654 setFocusedWindow(window);
1655
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001656 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001657
1658 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1659 mDispatcher->notifyKey(&keyArgs);
1660
1661 // Window should receive key down event.
1662 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1663
1664 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1665 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001666 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001667 mDispatcher->notifyDeviceReset(&args);
1668 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1669 AKEY_EVENT_FLAG_CANCELED);
1670}
1671
1672TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001673 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001674 sp<FakeWindowHandle> window =
1675 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1676
Arthur Hung72d8dc32020-03-28 00:48:39 +00001677 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001678
1679 NotifyMotionArgs motionArgs =
1680 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1681 ADISPLAY_ID_DEFAULT);
1682 mDispatcher->notifyMotion(&motionArgs);
1683
1684 // Window should receive motion down event.
1685 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1686
1687 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1688 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001689 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001690 mDispatcher->notifyDeviceReset(&args);
1691 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1692 0 /*expectedFlags*/);
1693}
1694
Svet Ganov5d3bc372020-01-26 23:11:07 -08001695TEST_F(InputDispatcherTest, TransferTouchFocus_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001696 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001697
1698 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001699 sp<FakeWindowHandle> firstWindow =
1700 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1701 sp<FakeWindowHandle> secondWindow =
1702 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001703
1704 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001706
1707 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001708 NotifyMotionArgs downMotionArgs =
1709 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1710 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001711 mDispatcher->notifyMotion(&downMotionArgs);
1712 // Only the first window should get the down event
1713 firstWindow->consumeMotionDown();
1714 secondWindow->assertNoEvents();
1715
1716 // Transfer touch focus to the second window
1717 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1718 // The first window gets cancel and the second gets down
1719 firstWindow->consumeMotionCancel();
1720 secondWindow->consumeMotionDown();
1721
1722 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001723 NotifyMotionArgs upMotionArgs =
1724 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1725 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001726 mDispatcher->notifyMotion(&upMotionArgs);
1727 // The first window gets no events and the second gets up
1728 firstWindow->assertNoEvents();
1729 secondWindow->consumeMotionUp();
1730}
1731
1732TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointerNoSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001733 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001734
1735 PointF touchPoint = {10, 10};
1736
1737 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001738 sp<FakeWindowHandle> firstWindow =
1739 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1740 sp<FakeWindowHandle> secondWindow =
1741 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001742
1743 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001744 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001745
1746 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001747 NotifyMotionArgs downMotionArgs =
1748 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1749 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001750 mDispatcher->notifyMotion(&downMotionArgs);
1751 // Only the first window should get the down event
1752 firstWindow->consumeMotionDown();
1753 secondWindow->assertNoEvents();
1754
1755 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001756 NotifyMotionArgs pointerDownMotionArgs =
1757 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1758 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1759 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1760 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001761 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1762 // Only the first window should get the pointer down event
1763 firstWindow->consumeMotionPointerDown(1);
1764 secondWindow->assertNoEvents();
1765
1766 // Transfer touch focus to the second window
1767 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1768 // The first window gets cancel and the second gets down and pointer down
1769 firstWindow->consumeMotionCancel();
1770 secondWindow->consumeMotionDown();
1771 secondWindow->consumeMotionPointerDown(1);
1772
1773 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001774 NotifyMotionArgs pointerUpMotionArgs =
1775 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1776 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1777 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1778 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001779 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1780 // The first window gets nothing and the second gets pointer up
1781 firstWindow->assertNoEvents();
1782 secondWindow->consumeMotionPointerUp(1);
1783
1784 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001785 NotifyMotionArgs upMotionArgs =
1786 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1787 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001788 mDispatcher->notifyMotion(&upMotionArgs);
1789 // The first window gets nothing and the second gets up
1790 firstWindow->assertNoEvents();
1791 secondWindow->consumeMotionUp();
1792}
1793
1794TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001795 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001796
1797 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001798 sp<FakeWindowHandle> firstWindow =
1799 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001800 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001801 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1802 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001803
1804 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001805 sp<FakeWindowHandle> secondWindow =
1806 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001807 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001808 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1809 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001810
1811 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001813
1814 PointF pointInFirst = {300, 200};
1815 PointF pointInSecond = {300, 600};
1816
1817 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001818 NotifyMotionArgs firstDownMotionArgs =
1819 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1820 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001821 mDispatcher->notifyMotion(&firstDownMotionArgs);
1822 // Only the first window should get the down event
1823 firstWindow->consumeMotionDown();
1824 secondWindow->assertNoEvents();
1825
1826 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001827 NotifyMotionArgs secondDownMotionArgs =
1828 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1829 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1830 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1831 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001832 mDispatcher->notifyMotion(&secondDownMotionArgs);
1833 // The first window gets a move and the second a down
1834 firstWindow->consumeMotionMove();
1835 secondWindow->consumeMotionDown();
1836
1837 // Transfer touch focus to the second window
1838 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1839 // The first window gets cancel and the new gets pointer down (it already saw down)
1840 firstWindow->consumeMotionCancel();
1841 secondWindow->consumeMotionPointerDown(1);
1842
1843 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001844 NotifyMotionArgs pointerUpMotionArgs =
1845 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1846 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1847 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1848 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001849 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1850 // The first window gets nothing and the second gets pointer up
1851 firstWindow->assertNoEvents();
1852 secondWindow->consumeMotionPointerUp(1);
1853
1854 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001855 NotifyMotionArgs upMotionArgs =
1856 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1857 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001858 mDispatcher->notifyMotion(&upMotionArgs);
1859 // The first window gets nothing and the second gets up
1860 firstWindow->assertNoEvents();
1861 secondWindow->consumeMotionUp();
1862}
1863
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001864TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001865 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001866 sp<FakeWindowHandle> window =
1867 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1868
Vishnu Nair47074b82020-08-14 11:54:47 -07001869 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001871 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001872
1873 window->consumeFocusEvent(true);
1874
1875 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1876 mDispatcher->notifyKey(&keyArgs);
1877
1878 // Window should receive key down event.
1879 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1880}
1881
1882TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001883 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001884 sp<FakeWindowHandle> window =
1885 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1886
Arthur Hung72d8dc32020-03-28 00:48:39 +00001887 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001888
1889 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1890 mDispatcher->notifyKey(&keyArgs);
1891 mDispatcher->waitForIdle();
1892
1893 window->assertNoEvents();
1894}
1895
1896// If a window is touchable, but does not have focus, it should receive motion events, but not keys
1897TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07001898 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001899 sp<FakeWindowHandle> window =
1900 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1901
Arthur Hung72d8dc32020-03-28 00:48:39 +00001902 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001903
1904 // Send key
1905 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1906 mDispatcher->notifyKey(&keyArgs);
1907 // Send motion
1908 NotifyMotionArgs motionArgs =
1909 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1910 ADISPLAY_ID_DEFAULT);
1911 mDispatcher->notifyMotion(&motionArgs);
1912
1913 // Window should receive only the motion event
1914 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1915 window->assertNoEvents(); // Key event or focus event will not be received
1916}
1917
arthurhungea3f4fc2020-12-21 23:18:53 +08001918TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
1919 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1920
1921 // Create first non touch modal window that supports split touch
1922 sp<FakeWindowHandle> firstWindow =
1923 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1924 firstWindow->setFrame(Rect(0, 0, 600, 400));
1925 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1926 InputWindowInfo::Flag::SPLIT_TOUCH);
1927
1928 // Create second non touch modal window that supports split touch
1929 sp<FakeWindowHandle> secondWindow =
1930 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1931 secondWindow->setFrame(Rect(0, 400, 600, 800));
1932 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1933 InputWindowInfo::Flag::SPLIT_TOUCH);
1934
1935 // Add the windows to the dispatcher
1936 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1937
1938 PointF pointInFirst = {300, 200};
1939 PointF pointInSecond = {300, 600};
1940
1941 // Send down to the first window
1942 NotifyMotionArgs firstDownMotionArgs =
1943 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1944 ADISPLAY_ID_DEFAULT, {pointInFirst});
1945 mDispatcher->notifyMotion(&firstDownMotionArgs);
1946 // Only the first window should get the down event
1947 firstWindow->consumeMotionDown();
1948 secondWindow->assertNoEvents();
1949
1950 // Send down to the second window
1951 NotifyMotionArgs secondDownMotionArgs =
1952 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1953 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1954 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1955 {pointInFirst, pointInSecond});
1956 mDispatcher->notifyMotion(&secondDownMotionArgs);
1957 // The first window gets a move and the second a down
1958 firstWindow->consumeMotionMove();
1959 secondWindow->consumeMotionDown();
1960
1961 // Send pointer cancel to the second window
1962 NotifyMotionArgs pointerUpMotionArgs =
1963 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1964 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1965 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1966 {pointInFirst, pointInSecond});
1967 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
1968 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1969 // The first window gets move and the second gets cancel.
1970 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
1971 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
1972
1973 // Send up event.
1974 NotifyMotionArgs upMotionArgs =
1975 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1976 ADISPLAY_ID_DEFAULT);
1977 mDispatcher->notifyMotion(&upMotionArgs);
1978 // The first window gets up and the second gets nothing.
1979 firstWindow->consumeMotionUp();
1980 secondWindow->assertNoEvents();
1981}
1982
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001983TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
1984 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1985
1986 sp<FakeWindowHandle> window =
1987 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1989 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
1990 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
1991 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
1992
1993 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
1994 window->assertNoEvents();
1995 mDispatcher->waitForIdle();
1996}
1997
chaviwd1c23182019-12-20 18:44:56 -08001998class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00001999public:
2000 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002001 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002002 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002003 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002004 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002005 }
2006
chaviwd1c23182019-12-20 18:44:56 -08002007 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2008
2009 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2010 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2011 expectedDisplayId, expectedFlags);
2012 }
2013
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002014 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2015
2016 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2017
chaviwd1c23182019-12-20 18:44:56 -08002018 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2019 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2020 expectedDisplayId, expectedFlags);
2021 }
2022
2023 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2024 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2025 expectedDisplayId, expectedFlags);
2026 }
2027
2028 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2029
2030private:
2031 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002032};
2033
2034// Tests for gesture monitors
2035TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002036 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002037 sp<FakeWindowHandle> window =
2038 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002040
chaviwd1c23182019-12-20 18:44:56 -08002041 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2042 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002043
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002045 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002046 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002047 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002048 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002049}
2050
2051TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002052 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002053 sp<FakeWindowHandle> window =
2054 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2055
2056 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002057 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002058
Arthur Hung72d8dc32020-03-28 00:48:39 +00002059 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002060 setFocusedWindow(window);
2061
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002062 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002063
chaviwd1c23182019-12-20 18:44:56 -08002064 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2065 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002066
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2068 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002069 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002070 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002071}
2072
2073TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002074 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002075 sp<FakeWindowHandle> window =
2076 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002077 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002078
chaviwd1c23182019-12-20 18:44:56 -08002079 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2080 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002081
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002082 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002083 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002084 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002085 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002086 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002087
2088 window->releaseChannel();
2089
chaviwd1c23182019-12-20 18:44:56 -08002090 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002091
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002093 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002095 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002096}
2097
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002098TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2099 FakeMonitorReceiver monitor =
2100 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2101 true /*isGestureMonitor*/);
2102
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002103 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002104 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2105 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2106 ASSERT_TRUE(consumeSeq);
2107
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002108 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002109 monitor.finishEvent(*consumeSeq);
2110 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002111 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002112}
2113
chaviw81e2bb92019-12-18 15:03:51 -08002114TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002115 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002116 sp<FakeWindowHandle> window =
2117 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2118
Arthur Hung72d8dc32020-03-28 00:48:39 +00002119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002120
2121 NotifyMotionArgs motionArgs =
2122 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2123 ADISPLAY_ID_DEFAULT);
2124
2125 mDispatcher->notifyMotion(&motionArgs);
2126 // Window should receive motion down event.
2127 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2128
2129 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002130 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002131 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2132 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2133 motionArgs.pointerCoords[0].getX() - 10);
2134
2135 mDispatcher->notifyMotion(&motionArgs);
2136 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2137 0 /*expectedFlags*/);
2138}
2139
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002140/**
2141 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2142 * the device default right away. In the test scenario, we check both the default value,
2143 * and the action of enabling / disabling.
2144 */
2145TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002146 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002147 sp<FakeWindowHandle> window =
2148 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2149
2150 // Set focused application.
2151 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002152 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002153
2154 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002155 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002156 setFocusedWindow(window);
2157
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002158 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2159
2160 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002161 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002162 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002163 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2164
2165 SCOPED_TRACE("Disable touch mode");
2166 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002167 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002169 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002170 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2171
2172 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002173 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002174 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002175 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2176
2177 SCOPED_TRACE("Enable touch mode again");
2178 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002179 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002181 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002182 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2183
2184 window->assertNoEvents();
2185}
2186
Gang Wange9087892020-01-07 12:17:14 -05002187TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002188 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002189 sp<FakeWindowHandle> window =
2190 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2191
2192 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002193 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002194
Arthur Hung72d8dc32020-03-28 00:48:39 +00002195 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002196 setFocusedWindow(window);
2197
Gang Wange9087892020-01-07 12:17:14 -05002198 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2199
2200 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2201 mDispatcher->notifyKey(&keyArgs);
2202
2203 InputEvent* event = window->consume();
2204 ASSERT_NE(event, nullptr);
2205
2206 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2207 ASSERT_NE(verified, nullptr);
2208 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2209
2210 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2211 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2212 ASSERT_EQ(keyArgs.source, verified->source);
2213 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2214
2215 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2216
2217 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2218 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002219 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2220 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2221 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2222 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2223 ASSERT_EQ(0, verifiedKey.repeatCount);
2224}
2225
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002226TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002227 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002228 sp<FakeWindowHandle> window =
2229 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2230
2231 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2232
Arthur Hung72d8dc32020-03-28 00:48:39 +00002233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002234
2235 NotifyMotionArgs motionArgs =
2236 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2237 ADISPLAY_ID_DEFAULT);
2238 mDispatcher->notifyMotion(&motionArgs);
2239
2240 InputEvent* event = window->consume();
2241 ASSERT_NE(event, nullptr);
2242
2243 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2244 ASSERT_NE(verified, nullptr);
2245 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2246
2247 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2248 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2249 EXPECT_EQ(motionArgs.source, verified->source);
2250 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2251
2252 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2253
2254 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2255 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2256 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2257 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2258 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2259 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2260 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2261}
2262
Prabir Pradhanbd527712021-03-09 19:17:09 -08002263TEST_F(InputDispatcherTest, NonPointerMotionEvent_NotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002264 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2265 sp<FakeWindowHandle> window =
2266 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2267 const std::string name = window->getName();
2268
2269 // Window gets transformed by offset values.
2270 window->setWindowOffset(500.0f, 500.0f);
2271
2272 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2273 window->setFocusable(true);
2274
2275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2276
2277 // First, we set focused window so that focusedWindowHandle is not null.
2278 setFocusedWindow(window);
2279
2280 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2281 window->consumeFocusEvent(true);
2282
Prabir Pradhanbd527712021-03-09 19:17:09 -08002283 constexpr const std::array nonPointerSources = {AINPUT_SOURCE_TRACKBALL,
2284 AINPUT_SOURCE_MOUSE_RELATIVE,
2285 AINPUT_SOURCE_JOYSTICK};
2286 for (const int source : nonPointerSources) {
2287 // Notify motion with a non-pointer source.
2288 NotifyMotionArgs motionArgs =
2289 generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, source, ADISPLAY_ID_DEFAULT);
2290 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09002291
Prabir Pradhanbd527712021-03-09 19:17:09 -08002292 InputEvent* event = window->consume();
2293 ASSERT_NE(event, nullptr);
2294 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2295 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2296 << " event, got " << inputEventTypeToString(event->getType()) << " event";
yunho.shinf4a80b82020-11-16 21:13:57 +09002297
Prabir Pradhanbd527712021-03-09 19:17:09 -08002298 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2299 EXPECT_EQ(AMOTION_EVENT_ACTION_MOVE, motionEvent.getAction());
2300 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09002301
Prabir Pradhanbd527712021-03-09 19:17:09 -08002302 float expectedX = motionArgs.pointerCoords[0].getX();
2303 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09002304
Prabir Pradhanbd527712021-03-09 19:17:09 -08002305 // Ensure the axis values from the final motion event are not transformed.
2306 EXPECT_EQ(expectedX, motionEvent.getX(0))
2307 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2308 << motionEvent.getX(0);
2309 EXPECT_EQ(expectedY, motionEvent.getY(0))
2310 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2311 << motionEvent.getY(0);
2312 // Ensure the raw and transformed axis values for the motion event are the same.
2313 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2314 << "expected raw and transformed X-axis values to be equal";
2315 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2316 << "expected raw and transformed Y-axis values to be equal";
2317 }
yunho.shinf4a80b82020-11-16 21:13:57 +09002318}
2319
chaviw09c8d2d2020-08-24 15:48:26 -07002320/**
2321 * Ensure that separate calls to sign the same data are generating the same key.
2322 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2323 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2324 * tests.
2325 */
2326TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2327 KeyEvent event = getTestKeyEvent();
2328 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2329
2330 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2331 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2332 ASSERT_EQ(hmac1, hmac2);
2333}
2334
2335/**
2336 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2337 */
2338TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2339 KeyEvent event = getTestKeyEvent();
2340 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2341 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2342
2343 verifiedEvent.deviceId += 1;
2344 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2345
2346 verifiedEvent.source += 1;
2347 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2348
2349 verifiedEvent.eventTimeNanos += 1;
2350 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2351
2352 verifiedEvent.displayId += 1;
2353 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2354
2355 verifiedEvent.action += 1;
2356 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2357
2358 verifiedEvent.downTimeNanos += 1;
2359 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2360
2361 verifiedEvent.flags += 1;
2362 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2363
2364 verifiedEvent.keyCode += 1;
2365 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2366
2367 verifiedEvent.scanCode += 1;
2368 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2369
2370 verifiedEvent.metaState += 1;
2371 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2372
2373 verifiedEvent.repeatCount += 1;
2374 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2375}
2376
Vishnu Nair958da932020-08-21 17:12:37 -07002377TEST_F(InputDispatcherTest, SetFocusedWindow) {
2378 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2379 sp<FakeWindowHandle> windowTop =
2380 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2381 sp<FakeWindowHandle> windowSecond =
2382 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2383 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2384
2385 // Top window is also focusable but is not granted focus.
2386 windowTop->setFocusable(true);
2387 windowSecond->setFocusable(true);
2388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2389 setFocusedWindow(windowSecond);
2390
2391 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2393 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002394
2395 // Focused window should receive event.
2396 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2397 windowTop->assertNoEvents();
2398}
2399
2400TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2401 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2402 sp<FakeWindowHandle> window =
2403 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2404 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2405
2406 window->setFocusable(true);
2407 // Release channel for window is no longer valid.
2408 window->releaseChannel();
2409 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2410 setFocusedWindow(window);
2411
2412 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002413 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2414 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002415
2416 // window channel is invalid, so it should not receive any input event.
2417 window->assertNoEvents();
2418}
2419
2420TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2421 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2422 sp<FakeWindowHandle> window =
2423 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2424 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2425
2426 // Window is not focusable.
2427 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2428 setFocusedWindow(window);
2429
2430 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002431 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2432 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002433
2434 // window is invalid, so it should not receive any input event.
2435 window->assertNoEvents();
2436}
2437
2438TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2439 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2440 sp<FakeWindowHandle> windowTop =
2441 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2442 sp<FakeWindowHandle> windowSecond =
2443 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2444 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2445
2446 windowTop->setFocusable(true);
2447 windowSecond->setFocusable(true);
2448 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2449 setFocusedWindow(windowTop);
2450 windowTop->consumeFocusEvent(true);
2451
2452 setFocusedWindow(windowSecond, windowTop);
2453 windowSecond->consumeFocusEvent(true);
2454 windowTop->consumeFocusEvent(false);
2455
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2457 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002458
2459 // Focused window should receive event.
2460 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2461}
2462
2463TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2464 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2465 sp<FakeWindowHandle> windowTop =
2466 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2467 sp<FakeWindowHandle> windowSecond =
2468 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2469 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2470
2471 windowTop->setFocusable(true);
2472 windowSecond->setFocusable(true);
2473 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2474 setFocusedWindow(windowSecond, windowTop);
2475
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002476 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2477 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002478
2479 // Event should be dropped.
2480 windowTop->assertNoEvents();
2481 windowSecond->assertNoEvents();
2482}
2483
2484TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2485 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2486 sp<FakeWindowHandle> window =
2487 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2488 sp<FakeWindowHandle> previousFocusedWindow =
2489 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2490 ADISPLAY_ID_DEFAULT);
2491 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2492
2493 window->setFocusable(true);
2494 previousFocusedWindow->setFocusable(true);
2495 window->setVisible(false);
2496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2497 setFocusedWindow(previousFocusedWindow);
2498 previousFocusedWindow->consumeFocusEvent(true);
2499
2500 // Requesting focus on invisible window takes focus from currently focused window.
2501 setFocusedWindow(window);
2502 previousFocusedWindow->consumeFocusEvent(false);
2503
2504 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002506 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002507 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002508
2509 // Window does not get focus event or key down.
2510 window->assertNoEvents();
2511
2512 // Window becomes visible.
2513 window->setVisible(true);
2514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2515
2516 // Window receives focus event.
2517 window->consumeFocusEvent(true);
2518 // Focused window receives key down.
2519 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2520}
2521
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002522/**
2523 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2524 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2525 * of the 'slipperyEnterWindow'.
2526 *
2527 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2528 * a way so that the touched location is no longer covered by the top window.
2529 *
2530 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2531 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2532 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2533 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2534 * with ACTION_DOWN).
2535 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2536 * window moved itself away from the touched location and had Flag::SLIPPERY.
2537 *
2538 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2539 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2540 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2541 *
2542 * In this test, we ensure that the event received by the bottom window has
2543 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2544 */
2545TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2546 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2547 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2548
2549 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2550 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2551
2552 sp<FakeWindowHandle> slipperyExitWindow =
2553 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2554 slipperyExitWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2555 InputWindowInfo::Flag::SLIPPERY);
2556 // Make sure this one overlaps the bottom window
2557 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2558 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2559 // one. Windows with the same owner are not considered to be occluding each other.
2560 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2561
2562 sp<FakeWindowHandle> slipperyEnterWindow =
2563 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2564 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2565
2566 mDispatcher->setInputWindows(
2567 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2568
2569 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2570 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2571 ADISPLAY_ID_DEFAULT, {{50, 50}});
2572 mDispatcher->notifyMotion(&args);
2573 slipperyExitWindow->consumeMotionDown();
2574 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2575 mDispatcher->setInputWindows(
2576 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2577
2578 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2579 ADISPLAY_ID_DEFAULT, {{51, 51}});
2580 mDispatcher->notifyMotion(&args);
2581
2582 slipperyExitWindow->consumeMotionCancel();
2583
2584 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2585 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2586}
2587
Garfield Tan1c7bc862020-01-28 13:24:04 -08002588class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2589protected:
2590 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2591 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2592
Chris Yea209fde2020-07-22 13:54:51 -07002593 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002594 sp<FakeWindowHandle> mWindow;
2595
2596 virtual void SetUp() override {
2597 mFakePolicy = new FakeInputDispatcherPolicy();
2598 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2599 mDispatcher = new InputDispatcher(mFakePolicy);
2600 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2601 ASSERT_EQ(OK, mDispatcher->start());
2602
2603 setUpWindow();
2604 }
2605
2606 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002607 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002608 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2609
Vishnu Nair47074b82020-08-14 11:54:47 -07002610 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002612 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002613 mWindow->consumeFocusEvent(true);
2614 }
2615
Chris Ye2ad95392020-09-01 13:44:44 -07002616 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002617 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002618 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002619 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2620 mDispatcher->notifyKey(&keyArgs);
2621
2622 // Window should receive key down event.
2623 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2624 }
2625
2626 void expectKeyRepeatOnce(int32_t repeatCount) {
2627 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2628 InputEvent* repeatEvent = mWindow->consume();
2629 ASSERT_NE(nullptr, repeatEvent);
2630
2631 uint32_t eventType = repeatEvent->getType();
2632 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2633
2634 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2635 uint32_t eventAction = repeatKeyEvent->getAction();
2636 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2637 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2638 }
2639
Chris Ye2ad95392020-09-01 13:44:44 -07002640 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002641 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002642 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002643 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2644 mDispatcher->notifyKey(&keyArgs);
2645
2646 // Window should receive key down event.
2647 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2648 0 /*expectedFlags*/);
2649 }
2650};
2651
2652TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002653 sendAndConsumeKeyDown(1 /* deviceId */);
2654 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2655 expectKeyRepeatOnce(repeatCount);
2656 }
2657}
2658
2659TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2660 sendAndConsumeKeyDown(1 /* deviceId */);
2661 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2662 expectKeyRepeatOnce(repeatCount);
2663 }
2664 sendAndConsumeKeyDown(2 /* deviceId */);
2665 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002666 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2667 expectKeyRepeatOnce(repeatCount);
2668 }
2669}
2670
2671TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002672 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002673 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002674 sendAndConsumeKeyUp(1 /* deviceId */);
2675 mWindow->assertNoEvents();
2676}
2677
2678TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2679 sendAndConsumeKeyDown(1 /* deviceId */);
2680 expectKeyRepeatOnce(1 /*repeatCount*/);
2681 sendAndConsumeKeyDown(2 /* deviceId */);
2682 expectKeyRepeatOnce(1 /*repeatCount*/);
2683 // Stale key up from device 1.
2684 sendAndConsumeKeyUp(1 /* deviceId */);
2685 // Device 2 is still down, keep repeating
2686 expectKeyRepeatOnce(2 /*repeatCount*/);
2687 expectKeyRepeatOnce(3 /*repeatCount*/);
2688 // Device 2 key up
2689 sendAndConsumeKeyUp(2 /* deviceId */);
2690 mWindow->assertNoEvents();
2691}
2692
2693TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2694 sendAndConsumeKeyDown(1 /* deviceId */);
2695 expectKeyRepeatOnce(1 /*repeatCount*/);
2696 sendAndConsumeKeyDown(2 /* deviceId */);
2697 expectKeyRepeatOnce(1 /*repeatCount*/);
2698 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2699 sendAndConsumeKeyUp(2 /* deviceId */);
2700 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002701 mWindow->assertNoEvents();
2702}
2703
2704TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002705 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002706 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2707 InputEvent* repeatEvent = mWindow->consume();
2708 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2709 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2710 IdGenerator::getSource(repeatEvent->getId()));
2711 }
2712}
2713
2714TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002715 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002716
2717 std::unordered_set<int32_t> idSet;
2718 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2719 InputEvent* repeatEvent = mWindow->consume();
2720 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2721 int32_t id = repeatEvent->getId();
2722 EXPECT_EQ(idSet.end(), idSet.find(id));
2723 idSet.insert(id);
2724 }
2725}
2726
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002727/* Test InputDispatcher for MultiDisplay */
2728class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2729public:
2730 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002731 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002732 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002733
Chris Yea209fde2020-07-22 13:54:51 -07002734 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002735 windowInPrimary =
2736 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002737
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002738 // Set focus window for primary display, but focused display would be second one.
2739 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002740 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002742 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002743 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002744
Chris Yea209fde2020-07-22 13:54:51 -07002745 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002746 windowInSecondary =
2747 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002748 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002749 // Set focus display to second one.
2750 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2751 // Set focus window for second display.
2752 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002753 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002754 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002755 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002756 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002757 }
2758
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002759 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002760 InputDispatcherTest::TearDown();
2761
Chris Yea209fde2020-07-22 13:54:51 -07002762 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002763 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002764 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002765 windowInSecondary.clear();
2766 }
2767
2768protected:
Chris Yea209fde2020-07-22 13:54:51 -07002769 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002770 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002771 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002772 sp<FakeWindowHandle> windowInSecondary;
2773};
2774
2775TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2776 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002777 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2778 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2779 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002780 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002781 windowInSecondary->assertNoEvents();
2782
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002783 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2785 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2786 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002787 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002788 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002789}
2790
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002791TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002792 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2794 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002795 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002796 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002797 windowInSecondary->assertNoEvents();
2798
2799 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002800 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002801 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002802 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002803 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002804
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002805 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002806 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002807
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002808 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002809 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2810 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002811
2812 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002813 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002814 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08002815 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002816 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002817 windowInSecondary->assertNoEvents();
2818}
2819
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002820// Test per-display input monitors for motion event.
2821TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002822 FakeMonitorReceiver monitorInPrimary =
2823 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2824 FakeMonitorReceiver monitorInSecondary =
2825 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002826
2827 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002828 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2829 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2830 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002831 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002832 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002833 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002834 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002835
2836 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2838 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2839 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002840 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002841 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002842 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08002843 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002844
2845 // Test inject a non-pointer motion event.
2846 // If specific a display, it will dispatch to the focused window of particular display,
2847 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2849 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
2850 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002851 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002852 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002853 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002854 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002855}
2856
2857// Test per-display input monitors for key event.
2858TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002859 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08002860 FakeMonitorReceiver monitorInPrimary =
2861 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2862 FakeMonitorReceiver monitorInSecondary =
2863 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002864
2865 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2867 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002868 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002869 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002870 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002871 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002872}
2873
Vishnu Nair958da932020-08-21 17:12:37 -07002874TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
2875 sp<FakeWindowHandle> secondWindowInPrimary =
2876 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2877 secondWindowInPrimary->setFocusable(true);
2878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
2879 setFocusedWindow(secondWindowInPrimary);
2880 windowInPrimary->consumeFocusEvent(false);
2881 secondWindowInPrimary->consumeFocusEvent(true);
2882
2883 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002884 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2885 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002886 windowInPrimary->assertNoEvents();
2887 windowInSecondary->assertNoEvents();
2888 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2889}
2890
Jackal Guof9696682018-10-05 12:23:23 +08002891class InputFilterTest : public InputDispatcherTest {
2892protected:
2893 static constexpr int32_t SECOND_DISPLAY_ID = 1;
2894
2895 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
2896 NotifyMotionArgs motionArgs;
2897
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002898 motionArgs =
2899 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08002900 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002901 motionArgs =
2902 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08002903 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002904 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002905 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002906 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002907 } else {
2908 mFakePolicy->assertFilterInputEventWasNotCalled();
2909 }
2910 }
2911
2912 void testNotifyKey(bool expectToBeFiltered) {
2913 NotifyKeyArgs keyArgs;
2914
2915 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2916 mDispatcher->notifyKey(&keyArgs);
2917 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
2918 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002919 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002920
2921 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002922 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002923 } else {
2924 mFakePolicy->assertFilterInputEventWasNotCalled();
2925 }
2926 }
2927};
2928
2929// Test InputFilter for MotionEvent
2930TEST_F(InputFilterTest, MotionEvent_InputFilter) {
2931 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
2932 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2933 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2934
2935 // Enable InputFilter
2936 mDispatcher->setInputFilterEnabled(true);
2937 // Test touch on both primary and second display, and check if both events are filtered.
2938 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
2939 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
2940
2941 // Disable InputFilter
2942 mDispatcher->setInputFilterEnabled(false);
2943 // Test touch on both primary and second display, and check if both events aren't filtered.
2944 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2945 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2946}
2947
2948// Test InputFilter for KeyEvent
2949TEST_F(InputFilterTest, KeyEvent_InputFilter) {
2950 // Since the InputFilter is disabled by default, check if key event aren't filtered.
2951 testNotifyKey(/*expectToBeFiltered*/ false);
2952
2953 // Enable InputFilter
2954 mDispatcher->setInputFilterEnabled(true);
2955 // Send a key event, and check if it is filtered.
2956 testNotifyKey(/*expectToBeFiltered*/ true);
2957
2958 // Disable InputFilter
2959 mDispatcher->setInputFilterEnabled(false);
2960 // Send a key event, and check if it isn't filtered.
2961 testNotifyKey(/*expectToBeFiltered*/ false);
2962}
2963
chaviwfd6d3512019-03-25 13:23:49 -07002964class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002965 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07002966 InputDispatcherTest::SetUp();
2967
Chris Yea209fde2020-07-22 13:54:51 -07002968 std::shared_ptr<FakeApplicationHandle> application =
2969 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002970 mUnfocusedWindow =
2971 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002972 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
2973 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2974 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002975 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002976
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002977 mFocusedWindow =
2978 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2979 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01002980 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002981
2982 // Set focused application.
2983 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002984 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07002985
2986 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002988 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002989 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07002990 }
2991
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002992 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07002993 InputDispatcherTest::TearDown();
2994
2995 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002996 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07002997 }
2998
2999protected:
3000 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003001 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003002 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003003};
3004
3005// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3006// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3007// the onPointerDownOutsideFocus callback.
3008TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003010 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3011 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003012 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003013 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003014
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003015 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003016 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3017}
3018
3019// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3020// DOWN on the window that doesn't have focus. Ensure no window received the
3021// onPointerDownOutsideFocus callback.
3022TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003024 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003025 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003026 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003027
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003028 ASSERT_TRUE(mDispatcher->waitForIdle());
3029 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003030}
3031
3032// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3033// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3034TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3036 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003037 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003038 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003039
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003040 ASSERT_TRUE(mDispatcher->waitForIdle());
3041 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003042}
3043
3044// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3045// DOWN on the window that already has focus. Ensure no window received the
3046// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003047TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003049 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003050 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003051 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003052 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003053
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003054 ASSERT_TRUE(mDispatcher->waitForIdle());
3055 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003056}
3057
chaviwaf87b3e2019-10-01 16:59:28 -07003058// These tests ensures we can send touch events to a single client when there are multiple input
3059// windows that point to the same client token.
3060class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3061 virtual void SetUp() override {
3062 InputDispatcherTest::SetUp();
3063
Chris Yea209fde2020-07-22 13:54:51 -07003064 std::shared_ptr<FakeApplicationHandle> application =
3065 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003066 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3067 ADISPLAY_ID_DEFAULT);
3068 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3069 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
Michael Wright44753b12020-07-08 13:48:11 +01003070 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3071 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003072 mWindow1->setFrame(Rect(0, 0, 100, 100));
3073
3074 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3075 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01003076 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3077 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003078 mWindow2->setFrame(Rect(100, 100, 200, 200));
3079
Arthur Hung72d8dc32020-03-28 00:48:39 +00003080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003081 }
3082
3083protected:
3084 sp<FakeWindowHandle> mWindow1;
3085 sp<FakeWindowHandle> mWindow2;
3086
3087 // Helper function to convert the point from screen coordinates into the window's space
3088 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003089 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3090 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003091 }
3092
3093 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3094 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003095 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003096 InputEvent* event = window->consume();
3097
3098 ASSERT_NE(nullptr, event) << name.c_str()
3099 << ": consumer should have returned non-NULL event.";
3100
3101 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3102 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3103 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3104
3105 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3106 EXPECT_EQ(expectedAction, motionEvent.getAction());
3107
3108 for (size_t i = 0; i < points.size(); i++) {
3109 float expectedX = points[i].x;
3110 float expectedY = points[i].y;
3111
3112 EXPECT_EQ(expectedX, motionEvent.getX(i))
3113 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3114 << ", got " << motionEvent.getX(i);
3115 EXPECT_EQ(expectedY, motionEvent.getY(i))
3116 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3117 << ", got " << motionEvent.getY(i);
3118 }
3119 }
chaviw9eaa22c2020-07-01 16:21:27 -07003120
3121 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3122 std::vector<PointF> expectedPoints) {
3123 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3124 ADISPLAY_ID_DEFAULT, touchedPoints);
3125 mDispatcher->notifyMotion(&motionArgs);
3126
3127 // Always consume from window1 since it's the window that has the InputReceiver
3128 consumeMotionEvent(mWindow1, action, expectedPoints);
3129 }
chaviwaf87b3e2019-10-01 16:59:28 -07003130};
3131
3132TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3133 // Touch Window 1
3134 PointF touchedPoint = {10, 10};
3135 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003136 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003137
3138 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003139 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003140
3141 // Touch Window 2
3142 touchedPoint = {150, 150};
3143 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003144 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003145}
3146
chaviw9eaa22c2020-07-01 16:21:27 -07003147TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3148 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003149 mWindow2->setWindowScale(0.5f, 0.5f);
3150
3151 // Touch Window 1
3152 PointF touchedPoint = {10, 10};
3153 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003154 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003155 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003156 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003157
3158 // Touch Window 2
3159 touchedPoint = {150, 150};
3160 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003161 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3162 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003163
chaviw9eaa22c2020-07-01 16:21:27 -07003164 // Update the transform so rotation is set
3165 mWindow2->setWindowTransform(0, -1, 1, 0);
3166 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3167 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003168}
3169
chaviw9eaa22c2020-07-01 16:21:27 -07003170TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003171 mWindow2->setWindowScale(0.5f, 0.5f);
3172
3173 // Touch Window 1
3174 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3175 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003176 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003177
3178 // Touch Window 2
3179 int32_t actionPointerDown =
3180 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003181 touchedPoints.push_back(PointF{150, 150});
3182 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3183 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003184
chaviw9eaa22c2020-07-01 16:21:27 -07003185 // Release Window 2
3186 int32_t actionPointerUp =
3187 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3188 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3189 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003190
chaviw9eaa22c2020-07-01 16:21:27 -07003191 // Update the transform so rotation is set for Window 2
3192 mWindow2->setWindowTransform(0, -1, 1, 0);
3193 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3194 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003195}
3196
chaviw9eaa22c2020-07-01 16:21:27 -07003197TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003198 mWindow2->setWindowScale(0.5f, 0.5f);
3199
3200 // Touch Window 1
3201 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3202 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003203 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003204
3205 // Touch Window 2
3206 int32_t actionPointerDown =
3207 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003208 touchedPoints.push_back(PointF{150, 150});
3209 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003210
chaviw9eaa22c2020-07-01 16:21:27 -07003211 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003212
3213 // Move both windows
3214 touchedPoints = {{20, 20}, {175, 175}};
3215 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3216 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3217
chaviw9eaa22c2020-07-01 16:21:27 -07003218 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003219
chaviw9eaa22c2020-07-01 16:21:27 -07003220 // Release Window 2
3221 int32_t actionPointerUp =
3222 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3223 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3224 expectedPoints.pop_back();
3225
3226 // Touch Window 2
3227 mWindow2->setWindowTransform(0, -1, 1, 0);
3228 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3229 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3230
3231 // Move both windows
3232 touchedPoints = {{20, 20}, {175, 175}};
3233 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3234 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3235
3236 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003237}
3238
3239TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3240 mWindow1->setWindowScale(0.5f, 0.5f);
3241
3242 // Touch Window 1
3243 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3244 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003245 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003246
3247 // Touch Window 2
3248 int32_t actionPointerDown =
3249 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003250 touchedPoints.push_back(PointF{150, 150});
3251 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003252
chaviw9eaa22c2020-07-01 16:21:27 -07003253 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003254
3255 // Move both windows
3256 touchedPoints = {{20, 20}, {175, 175}};
3257 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3258 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3259
chaviw9eaa22c2020-07-01 16:21:27 -07003260 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003261}
3262
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003263class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3264 virtual void SetUp() override {
3265 InputDispatcherTest::SetUp();
3266
Chris Yea209fde2020-07-22 13:54:51 -07003267 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003268 mApplication->setDispatchingTimeout(20ms);
3269 mWindow =
3270 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3271 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003272 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003273 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003274 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3275 // window.
Michael Wright44753b12020-07-08 13:48:11 +01003276 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003277
3278 // Set focused application.
3279 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3280
3281 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003282 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003283 mWindow->consumeFocusEvent(true);
3284 }
3285
3286 virtual void TearDown() override {
3287 InputDispatcherTest::TearDown();
3288 mWindow.clear();
3289 }
3290
3291protected:
Chris Yea209fde2020-07-22 13:54:51 -07003292 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003293 sp<FakeWindowHandle> mWindow;
3294 static constexpr PointF WINDOW_LOCATION = {20, 20};
3295
3296 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003298 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3299 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003300 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003301 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3302 WINDOW_LOCATION));
3303 }
3304};
3305
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003306// Send a tap and respond, which should not cause an ANR.
3307TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3308 tapOnWindow();
3309 mWindow->consumeMotionDown();
3310 mWindow->consumeMotionUp();
3311 ASSERT_TRUE(mDispatcher->waitForIdle());
3312 mFakePolicy->assertNotifyAnrWasNotCalled();
3313}
3314
3315// Send a regular key and respond, which should not cause an ANR.
3316TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003318 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3319 ASSERT_TRUE(mDispatcher->waitForIdle());
3320 mFakePolicy->assertNotifyAnrWasNotCalled();
3321}
3322
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003323TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3324 mWindow->setFocusable(false);
3325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3326 mWindow->consumeFocusEvent(false);
3327
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003328 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003329 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003330 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3331 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003332 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003333 // Key will not go to window because we have no focused window.
3334 // The 'no focused window' ANR timer should start instead.
3335
3336 // Now, the focused application goes away.
3337 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3338 // The key should get dropped and there should be no ANR.
3339
3340 ASSERT_TRUE(mDispatcher->waitForIdle());
3341 mFakePolicy->assertNotifyAnrWasNotCalled();
3342}
3343
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003344// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003345// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3346// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003347TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003348 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003349 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3350 WINDOW_LOCATION));
3351
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003352 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3353 ASSERT_TRUE(sequenceNum);
3354 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003355 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003356
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003357 mWindow->finishEvent(*sequenceNum);
3358 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3359 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003360 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003361 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003362}
3363
3364// Send a key to the app and have the app not respond right away.
3365TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3366 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003368 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3369 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003370 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003371 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003372 ASSERT_TRUE(mDispatcher->waitForIdle());
3373}
3374
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003375// We have a focused application, but no focused window
3376TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003377 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003378 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3379 mWindow->consumeFocusEvent(false);
3380
3381 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003382 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003383 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3384 WINDOW_LOCATION));
3385 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3386 mDispatcher->waitForIdle();
3387 mFakePolicy->assertNotifyAnrWasNotCalled();
3388
3389 // Once a focused event arrives, we get an ANR for this application
3390 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3391 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003392 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003393 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003394 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003395 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003396 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003397 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003398 ASSERT_TRUE(mDispatcher->waitForIdle());
3399}
3400
3401// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003402// Make sure that we don't notify policy twice about the same ANR.
3403TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003404 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3406 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003407
3408 // Once a focused event arrives, we get an ANR for this application
3409 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3410 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003411 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003412 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003413 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003414 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003415 const std::chrono::duration appTimeout =
3416 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003417 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003418
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003419 std::this_thread::sleep_for(appTimeout);
3420 // ANR should not be raised again. It is up to policy to do that if it desires.
3421 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003422
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003423 // If we now get a focused window, the ANR should stop, but the policy handles that via
3424 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003425 ASSERT_TRUE(mDispatcher->waitForIdle());
3426}
3427
3428// We have a focused application, but no focused window
3429TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003430 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3432 mWindow->consumeFocusEvent(false);
3433
3434 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003435 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003436 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003437 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3438 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003439
3440 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003441 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003442
3443 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003444 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003445 ASSERT_TRUE(mDispatcher->waitForIdle());
3446 mWindow->assertNoEvents();
3447}
3448
3449/**
3450 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3451 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3452 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3453 * the ANR mechanism should still work.
3454 *
3455 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3456 * DOWN event, while not responding on the second one.
3457 */
3458TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3459 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3460 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3461 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3462 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3463 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003464 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003465
3466 // Now send ACTION_UP, with identical timestamp
3467 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3468 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3469 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3470 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003471 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003472
3473 // We have now sent down and up. Let's consume first event and then ANR on the second.
3474 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3475 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003476 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003477}
3478
3479// If an app is not responding to a key event, gesture monitors should continue to receive
3480// new motion events
3481TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3482 FakeMonitorReceiver monitor =
3483 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3484 true /*isGestureMonitor*/);
3485
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3487 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003488 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003489 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003490
3491 // Stuck on the ACTION_UP
3492 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003493 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003494
3495 // New tap will go to the gesture monitor, but not to the window
3496 tapOnWindow();
3497 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3498 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3499
3500 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3501 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003502 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003503 mWindow->assertNoEvents();
3504 monitor.assertNoEvents();
3505}
3506
3507// If an app is not responding to a motion event, gesture monitors should continue to receive
3508// new motion events
3509TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3510 FakeMonitorReceiver monitor =
3511 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3512 true /*isGestureMonitor*/);
3513
3514 tapOnWindow();
3515 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3516 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3517
3518 mWindow->consumeMotionDown();
3519 // Stuck on the ACTION_UP
3520 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003521 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003522
3523 // New tap will go to the gesture monitor, but not to the window
3524 tapOnWindow();
3525 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3526 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3527
3528 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3529 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003530 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003531 mWindow->assertNoEvents();
3532 monitor.assertNoEvents();
3533}
3534
3535// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3536// process events, you don't get an anr. When the window later becomes unresponsive again, you
3537// get an ANR again.
3538// 1. tap -> block on ACTION_UP -> receive ANR
3539// 2. consume all pending events (= queue becomes healthy again)
3540// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3541TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3542 tapOnWindow();
3543
3544 mWindow->consumeMotionDown();
3545 // Block on ACTION_UP
3546 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003547 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003548 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3549 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003550 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003551 mWindow->assertNoEvents();
3552
3553 tapOnWindow();
3554 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003555 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003556 mWindow->consumeMotionUp();
3557
3558 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003559 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003560 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003561 mWindow->assertNoEvents();
3562}
3563
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003564// If a connection remains unresponsive for a while, make sure policy is only notified once about
3565// it.
3566TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003568 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3569 WINDOW_LOCATION));
3570
3571 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003572 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003573 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003574 // 'notifyConnectionUnresponsive' should only be called once per connection
3575 mFakePolicy->assertNotifyAnrWasNotCalled();
3576 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003577 mWindow->consumeMotionDown();
3578 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3579 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3580 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003581 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003582 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003583 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003584}
3585
3586/**
3587 * If a window is processing a motion event, and then a key event comes in, the key event should
3588 * not to to the focused window until the motion is processed.
3589 *
3590 * Warning!!!
3591 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3592 * and the injection timeout that we specify when injecting the key.
3593 * We must have the injection timeout (10ms) be smaller than
3594 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3595 *
3596 * If that value changes, this test should also change.
3597 */
3598TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3599 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3601
3602 tapOnWindow();
3603 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3604 ASSERT_TRUE(downSequenceNum);
3605 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3606 ASSERT_TRUE(upSequenceNum);
3607 // Don't finish the events yet, and send a key
3608 // Injection will "succeed" because we will eventually give up and send the key to the focused
3609 // window even if motions are still being processed. But because the injection timeout is short,
3610 // we will receive INJECTION_TIMED_OUT as the result.
3611
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003612 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003613 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003614 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3615 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003616 // Key will not be sent to the window, yet, because the window is still processing events
3617 // and the key remains pending, waiting for the touch events to be processed
3618 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3619 ASSERT_FALSE(keySequenceNum);
3620
3621 std::this_thread::sleep_for(500ms);
3622 // if we wait long enough though, dispatcher will give up, and still send the key
3623 // to the focused window, even though we have not yet finished the motion event
3624 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3625 mWindow->finishEvent(*downSequenceNum);
3626 mWindow->finishEvent(*upSequenceNum);
3627}
3628
3629/**
3630 * If a window is processing a motion event, and then a key event comes in, the key event should
3631 * not go to the focused window until the motion is processed.
3632 * If then a new motion comes in, then the pending key event should be going to the currently
3633 * focused window right away.
3634 */
3635TEST_F(InputDispatcherSingleWindowAnr,
3636 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3637 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3639
3640 tapOnWindow();
3641 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3642 ASSERT_TRUE(downSequenceNum);
3643 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3644 ASSERT_TRUE(upSequenceNum);
3645 // Don't finish the events yet, and send a key
3646 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003647 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003648 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003649 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003650 // At this point, key is still pending, and should not be sent to the application yet.
3651 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3652 ASSERT_FALSE(keySequenceNum);
3653
3654 // Now tap down again. It should cause the pending key to go to the focused window right away.
3655 tapOnWindow();
3656 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3657 // the other events yet. We can finish events in any order.
3658 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3659 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3660 mWindow->consumeMotionDown();
3661 mWindow->consumeMotionUp();
3662 mWindow->assertNoEvents();
3663}
3664
3665class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3666 virtual void SetUp() override {
3667 InputDispatcherTest::SetUp();
3668
Chris Yea209fde2020-07-22 13:54:51 -07003669 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003670 mApplication->setDispatchingTimeout(10ms);
3671 mUnfocusedWindow =
3672 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3673 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3674 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3675 // window.
3676 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003677 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3678 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3679 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003680
3681 mFocusedWindow =
3682 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003683 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003684 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003685 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3686 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003687
3688 // Set focused application.
3689 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003690 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003691
3692 // Expect one focus window exist in display.
3693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003694 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003695 mFocusedWindow->consumeFocusEvent(true);
3696 }
3697
3698 virtual void TearDown() override {
3699 InputDispatcherTest::TearDown();
3700
3701 mUnfocusedWindow.clear();
3702 mFocusedWindow.clear();
3703 }
3704
3705protected:
Chris Yea209fde2020-07-22 13:54:51 -07003706 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003707 sp<FakeWindowHandle> mUnfocusedWindow;
3708 sp<FakeWindowHandle> mFocusedWindow;
3709 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3710 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3711 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3712
3713 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3714
3715 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3716
3717private:
3718 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003720 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3721 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003723 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3724 location));
3725 }
3726};
3727
3728// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3729// should be ANR'd first.
3730TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003732 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3733 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003734 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003735 mFocusedWindow->consumeMotionDown();
3736 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3737 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3738 // We consumed all events, so no ANR
3739 ASSERT_TRUE(mDispatcher->waitForIdle());
3740 mFakePolicy->assertNotifyAnrWasNotCalled();
3741
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003742 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003743 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3744 FOCUSED_WINDOW_LOCATION));
3745 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
3746 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003747
3748 const std::chrono::duration timeout =
3749 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003750 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003751 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
3752 // sequence to make it consistent
3753 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003754 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003755 mFocusedWindow->consumeMotionDown();
3756 // This cancel is generated because the connection was unresponsive
3757 mFocusedWindow->consumeMotionCancel();
3758 mFocusedWindow->assertNoEvents();
3759 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003760 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003761 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003762 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003763}
3764
3765// If we have 2 windows with identical timeouts that are both unresponsive,
3766// it doesn't matter which order they should have ANR.
3767// But we should receive ANR for both.
3768TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
3769 // Set the timeout for unfocused window to match the focused window
3770 mUnfocusedWindow->setDispatchingTimeout(10ms);
3771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3772
3773 tapOnFocusedWindow();
3774 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003775 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
3776 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003777
3778 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003779 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
3780 mFocusedWindow->getToken() == anrConnectionToken2);
3781 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
3782 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003783
3784 ASSERT_TRUE(mDispatcher->waitForIdle());
3785 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003786
3787 mFocusedWindow->consumeMotionDown();
3788 mFocusedWindow->consumeMotionUp();
3789 mUnfocusedWindow->consumeMotionOutside();
3790
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003791 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
3792 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003793
3794 // Both applications should be marked as responsive, in any order
3795 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
3796 mFocusedWindow->getToken() == responsiveToken2);
3797 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
3798 mUnfocusedWindow->getToken() == responsiveToken2);
3799 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003800}
3801
3802// If a window is already not responding, the second tap on the same window should be ignored.
3803// We should also log an error to account for the dropped event (not tested here).
3804// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
3805TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
3806 tapOnFocusedWindow();
3807 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3808 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3809 // Receive the events, but don't respond
3810 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
3811 ASSERT_TRUE(downEventSequenceNum);
3812 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
3813 ASSERT_TRUE(upEventSequenceNum);
3814 const std::chrono::duration timeout =
3815 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003816 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003817
3818 // Tap once again
3819 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003820 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003821 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3822 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003823 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003824 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3825 FOCUSED_WINDOW_LOCATION));
3826 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
3827 // valid touch target
3828 mUnfocusedWindow->assertNoEvents();
3829
3830 // Consume the first tap
3831 mFocusedWindow->finishEvent(*downEventSequenceNum);
3832 mFocusedWindow->finishEvent(*upEventSequenceNum);
3833 ASSERT_TRUE(mDispatcher->waitForIdle());
3834 // The second tap did not go to the focused window
3835 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003836 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003837 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003838 mFakePolicy->assertNotifyAnrWasNotCalled();
3839}
3840
3841// If you tap outside of all windows, there will not be ANR
3842TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003843 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003844 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3845 LOCATION_OUTSIDE_ALL_WINDOWS));
3846 ASSERT_TRUE(mDispatcher->waitForIdle());
3847 mFakePolicy->assertNotifyAnrWasNotCalled();
3848}
3849
3850// Since the focused window is paused, tapping on it should not produce any events
3851TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
3852 mFocusedWindow->setPaused(true);
3853 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3854
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003855 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003856 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3857 FOCUSED_WINDOW_LOCATION));
3858
3859 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
3860 ASSERT_TRUE(mDispatcher->waitForIdle());
3861 // Should not ANR because the window is paused, and touches shouldn't go to it
3862 mFakePolicy->assertNotifyAnrWasNotCalled();
3863
3864 mFocusedWindow->assertNoEvents();
3865 mUnfocusedWindow->assertNoEvents();
3866}
3867
3868/**
3869 * If a window is processing a motion event, and then a key event comes in, the key event should
3870 * not to to the focused window until the motion is processed.
3871 * If a different window becomes focused at this time, the key should go to that window instead.
3872 *
3873 * Warning!!!
3874 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3875 * and the injection timeout that we specify when injecting the key.
3876 * We must have the injection timeout (10ms) be smaller than
3877 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3878 *
3879 * If that value changes, this test should also change.
3880 */
3881TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
3882 // Set a long ANR timeout to prevent it from triggering
3883 mFocusedWindow->setDispatchingTimeout(2s);
3884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3885
3886 tapOnUnfocusedWindow();
3887 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
3888 ASSERT_TRUE(downSequenceNum);
3889 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
3890 ASSERT_TRUE(upSequenceNum);
3891 // Don't finish the events yet, and send a key
3892 // Injection will succeed because we will eventually give up and send the key to the focused
3893 // window even if motions are still being processed.
3894
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003895 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003896 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003897 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3898 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003899 // Key will not be sent to the window, yet, because the window is still processing events
3900 // and the key remains pending, waiting for the touch events to be processed
3901 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
3902 ASSERT_FALSE(keySequenceNum);
3903
3904 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07003905 mFocusedWindow->setFocusable(false);
3906 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003908 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003909
3910 // Focus events should precede the key events
3911 mUnfocusedWindow->consumeFocusEvent(true);
3912 mFocusedWindow->consumeFocusEvent(false);
3913
3914 // Finish the tap events, which should unblock dispatcher
3915 mUnfocusedWindow->finishEvent(*downSequenceNum);
3916 mUnfocusedWindow->finishEvent(*upSequenceNum);
3917
3918 // Now that all queues are cleared and no backlog in the connections, the key event
3919 // can finally go to the newly focused "mUnfocusedWindow".
3920 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3921 mFocusedWindow->assertNoEvents();
3922 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003923 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003924}
3925
3926// When the touch stream is split across 2 windows, and one of them does not respond,
3927// then ANR should be raised and the touch should be canceled for the unresponsive window.
3928// The other window should not be affected by that.
3929TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
3930 // Touch Window 1
3931 NotifyMotionArgs motionArgs =
3932 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3933 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
3934 mDispatcher->notifyMotion(&motionArgs);
3935 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3936 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3937
3938 // Touch Window 2
3939 int32_t actionPointerDown =
3940 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3941
3942 motionArgs =
3943 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3944 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
3945 mDispatcher->notifyMotion(&motionArgs);
3946
3947 const std::chrono::duration timeout =
3948 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003949 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003950
3951 mUnfocusedWindow->consumeMotionDown();
3952 mFocusedWindow->consumeMotionDown();
3953 // Focused window may or may not receive ACTION_MOVE
3954 // But it should definitely receive ACTION_CANCEL due to the ANR
3955 InputEvent* event;
3956 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
3957 ASSERT_TRUE(moveOrCancelSequenceNum);
3958 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
3959 ASSERT_NE(nullptr, event);
3960 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
3961 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
3962 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
3963 mFocusedWindow->consumeMotionCancel();
3964 } else {
3965 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
3966 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003967 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003968 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003969
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003970 mUnfocusedWindow->assertNoEvents();
3971 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003972 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003973}
3974
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003975/**
3976 * If we have no focused window, and a key comes in, we start the ANR timer.
3977 * The focused application should add a focused window before the timer runs out to prevent ANR.
3978 *
3979 * If the user touches another application during this time, the key should be dropped.
3980 * Next, if a new focused window comes in, without toggling the focused application,
3981 * then no ANR should occur.
3982 *
3983 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
3984 * but in some cases the policy may not update the focused application.
3985 */
3986TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
3987 std::shared_ptr<FakeApplicationHandle> focusedApplication =
3988 std::make_shared<FakeApplicationHandle>();
3989 focusedApplication->setDispatchingTimeout(60ms);
3990 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
3991 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
3992 mFocusedWindow->setFocusable(false);
3993
3994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3995 mFocusedWindow->consumeFocusEvent(false);
3996
3997 // Send a key. The ANR timer should start because there is no focused window.
3998 // 'focusedApplication' will get blamed if this timer completes.
3999 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004000 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004001 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004002 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4003 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004005
4006 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4007 // then the injected touches won't cause the focused event to get dropped.
4008 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4009 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4010 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4011 // For this test, it means that the key would get delivered to the window once it becomes
4012 // focused.
4013 std::this_thread::sleep_for(10ms);
4014
4015 // Touch unfocused window. This should force the pending key to get dropped.
4016 NotifyMotionArgs motionArgs =
4017 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4018 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4019 mDispatcher->notifyMotion(&motionArgs);
4020
4021 // We do not consume the motion right away, because that would require dispatcher to first
4022 // process (== drop) the key event, and by that time, ANR will be raised.
4023 // Set the focused window first.
4024 mFocusedWindow->setFocusable(true);
4025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4026 setFocusedWindow(mFocusedWindow);
4027 mFocusedWindow->consumeFocusEvent(true);
4028 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4029 // to another application. This could be a bug / behaviour in the policy.
4030
4031 mUnfocusedWindow->consumeMotionDown();
4032
4033 ASSERT_TRUE(mDispatcher->waitForIdle());
4034 // Should not ANR because we actually have a focused window. It was just added too slowly.
4035 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4036}
4037
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004038// These tests ensure we cannot send touch events to a window that's positioned behind a window
4039// that has feature NO_INPUT_CHANNEL.
4040// Layout:
4041// Top (closest to user)
4042// mNoInputWindow (above all windows)
4043// mBottomWindow
4044// Bottom (furthest from user)
4045class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4046 virtual void SetUp() override {
4047 InputDispatcherTest::SetUp();
4048
4049 mApplication = std::make_shared<FakeApplicationHandle>();
4050 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4051 "Window without input channel", ADISPLAY_ID_DEFAULT,
4052 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4053
4054 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4055 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4056 // It's perfectly valid for this window to not have an associated input channel
4057
4058 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4059 ADISPLAY_ID_DEFAULT);
4060 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4061
4062 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4063 }
4064
4065protected:
4066 std::shared_ptr<FakeApplicationHandle> mApplication;
4067 sp<FakeWindowHandle> mNoInputWindow;
4068 sp<FakeWindowHandle> mBottomWindow;
4069};
4070
4071TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4072 PointF touchedPoint = {10, 10};
4073
4074 NotifyMotionArgs motionArgs =
4075 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4076 ADISPLAY_ID_DEFAULT, {touchedPoint});
4077 mDispatcher->notifyMotion(&motionArgs);
4078
4079 mNoInputWindow->assertNoEvents();
4080 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4081 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4082 // and therefore should prevent mBottomWindow from receiving touches
4083 mBottomWindow->assertNoEvents();
4084}
4085
4086/**
4087 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4088 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4089 */
4090TEST_F(InputDispatcherMultiWindowOcclusionTests,
4091 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4092 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4093 "Window with input channel and NO_INPUT_CHANNEL",
4094 ADISPLAY_ID_DEFAULT);
4095
4096 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4097 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4098 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4099
4100 PointF touchedPoint = {10, 10};
4101
4102 NotifyMotionArgs motionArgs =
4103 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4104 ADISPLAY_ID_DEFAULT, {touchedPoint});
4105 mDispatcher->notifyMotion(&motionArgs);
4106
4107 mNoInputWindow->assertNoEvents();
4108 mBottomWindow->assertNoEvents();
4109}
4110
Vishnu Nair958da932020-08-21 17:12:37 -07004111class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4112protected:
4113 std::shared_ptr<FakeApplicationHandle> mApp;
4114 sp<FakeWindowHandle> mWindow;
4115 sp<FakeWindowHandle> mMirror;
4116
4117 virtual void SetUp() override {
4118 InputDispatcherTest::SetUp();
4119 mApp = std::make_shared<FakeApplicationHandle>();
4120 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4121 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4122 mWindow->getToken());
4123 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4124 mWindow->setFocusable(true);
4125 mMirror->setFocusable(true);
4126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4127 }
4128};
4129
4130TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4131 // Request focus on a mirrored window
4132 setFocusedWindow(mMirror);
4133
4134 // window gets focused
4135 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4137 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004138 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4139}
4140
4141// A focused & mirrored window remains focused only if the window and its mirror are both
4142// focusable.
4143TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4144 setFocusedWindow(mMirror);
4145
4146 // window gets focused
4147 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4149 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004150 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004151 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4152 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004153 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4154
4155 mMirror->setFocusable(false);
4156 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4157
4158 // window loses focus since one of the windows associated with the token in not focusable
4159 mWindow->consumeFocusEvent(false);
4160
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004161 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4162 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004163 mWindow->assertNoEvents();
4164}
4165
4166// A focused & mirrored window remains focused until the window and its mirror both become
4167// invisible.
4168TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4169 setFocusedWindow(mMirror);
4170
4171 // window gets focused
4172 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4174 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004175 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4177 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004178 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4179
4180 mMirror->setVisible(false);
4181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4182
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004183 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4184 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004185 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004186 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4187 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004188 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4189
4190 mWindow->setVisible(false);
4191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4192
4193 // window loses focus only after all windows associated with the token become invisible.
4194 mWindow->consumeFocusEvent(false);
4195
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004196 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4197 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004198 mWindow->assertNoEvents();
4199}
4200
4201// A focused & mirrored window remains focused until both windows are removed.
4202TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4203 setFocusedWindow(mMirror);
4204
4205 // window gets focused
4206 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004207 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4208 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004209 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004210 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4211 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004212 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4213
4214 // single window is removed but the window token remains focused
4215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4216
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004217 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4218 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004219 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004220 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4221 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004222 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4223
4224 // Both windows are removed
4225 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4226 mWindow->consumeFocusEvent(false);
4227
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004228 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4229 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004230 mWindow->assertNoEvents();
4231}
4232
4233// Focus request can be pending until one window becomes visible.
4234TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4235 // Request focus on an invisible mirror.
4236 mWindow->setVisible(false);
4237 mMirror->setVisible(false);
4238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4239 setFocusedWindow(mMirror);
4240
4241 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004242 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004243 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004244 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004245
4246 mMirror->setVisible(true);
4247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4248
4249 // window gets focused
4250 mWindow->consumeFocusEvent(true);
4251 // window gets the pending key event
4252 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4253}
Prabir Pradhan99987712020-11-10 18:43:05 -08004254
4255class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4256protected:
4257 std::shared_ptr<FakeApplicationHandle> mApp;
4258 sp<FakeWindowHandle> mWindow;
4259 sp<FakeWindowHandle> mSecondWindow;
4260
4261 void SetUp() override {
4262 InputDispatcherTest::SetUp();
4263 mApp = std::make_shared<FakeApplicationHandle>();
4264 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4265 mWindow->setFocusable(true);
4266 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4267 mSecondWindow->setFocusable(true);
4268
4269 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4271
4272 setFocusedWindow(mWindow);
4273 mWindow->consumeFocusEvent(true);
4274 }
4275
4276 void notifyPointerCaptureChanged(bool enabled) {
4277 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
4278 mDispatcher->notifyPointerCaptureChanged(&args);
4279 }
4280
4281 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
4282 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4283 mFakePolicy->waitForSetPointerCapture(enabled);
4284 notifyPointerCaptureChanged(enabled);
4285 window->consumeCaptureEvent(enabled);
4286 }
4287};
4288
4289TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4290 // Ensure that capture cannot be obtained for unfocused windows.
4291 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4292 mFakePolicy->assertSetPointerCaptureNotCalled();
4293 mSecondWindow->assertNoEvents();
4294
4295 // Ensure that capture can be enabled from the focus window.
4296 requestAndVerifyPointerCapture(mWindow, true);
4297
4298 // Ensure that capture cannot be disabled from a window that does not have capture.
4299 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4300 mFakePolicy->assertSetPointerCaptureNotCalled();
4301
4302 // Ensure that capture can be disabled from the window with capture.
4303 requestAndVerifyPointerCapture(mWindow, false);
4304}
4305
4306TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4307 requestAndVerifyPointerCapture(mWindow, true);
4308
4309 setFocusedWindow(mSecondWindow);
4310
4311 // Ensure that the capture disabled event was sent first.
4312 mWindow->consumeCaptureEvent(false);
4313 mWindow->consumeFocusEvent(false);
4314 mSecondWindow->consumeFocusEvent(true);
4315 mFakePolicy->waitForSetPointerCapture(false);
4316
4317 // Ensure that additional state changes from InputReader are not sent to the window.
4318 notifyPointerCaptureChanged(false);
4319 notifyPointerCaptureChanged(true);
4320 notifyPointerCaptureChanged(false);
4321 mWindow->assertNoEvents();
4322 mSecondWindow->assertNoEvents();
4323 mFakePolicy->assertSetPointerCaptureNotCalled();
4324}
4325
4326TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4327 requestAndVerifyPointerCapture(mWindow, true);
4328
4329 // InputReader unexpectedly disables and enables pointer capture.
4330 notifyPointerCaptureChanged(false);
4331 notifyPointerCaptureChanged(true);
4332
4333 // Ensure that Pointer Capture is disabled.
Prabir Pradhan7d030382020-12-21 07:58:35 -08004334 mFakePolicy->waitForSetPointerCapture(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004335 mWindow->consumeCaptureEvent(false);
4336 mWindow->assertNoEvents();
4337}
4338
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004339TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4340 requestAndVerifyPointerCapture(mWindow, true);
4341
4342 // The first window loses focus.
4343 setFocusedWindow(mSecondWindow);
4344 mFakePolicy->waitForSetPointerCapture(false);
4345 mWindow->consumeCaptureEvent(false);
4346
4347 // Request Pointer Capture from the second window before the notification from InputReader
4348 // arrives.
4349 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4350 mFakePolicy->waitForSetPointerCapture(true);
4351
4352 // InputReader notifies Pointer Capture was disabled (because of the focus change).
4353 notifyPointerCaptureChanged(false);
4354
4355 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
4356 notifyPointerCaptureChanged(true);
4357
4358 mSecondWindow->consumeFocusEvent(true);
4359 mSecondWindow->consumeCaptureEvent(true);
4360}
4361
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004362class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4363protected:
4364 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00004365
4366 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4367 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4368
4369 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4370 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4371
4372 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4373 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4374 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4375 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4376 MAXIMUM_OBSCURING_OPACITY);
4377
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004378 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004379 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004380 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004381
4382 sp<FakeWindowHandle> mTouchWindow;
4383
4384 virtual void SetUp() override {
4385 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004386 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004387 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4388 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4389 }
4390
4391 virtual void TearDown() override {
4392 InputDispatcherTest::TearDown();
4393 mTouchWindow.clear();
4394 }
4395
4396 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name,
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004397 os::TouchOcclusionMode mode, float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004398 sp<FakeWindowHandle> window = getWindow(uid, name);
4399 window->setFlags(InputWindowInfo::Flag::NOT_TOUCHABLE);
4400 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004401 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004402 return window;
4403 }
4404
4405 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4406 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4407 sp<FakeWindowHandle> window =
4408 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4409 // Generate an arbitrary PID based on the UID
4410 window->setOwnerInfo(1777 + (uid % 10000), uid);
4411 return window;
4412 }
4413
4414 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4415 NotifyMotionArgs args =
4416 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4417 ADISPLAY_ID_DEFAULT, points);
4418 mDispatcher->notifyMotion(&args);
4419 }
4420};
4421
4422TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004423 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004424 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004426
4427 touch();
4428
4429 mTouchWindow->assertNoEvents();
4430}
4431
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004432TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00004433 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
4434 const sp<FakeWindowHandle>& w =
4435 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
4436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4437
4438 touch();
4439
4440 mTouchWindow->assertNoEvents();
4441}
4442
4443TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004444 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
4445 const sp<FakeWindowHandle>& w =
4446 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4448
4449 touch();
4450
4451 w->assertNoEvents();
4452}
4453
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004454TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004455 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
4456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004457
4458 touch();
4459
4460 mTouchWindow->consumeAnyMotionDown();
4461}
4462
4463TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004464 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004465 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004466 w->setFrame(Rect(0, 0, 50, 50));
4467 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004468
4469 touch({PointF{100, 100}});
4470
4471 mTouchWindow->consumeAnyMotionDown();
4472}
4473
4474TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004475 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004476 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4478
4479 touch();
4480
4481 mTouchWindow->consumeAnyMotionDown();
4482}
4483
4484TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
4485 const sp<FakeWindowHandle>& w =
4486 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4487 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004488
4489 touch();
4490
4491 mTouchWindow->consumeAnyMotionDown();
4492}
4493
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004494TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
4495 const sp<FakeWindowHandle>& w =
4496 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4498
4499 touch();
4500
4501 w->assertNoEvents();
4502}
4503
4504/**
4505 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
4506 * inside) while letting them pass-through. Note that even though touch passes through the occluding
4507 * window, the occluding window will still receive ACTION_OUTSIDE event.
4508 */
4509TEST_F(InputDispatcherUntrustedTouchesTest,
4510 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
4511 const sp<FakeWindowHandle>& w =
4512 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4513 w->addFlags(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
4514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4515
4516 touch();
4517
4518 w->consumeMotionOutside();
4519}
4520
4521TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
4522 const sp<FakeWindowHandle>& w =
4523 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4524 w->addFlags(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
4525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4526
4527 touch();
4528
4529 InputEvent* event = w->consume();
4530 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
4531 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4532 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
4533 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
4534}
4535
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004536TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004537 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004538 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4539 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4541
4542 touch();
4543
4544 mTouchWindow->consumeAnyMotionDown();
4545}
4546
4547TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
4548 const sp<FakeWindowHandle>& w =
4549 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4550 MAXIMUM_OBSCURING_OPACITY);
4551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004552
4553 touch();
4554
4555 mTouchWindow->consumeAnyMotionDown();
4556}
4557
4558TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004559 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004560 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4561 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004562 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4563
4564 touch();
4565
4566 mTouchWindow->assertNoEvents();
4567}
4568
4569TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
4570 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
4571 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004572 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4573 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004574 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004575 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4576 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4578
4579 touch();
4580
4581 mTouchWindow->assertNoEvents();
4582}
4583
4584TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
4585 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
4586 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004587 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4588 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004589 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004590 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4591 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004592 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4593
4594 touch();
4595
4596 mTouchWindow->consumeAnyMotionDown();
4597}
4598
4599TEST_F(InputDispatcherUntrustedTouchesTest,
4600 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
4601 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004602 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4603 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004604 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004605 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4606 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4608
4609 touch();
4610
4611 mTouchWindow->consumeAnyMotionDown();
4612}
4613
4614TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
4615 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004616 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4617 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004618 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004619 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4620 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004622
4623 touch();
4624
4625 mTouchWindow->assertNoEvents();
4626}
4627
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004628TEST_F(InputDispatcherUntrustedTouchesTest,
4629 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
4630 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004631 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4632 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004633 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004634 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4635 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4637
4638 touch();
4639
4640 mTouchWindow->assertNoEvents();
4641}
4642
4643TEST_F(InputDispatcherUntrustedTouchesTest,
4644 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
4645 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004646 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4647 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004648 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004649 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4650 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4652
4653 touch();
4654
4655 mTouchWindow->consumeAnyMotionDown();
4656}
4657
4658TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
4659 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004660 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4661 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4663
4664 touch();
4665
4666 mTouchWindow->consumeAnyMotionDown();
4667}
4668
4669TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
4670 const sp<FakeWindowHandle>& w =
4671 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
4672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4673
4674 touch();
4675
4676 mTouchWindow->consumeAnyMotionDown();
4677}
4678
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004679TEST_F(InputDispatcherUntrustedTouchesTest,
4680 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
4681 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4682 const sp<FakeWindowHandle>& w =
4683 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
4684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4685
4686 touch();
4687
4688 mTouchWindow->assertNoEvents();
4689}
4690
4691TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
4692 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4693 const sp<FakeWindowHandle>& w =
4694 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
4695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4696
4697 touch();
4698
4699 mTouchWindow->consumeAnyMotionDown();
4700}
4701
4702TEST_F(InputDispatcherUntrustedTouchesTest,
4703 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
4704 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
4705 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004706 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4707 OPACITY_ABOVE_THRESHOLD);
4708 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4709
4710 touch();
4711
4712 mTouchWindow->consumeAnyMotionDown();
4713}
4714
4715TEST_F(InputDispatcherUntrustedTouchesTest,
4716 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
4717 const sp<FakeWindowHandle>& w1 =
4718 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4719 OPACITY_BELOW_THRESHOLD);
4720 const sp<FakeWindowHandle>& w2 =
4721 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4722 OPACITY_BELOW_THRESHOLD);
4723 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4724
4725 touch();
4726
4727 mTouchWindow->assertNoEvents();
4728}
4729
4730/**
4731 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
4732 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
4733 * (which alone would result in allowing touches) does not affect the blocking behavior.
4734 */
4735TEST_F(InputDispatcherUntrustedTouchesTest,
4736 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
4737 const sp<FakeWindowHandle>& wB =
4738 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4739 OPACITY_BELOW_THRESHOLD);
4740 const sp<FakeWindowHandle>& wC =
4741 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4742 OPACITY_BELOW_THRESHOLD);
4743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4744
4745 touch();
4746
4747 mTouchWindow->assertNoEvents();
4748}
4749
4750/**
4751 * This test is testing that a window from a different UID but with same application token doesn't
4752 * block the touch. Apps can share the application token for close UI collaboration for example.
4753 */
4754TEST_F(InputDispatcherUntrustedTouchesTest,
4755 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
4756 const sp<FakeWindowHandle>& w =
4757 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4758 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4760
4761 touch();
4762
4763 mTouchWindow->consumeAnyMotionDown();
4764}
4765
arthurhungb89ccb02020-12-30 16:19:01 +08004766class InputDispatcherDragTests : public InputDispatcherTest {
4767protected:
4768 std::shared_ptr<FakeApplicationHandle> mApp;
4769 sp<FakeWindowHandle> mWindow;
4770 sp<FakeWindowHandle> mSecondWindow;
4771 sp<FakeWindowHandle> mDragWindow;
4772
4773 void SetUp() override {
4774 InputDispatcherTest::SetUp();
4775 mApp = std::make_shared<FakeApplicationHandle>();
4776 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4777 mWindow->setFrame(Rect(0, 0, 100, 100));
4778 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
4779
4780 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4781 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
4782 mSecondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
4783
4784 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4786 }
4787
4788 // Start performing drag, we will create a drag window and transfer touch to it.
4789 void performDrag() {
4790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4791 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4792 {50, 50}))
4793 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4794
4795 // Window should receive motion event.
4796 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4797
4798 // The drag window covers the entire display
4799 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
4800 mDispatcher->setInputWindows(
4801 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
4802
4803 // Transfer touch focus to the drag window
4804 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
4805 true /* isDragDrop */);
4806 mWindow->consumeMotionCancel();
4807 mDragWindow->consumeMotionDown();
4808 }
arthurhung6d4bed92021-03-17 11:59:33 +08004809
4810 // Start performing drag, we will create a drag window and transfer touch to it.
4811 void performStylusDrag() {
4812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4813 injectMotionEvent(mDispatcher,
4814 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
4815 AINPUT_SOURCE_STYLUS)
4816 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
4817 .pointer(PointerBuilder(0,
4818 AMOTION_EVENT_TOOL_TYPE_STYLUS)
4819 .x(50)
4820 .y(50))
4821 .build()));
4822 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4823
4824 // The drag window covers the entire display
4825 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
4826 mDispatcher->setInputWindows(
4827 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
4828
4829 // Transfer touch focus to the drag window
4830 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
4831 true /* isDragDrop */);
4832 mWindow->consumeMotionCancel();
4833 mDragWindow->consumeMotionDown();
4834 }
arthurhungb89ccb02020-12-30 16:19:01 +08004835};
4836
4837TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
4838 performDrag();
4839
4840 // Move on window.
4841 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4842 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4843 ADISPLAY_ID_DEFAULT, {50, 50}))
4844 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4845 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4846 mWindow->consumeDragEvent(false, 50, 50);
4847 mSecondWindow->assertNoEvents();
4848
4849 // Move to another window.
4850 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4851 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4852 ADISPLAY_ID_DEFAULT, {150, 50}))
4853 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4854 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4855 mWindow->consumeDragEvent(true, 150, 50);
4856 mSecondWindow->consumeDragEvent(false, 50, 50);
4857
4858 // Move back to original window.
4859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4860 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4861 ADISPLAY_ID_DEFAULT, {50, 50}))
4862 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4863 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4864 mWindow->consumeDragEvent(false, 50, 50);
4865 mSecondWindow->consumeDragEvent(true, -50, 50);
4866
4867 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4868 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
4869 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4870 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
4871 mWindow->assertNoEvents();
4872 mSecondWindow->assertNoEvents();
4873}
4874
arthurhungf452d0b2021-01-06 00:19:52 +08004875TEST_F(InputDispatcherDragTests, DragAndDrop) {
4876 performDrag();
4877
4878 // Move on window.
4879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4880 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4881 ADISPLAY_ID_DEFAULT, {50, 50}))
4882 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4883 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4884 mWindow->consumeDragEvent(false, 50, 50);
4885 mSecondWindow->assertNoEvents();
4886
4887 // Move to another window.
4888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4889 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4890 ADISPLAY_ID_DEFAULT, {150, 50}))
4891 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4892 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4893 mWindow->consumeDragEvent(true, 150, 50);
4894 mSecondWindow->consumeDragEvent(false, 50, 50);
4895
4896 // drop to another window.
4897 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4898 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4899 {150, 50}))
4900 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4901 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
4902 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
4903 mWindow->assertNoEvents();
4904 mSecondWindow->assertNoEvents();
4905}
4906
arthurhung6d4bed92021-03-17 11:59:33 +08004907TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
4908 performStylusDrag();
4909
4910 // Move on window and keep button pressed.
4911 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4912 injectMotionEvent(mDispatcher,
4913 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
4914 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
4915 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
4916 .x(50)
4917 .y(50))
4918 .build()))
4919 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4920 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4921 mWindow->consumeDragEvent(false, 50, 50);
4922 mSecondWindow->assertNoEvents();
4923
4924 // Move to another window and release button, expect to drop item.
4925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4926 injectMotionEvent(mDispatcher,
4927 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
4928 .buttonState(0)
4929 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
4930 .x(150)
4931 .y(50))
4932 .build()))
4933 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4934 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4935 mWindow->assertNoEvents();
4936 mSecondWindow->assertNoEvents();
4937 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
4938
4939 // nothing to the window.
4940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4941 injectMotionEvent(mDispatcher,
4942 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
4943 .buttonState(0)
4944 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
4945 .x(150)
4946 .y(50))
4947 .build()))
4948 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4949 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
4950 mWindow->assertNoEvents();
4951 mSecondWindow->assertNoEvents();
4952}
4953
Garfield Tane84e6f92019-08-29 17:28:41 -07004954} // namespace android::inputdispatcher