blob: 2a8c1bdbb48c6d629bbab46fe8f145034757b2d3 [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
Michael Wrightd02c5b62014-02-10 15:10:22 -0800269private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700270 std::mutex mLock;
271 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
272 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
273 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
274 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800275
Prabir Pradhan99987712020-11-10 18:43:05 -0800276 std::condition_variable mPointerCaptureChangedCondition;
277 std::optional<bool> mPointerCaptureEnabled GUARDED_BY(mLock);
278
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700279 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700280 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000281 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
282 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
283 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
284 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700285 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700286
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600287 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700288 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800289 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800290 }
291
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000292 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700293 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000294 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700295 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500296 }
297
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000298 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500299 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000300 mAnrMonitorPids.push(pid);
301 mNotifyAnr.notify_all();
302 }
303
304 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
305 std::scoped_lock lock(mLock);
306 mResponsiveWindowTokens.push(connectionToken);
307 mNotifyAnr.notify_all();
308 }
309
310 void notifyMonitorResponsive(int32_t pid) override {
311 std::scoped_lock lock(mLock);
312 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500313 mNotifyAnr.notify_all();
314 }
315
316 void notifyNoFocusedWindowAnr(
317 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
318 std::scoped_lock lock(mLock);
319 mAnrApplications.push(applicationHandle);
320 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800321 }
322
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600323 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800324
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600325 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700326
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600327 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700328 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
329 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
330 const std::vector<float>& values) override {}
331
332 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
333 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000334
Chris Yefb552902021-02-03 17:18:37 -0800335 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
336
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600337 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800338 *outConfig = mConfig;
339 }
340
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600341 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700342 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800343 switch (inputEvent->getType()) {
344 case AINPUT_EVENT_TYPE_KEY: {
345 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800346 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800347 break;
348 }
349
350 case AINPUT_EVENT_TYPE_MOTION: {
351 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800352 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800353 break;
354 }
355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 return true;
357 }
358
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600359 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600361 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800362
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600363 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800364 return 0;
365 }
366
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600367 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800368 return false;
369 }
370
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600371 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
372 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700373 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800374 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
375 * essentially a passthrough for notifySwitch.
376 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800377 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378 }
379
Sean Stoutb4e0a592021-02-23 07:34:53 -0800380 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800381
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800382 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
383 return pid == INJECTOR_PID && uid == INJECTOR_UID;
384 }
Jackal Guof9696682018-10-05 12:23:23 +0800385
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600386 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700387 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700388 mOnPointerDownToken = newToken;
389 }
390
Prabir Pradhan99987712020-11-10 18:43:05 -0800391 void setPointerCapture(bool enabled) override {
392 std::scoped_lock lock(mLock);
393 mPointerCaptureEnabled = {enabled};
394 mPointerCaptureChangedCondition.notify_all();
395 }
396
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800397 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
398 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700399 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800400 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
401 ASSERT_EQ(mFilteredEvent->getType(), type);
402
403 if (type == AINPUT_EVENT_TYPE_KEY) {
404 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
405 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
406 EXPECT_EQ(keyEvent.getAction(), action);
407 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
408 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
409 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
410 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
411 EXPECT_EQ(motionEvent.getAction(), action);
412 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
413 } else {
414 FAIL() << "Unknown type: " << type;
415 }
416
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800417 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419};
420
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421// --- InputDispatcherTest ---
422
423class InputDispatcherTest : public testing::Test {
424protected:
425 sp<FakeInputDispatcherPolicy> mFakePolicy;
426 sp<InputDispatcher> mDispatcher;
427
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700428 virtual void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 mFakePolicy = new FakeInputDispatcherPolicy();
430 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800431 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000432 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700433 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 }
435
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700436 virtual void TearDown() override {
437 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 mFakePolicy.clear();
439 mDispatcher.clear();
440 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700441
442 /**
443 * Used for debugging when writing the test
444 */
445 void dumpDispatcherState() {
446 std::string dump;
447 mDispatcher->dump(dump);
448 std::stringstream ss(dump);
449 std::string to;
450
451 while (std::getline(ss, to, '\n')) {
452 ALOGE("%s", to.c_str());
453 }
454 }
Vishnu Nair958da932020-08-21 17:12:37 -0700455
456 void setFocusedWindow(const sp<InputWindowHandle>& window,
457 const sp<InputWindowHandle>& focusedWindow = nullptr) {
458 FocusRequest request;
459 request.token = window->getToken();
460 if (focusedWindow) {
461 request.focusedToken = focusedWindow->getToken();
462 }
463 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
464 request.displayId = window->getInfo()->displayId;
465 mDispatcher->setFocusedWindow(request);
466 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467};
468
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
470 KeyEvent event;
471
472 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800473 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
474 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600475 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
476 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800477 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700478 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800479 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800480 << "Should reject key events with undefined action.";
481
482 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800483 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
484 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600485 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800486 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700487 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800488 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489 << "Should reject key events with ACTION_MULTIPLE.";
490}
491
492TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
493 MotionEvent event;
494 PointerProperties pointerProperties[MAX_POINTERS + 1];
495 PointerCoords pointerCoords[MAX_POINTERS + 1];
496 for (int i = 0; i <= MAX_POINTERS; i++) {
497 pointerProperties[i].clear();
498 pointerProperties[i].id = i;
499 pointerCoords[i].clear();
500 }
501
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800502 // Some constants commonly used below
503 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
504 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
505 constexpr int32_t metaState = AMETA_NONE;
506 constexpr MotionClassification classification = MotionClassification::NONE;
507
chaviw9eaa22c2020-07-01 16:21:27 -0700508 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800510 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700511 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
512 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600513 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700514 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800515 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700516 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800517 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800518 << "Should reject motion events with undefined action.";
519
520 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800521 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700522 AMOTION_EVENT_ACTION_POINTER_DOWN |
523 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700524 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
525 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
526 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
527 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800528 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700529 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800530 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 << "Should reject motion events with pointer down index too large.";
532
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 (~0U << 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 small.";
544
545 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800546 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700547 AMOTION_EVENT_ACTION_POINTER_UP |
548 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700549 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
550 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
551 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
552 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800553 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700554 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800555 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 << "Should reject motion events with pointer up index too large.";
557
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 (~0U << 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 small.";
569
570 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800571 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
572 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700573 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
574 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700575 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800576 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700577 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800578 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 << "Should reject motion events with 0 pointers.";
580
Garfield Tanfbe732e2020-01-24 11:26:14 -0800581 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
582 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700583 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
584 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700585 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800586 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700587 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800588 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 << "Should reject motion events with more than MAX_POINTERS pointers.";
590
591 // Rejects motion events with invalid pointer ids.
592 pointerProperties[0].id = -1;
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*/ 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 pointer ids less than 0.";
602
603 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800604 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
605 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700606 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
607 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700608 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800609 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700610 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800611 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
613
614 // Rejects motion events with duplicate pointer ids.
615 pointerProperties[0].id = 1;
616 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800617 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
618 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700619 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
620 AMOTION_EVENT_INVALID_CURSOR_POSITION, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700621 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800622 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700623 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 << "Should reject motion events with duplicate pointer ids.";
626}
627
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800628/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
629
630TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
631 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800632 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800633 mDispatcher->notifyConfigurationChanged(&args);
634 ASSERT_TRUE(mDispatcher->waitForIdle());
635
636 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
637}
638
639TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800640 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
641 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800642 mDispatcher->notifySwitch(&args);
643
644 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
645 args.policyFlags |= POLICY_FLAG_TRUSTED;
646 mFakePolicy->assertNotifySwitchWasCalled(args);
647}
648
Arthur Hungb92218b2018-08-14 12:00:21 +0800649// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700650static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700651static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800652
653class FakeApplicationHandle : public InputApplicationHandle {
654public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700655 FakeApplicationHandle() {
656 mInfo.name = "Fake Application";
657 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500658 mInfo.dispatchingTimeoutMillis =
659 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700660 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800661 virtual ~FakeApplicationHandle() {}
662
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000663 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700664
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500665 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
666 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700667 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800668};
669
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800670class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800671public:
Garfield Tan15601662020-09-22 15:32:38 -0700672 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800673 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700674 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800675 }
676
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800677 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700678 InputEvent* event;
679 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
680 if (!consumeSeq) {
681 return nullptr;
682 }
683 finishEvent(*consumeSeq);
684 return event;
685 }
686
687 /**
688 * Receive an event without acknowledging it.
689 * Return the sequence number that could later be used to send finished signal.
690 */
691 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800692 uint32_t consumeSeq;
693 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800694
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800695 std::chrono::time_point start = std::chrono::steady_clock::now();
696 status_t status = WOULD_BLOCK;
697 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800698 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800699 &event);
700 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
701 if (elapsed > 100ms) {
702 break;
703 }
704 }
705
706 if (status == WOULD_BLOCK) {
707 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700708 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800709 }
710
711 if (status != OK) {
712 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700713 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800714 }
715 if (event == nullptr) {
716 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700717 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800718 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700719 if (outEvent != nullptr) {
720 *outEvent = event;
721 }
722 return consumeSeq;
723 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800724
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700725 /**
726 * To be used together with "receiveEvent" to complete the consumption of an event.
727 */
728 void finishEvent(uint32_t consumeSeq) {
729 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
730 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800731 }
732
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000733 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
734 std::optional<int32_t> expectedDisplayId,
735 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800736 InputEvent* event = consume();
737
738 ASSERT_NE(nullptr, event) << mName.c_str()
739 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800740 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700741 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800742 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800743
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000744 if (expectedDisplayId.has_value()) {
745 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
746 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800747
Tiger Huang8664f8c2018-10-11 19:14:35 +0800748 switch (expectedEventType) {
749 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800750 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
751 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000752 if (expectedFlags.has_value()) {
753 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
754 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800755 break;
756 }
757 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800758 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
759 EXPECT_EQ(expectedAction, motionEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000760 if (expectedFlags.has_value()) {
761 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
762 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800763 break;
764 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100765 case AINPUT_EVENT_TYPE_FOCUS: {
766 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
767 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800768 case AINPUT_EVENT_TYPE_CAPTURE: {
769 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
770 }
arthurhungb89ccb02020-12-30 16:19:01 +0800771 case AINPUT_EVENT_TYPE_DRAG: {
772 FAIL() << "Use 'consumeDragEvent' for DRAG events";
773 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800774 default: {
775 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
776 }
777 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800778 }
779
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100780 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
781 InputEvent* event = consume();
782 ASSERT_NE(nullptr, event) << mName.c_str()
783 << ": consumer should have returned non-NULL event.";
784 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
785 << "Got " << inputEventTypeToString(event->getType())
786 << " event instead of FOCUS event";
787
788 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
789 << mName.c_str() << ": event displayId should always be NONE.";
790
791 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
792 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
793 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
794 }
795
Prabir Pradhan99987712020-11-10 18:43:05 -0800796 void consumeCaptureEvent(bool hasCapture) {
797 const InputEvent* event = consume();
798 ASSERT_NE(nullptr, event) << mName.c_str()
799 << ": consumer should have returned non-NULL event.";
800 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
801 << "Got " << inputEventTypeToString(event->getType())
802 << " event instead of CAPTURE event";
803
804 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
805 << mName.c_str() << ": event displayId should always be NONE.";
806
807 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
808 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
809 }
810
arthurhungb89ccb02020-12-30 16:19:01 +0800811 void consumeDragEvent(bool isExiting, float x, float y) {
812 const InputEvent* event = consume();
813 ASSERT_NE(nullptr, event) << mName.c_str()
814 << ": consumer should have returned non-NULL event.";
815 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
816 << "Got " << inputEventTypeToString(event->getType())
817 << " event instead of DRAG event";
818
819 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
820 << mName.c_str() << ": event displayId should always be NONE.";
821
822 const auto& dragEvent = static_cast<const DragEvent&>(*event);
823 EXPECT_EQ(isExiting, dragEvent.isExiting());
824 EXPECT_EQ(x, dragEvent.getX());
825 EXPECT_EQ(y, dragEvent.getY());
826 }
827
chaviwd1c23182019-12-20 18:44:56 -0800828 void assertNoEvents() {
829 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700830 if (event == nullptr) {
831 return;
832 }
833 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
834 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
835 ADD_FAILURE() << "Received key event "
836 << KeyEvent::actionToString(keyEvent.getAction());
837 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
838 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
839 ADD_FAILURE() << "Received motion event "
840 << MotionEvent::actionToString(motionEvent.getAction());
841 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
842 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
843 ADD_FAILURE() << "Received focus event, hasFocus = "
844 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800845 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
846 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
847 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
848 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700849 }
850 FAIL() << mName.c_str()
851 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800852 }
853
854 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
855
856protected:
857 std::unique_ptr<InputConsumer> mConsumer;
858 PreallocatedInputEventFactory mEventFactory;
859
860 std::string mName;
861};
862
863class FakeWindowHandle : public InputWindowHandle {
864public:
865 static const int32_t WIDTH = 600;
866 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800867
Chris Yea209fde2020-07-22 13:54:51 -0700868 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800869 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500870 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800871 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500872 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700873 base::Result<std::unique_ptr<InputChannel>> channel =
874 dispatcher->createInputChannel(name);
875 token = (*channel)->getConnectionToken();
876 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800877 }
878
879 inputApplicationHandle->updateInfo();
880 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
881
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500882 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700883 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800884 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100885 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500886 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000887 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800888 mInfo.frameLeft = 0;
889 mInfo.frameTop = 0;
890 mInfo.frameRight = WIDTH;
891 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700892 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800893 mInfo.globalScaleFactor = 1.0;
894 mInfo.touchableRegion.clear();
895 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
896 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700897 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800898 mInfo.hasWallpaper = false;
899 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800900 mInfo.ownerPid = INJECTOR_PID;
901 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800902 mInfo.displayId = displayId;
903 }
904
905 virtual bool updateInfo() { return true; }
906
Vishnu Nair47074b82020-08-14 11:54:47 -0700907 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800908
Vishnu Nair958da932020-08-21 17:12:37 -0700909 void setVisible(bool visible) { mInfo.visible = visible; }
910
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700911 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500912 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700913 }
914
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700915 void setPaused(bool paused) { mInfo.paused = paused; }
916
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000917 void setAlpha(float alpha) { mInfo.alpha = alpha; }
918
919 void setTouchOcclusionMode(android::os::TouchOcclusionMode mode) {
920 mInfo.touchOcclusionMode = mode;
921 }
922
Bernardo Rufino7393d172021-02-26 13:56:11 +0000923 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
924
chaviwd1c23182019-12-20 18:44:56 -0800925 void setFrame(const Rect& frame) {
926 mInfo.frameLeft = frame.left;
927 mInfo.frameTop = frame.top;
928 mInfo.frameRight = frame.right;
929 mInfo.frameBottom = frame.bottom;
arthurhungb89ccb02020-12-30 16:19:01 +0800930 mInfo.transform.set(-frame.left, -frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800931 mInfo.touchableRegion.clear();
932 mInfo.addTouchableRegion(frame);
933 }
934
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000935 void addFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags |= flags; }
936
Michael Wright44753b12020-07-08 13:48:11 +0100937 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800938
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500939 void setInputFeatures(InputWindowInfo::Feature features) { mInfo.inputFeatures = features; }
940
chaviw9eaa22c2020-07-01 16:21:27 -0700941 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
942 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
943 }
944
945 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700946
yunho.shinf4a80b82020-11-16 21:13:57 +0900947 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
948
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800949 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
950 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
951 expectedFlags);
952 }
953
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700954 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
955 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
956 }
957
Svet Ganov5d3bc372020-01-26 23:11:07 -0800958 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000959 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800960 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
961 expectedFlags);
962 }
963
964 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000965 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800966 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
967 expectedFlags);
968 }
969
970 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000971 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000972 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
973 }
974
975 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
976 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800977 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
978 expectedFlags);
979 }
980
Svet Ganov5d3bc372020-01-26 23:11:07 -0800981 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000982 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
983 int32_t expectedFlags = 0) {
984 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
985 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -0800986 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
987 }
988
989 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000990 int32_t expectedFlags = 0) {
991 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
992 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -0800993 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
994 }
995
996 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000997 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +0000998 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
999 expectedFlags);
1000 }
1001
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001002 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1003 int32_t expectedFlags = 0) {
1004 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1005 expectedFlags);
1006 }
1007
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001008 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1009 ASSERT_NE(mInputReceiver, nullptr)
1010 << "Cannot consume events from a window with no receiver";
1011 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1012 }
1013
Prabir Pradhan99987712020-11-10 18:43:05 -08001014 void consumeCaptureEvent(bool hasCapture) {
1015 ASSERT_NE(mInputReceiver, nullptr)
1016 << "Cannot consume events from a window with no receiver";
1017 mInputReceiver->consumeCaptureEvent(hasCapture);
1018 }
1019
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001020 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1021 std::optional<int32_t> expectedDisplayId,
1022 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001023 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1024 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1025 expectedFlags);
1026 }
1027
arthurhungb89ccb02020-12-30 16:19:01 +08001028 void consumeDragEvent(bool isExiting, float x, float y) {
1029 mInputReceiver->consumeDragEvent(isExiting, x, y);
1030 }
1031
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001032 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001033 if (mInputReceiver == nullptr) {
1034 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1035 return std::nullopt;
1036 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001037 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001038 }
1039
1040 void finishEvent(uint32_t sequenceNum) {
1041 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1042 mInputReceiver->finishEvent(sequenceNum);
1043 }
1044
chaviwaf87b3e2019-10-01 16:59:28 -07001045 InputEvent* consume() {
1046 if (mInputReceiver == nullptr) {
1047 return nullptr;
1048 }
1049 return mInputReceiver->consume();
1050 }
1051
Arthur Hungb92218b2018-08-14 12:00:21 +08001052 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001053 if (mInputReceiver == nullptr &&
1054 mInfo.inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL)) {
1055 return; // Can't receive events if the window does not have input channel
1056 }
1057 ASSERT_NE(nullptr, mInputReceiver)
1058 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001059 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001060 }
1061
chaviwaf87b3e2019-10-01 16:59:28 -07001062 sp<IBinder> getToken() { return mInfo.token; }
1063
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001064 const std::string& getName() { return mName; }
1065
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001066 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1067 mInfo.ownerPid = ownerPid;
1068 mInfo.ownerUid = ownerUid;
1069 }
1070
chaviwd1c23182019-12-20 18:44:56 -08001071private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001072 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001073 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001074 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001075};
1076
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001077std::atomic<int32_t> FakeWindowHandle::sId{1};
1078
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001079static InputEventInjectionResult injectKey(
1080 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1081 int32_t displayId = ADISPLAY_ID_NONE,
1082 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001083 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1084 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001085 KeyEvent event;
1086 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1087
1088 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001089 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001090 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1091 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001092
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001093 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1094 if (!allowKeyRepeat) {
1095 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1096 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001097 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001098 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001099 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001100}
1101
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001102static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1103 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001104 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1105}
1106
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001107// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1108// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1109// has to be woken up to process the repeating key.
1110static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1111 int32_t displayId = ADISPLAY_ID_NONE) {
1112 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1113 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1114 /* allowKeyRepeat */ false);
1115}
1116
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001117static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1118 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001119 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1120}
1121
Garfield Tandf26e862020-07-01 20:18:19 -07001122class PointerBuilder {
1123public:
1124 PointerBuilder(int32_t id, int32_t toolType) {
1125 mProperties.clear();
1126 mProperties.id = id;
1127 mProperties.toolType = toolType;
1128 mCoords.clear();
1129 }
1130
1131 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1132
1133 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1134
1135 PointerBuilder& axis(int32_t axis, float value) {
1136 mCoords.setAxisValue(axis, value);
1137 return *this;
1138 }
1139
1140 PointerProperties buildProperties() const { return mProperties; }
1141
1142 PointerCoords buildCoords() const { return mCoords; }
1143
1144private:
1145 PointerProperties mProperties;
1146 PointerCoords mCoords;
1147};
1148
1149class MotionEventBuilder {
1150public:
1151 MotionEventBuilder(int32_t action, int32_t source) {
1152 mAction = action;
1153 mSource = source;
1154 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1155 }
1156
1157 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1158 mEventTime = eventTime;
1159 return *this;
1160 }
1161
1162 MotionEventBuilder& displayId(int32_t displayId) {
1163 mDisplayId = displayId;
1164 return *this;
1165 }
1166
1167 MotionEventBuilder& actionButton(int32_t actionButton) {
1168 mActionButton = actionButton;
1169 return *this;
1170 }
1171
1172 MotionEventBuilder& buttonState(int32_t actionButton) {
1173 mActionButton = actionButton;
1174 return *this;
1175 }
1176
1177 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1178 mRawXCursorPosition = rawXCursorPosition;
1179 return *this;
1180 }
1181
1182 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1183 mRawYCursorPosition = rawYCursorPosition;
1184 return *this;
1185 }
1186
1187 MotionEventBuilder& pointer(PointerBuilder pointer) {
1188 mPointers.push_back(pointer);
1189 return *this;
1190 }
1191
1192 MotionEvent build() {
1193 std::vector<PointerProperties> pointerProperties;
1194 std::vector<PointerCoords> pointerCoords;
1195 for (const PointerBuilder& pointer : mPointers) {
1196 pointerProperties.push_back(pointer.buildProperties());
1197 pointerCoords.push_back(pointer.buildCoords());
1198 }
1199
1200 // Set mouse cursor position for the most common cases to avoid boilerplate.
1201 if (mSource == AINPUT_SOURCE_MOUSE &&
1202 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1203 mPointers.size() == 1) {
1204 mRawXCursorPosition = pointerCoords[0].getX();
1205 mRawYCursorPosition = pointerCoords[0].getY();
1206 }
1207
1208 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001209 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001210 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
1211 mAction, mActionButton, /* flags */ 0, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001212 mButtonState, MotionClassification::NONE, identityTransform,
1213 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
1214 mRawYCursorPosition, mEventTime, mEventTime, mPointers.size(),
1215 pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001216
1217 return event;
1218 }
1219
1220private:
1221 int32_t mAction;
1222 int32_t mSource;
1223 nsecs_t mEventTime;
1224 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1225 int32_t mActionButton{0};
1226 int32_t mButtonState{0};
1227 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1228 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1229
1230 std::vector<PointerBuilder> mPointers;
1231};
1232
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001233static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001234 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1235 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001236 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001237 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1238 injectionTimeout,
1239 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1240}
1241
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001242static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001243 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1244 const PointF& position,
1245 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001246 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1247 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001248 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001249 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001250 MotionEvent event = MotionEventBuilder(action, source)
1251 .displayId(displayId)
1252 .eventTime(eventTime)
1253 .rawXCursorPosition(cursorPosition.x)
1254 .rawYCursorPosition(cursorPosition.y)
1255 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1256 .x(position.x)
1257 .y(position.y))
1258 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001259
1260 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001261 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001262}
1263
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001264static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1265 int32_t source, int32_t displayId,
1266 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001267 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001268}
1269
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001270static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1271 int32_t source, int32_t displayId,
1272 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001273 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001274}
1275
Jackal Guof9696682018-10-05 12:23:23 +08001276static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1277 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1278 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001279 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1280 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1281 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001282
1283 return args;
1284}
1285
chaviwd1c23182019-12-20 18:44:56 -08001286static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1287 const std::vector<PointF>& points) {
1288 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001289 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1290 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1291 }
1292
chaviwd1c23182019-12-20 18:44:56 -08001293 PointerProperties pointerProperties[pointerCount];
1294 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001295
chaviwd1c23182019-12-20 18:44:56 -08001296 for (size_t i = 0; i < pointerCount; i++) {
1297 pointerProperties[i].clear();
1298 pointerProperties[i].id = i;
1299 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001300
chaviwd1c23182019-12-20 18:44:56 -08001301 pointerCoords[i].clear();
1302 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1303 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1304 }
Jackal Guof9696682018-10-05 12:23:23 +08001305
1306 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1307 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001308 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001309 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1310 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001311 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1312 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001313 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1314 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001315
1316 return args;
1317}
1318
chaviwd1c23182019-12-20 18:44:56 -08001319static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1320 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1321}
1322
Prabir Pradhan99987712020-11-10 18:43:05 -08001323static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(bool enabled) {
1324 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), enabled);
1325}
1326
Arthur Hungb92218b2018-08-14 12:00:21 +08001327TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001328 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001329 sp<FakeWindowHandle> window =
1330 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001331
Arthur Hung72d8dc32020-03-28 00:48:39 +00001332 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001333 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1334 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1335 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001336
1337 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001338 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001339}
1340
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001341/**
1342 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1343 * To ensure that window receives only events that were directly inside of it, add
1344 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1345 * when finding touched windows.
1346 * This test serves as a sanity check for the next test, where setInputWindows is
1347 * called twice.
1348 */
1349TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001350 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001351 sp<FakeWindowHandle> window =
1352 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1353 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001354 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001355
1356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001357 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001358 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1359 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001360 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001361
1362 // Window should receive motion event.
1363 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1364}
1365
1366/**
1367 * Calling setInputWindows twice, with the same info, should not cause any issues.
1368 * To ensure that window receives only events that were directly inside of it, add
1369 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1370 * when finding touched windows.
1371 */
1372TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001373 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001374 sp<FakeWindowHandle> window =
1375 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1376 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001377 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001378
1379 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001382 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1383 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001384 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001385
1386 // Window should receive motion event.
1387 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1388}
1389
Arthur Hungb92218b2018-08-14 12:00:21 +08001390// The foreground window should receive the first touch down event.
1391TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001392 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001393 sp<FakeWindowHandle> windowTop =
1394 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1395 sp<FakeWindowHandle> windowSecond =
1396 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001397
Arthur Hung72d8dc32020-03-28 00:48:39 +00001398 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1400 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1401 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001402
1403 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001404 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001405 windowSecond->assertNoEvents();
1406}
1407
Garfield Tandf26e862020-07-01 20:18:19 -07001408TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001409 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001410 sp<FakeWindowHandle> windowLeft =
1411 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1412 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001413 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001414 sp<FakeWindowHandle> windowRight =
1415 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1416 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001417 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001418
1419 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1420
1421 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1422
1423 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001424 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001425 injectMotionEvent(mDispatcher,
1426 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1427 AINPUT_SOURCE_MOUSE)
1428 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1429 .x(900)
1430 .y(400))
1431 .build()));
1432 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1433 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1434 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1435 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1436
1437 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001439 injectMotionEvent(mDispatcher,
1440 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1441 AINPUT_SOURCE_MOUSE)
1442 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1443 .x(300)
1444 .y(400))
1445 .build()));
1446 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1447 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1448 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1449 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1450 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1451 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1452
1453 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001455 injectMotionEvent(mDispatcher,
1456 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1457 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1458 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1459 .x(300)
1460 .y(400))
1461 .build()));
1462 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1463
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001465 injectMotionEvent(mDispatcher,
1466 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1467 AINPUT_SOURCE_MOUSE)
1468 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1469 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1470 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1471 .x(300)
1472 .y(400))
1473 .build()));
1474 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1475 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1476
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001478 injectMotionEvent(mDispatcher,
1479 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1480 AINPUT_SOURCE_MOUSE)
1481 .buttonState(0)
1482 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1483 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1484 .x(300)
1485 .y(400))
1486 .build()));
1487 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1488 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1489
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001490 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001491 injectMotionEvent(mDispatcher,
1492 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1493 .buttonState(0)
1494 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1495 .x(300)
1496 .y(400))
1497 .build()));
1498 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1499
1500 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001501 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001502 injectMotionEvent(mDispatcher,
1503 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1504 AINPUT_SOURCE_MOUSE)
1505 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1506 .x(900)
1507 .y(400))
1508 .build()));
1509 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1510 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1511 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1512 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1513 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1514 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1515}
1516
1517// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1518// directly in this test.
1519TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001520 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001521 sp<FakeWindowHandle> window =
1522 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1523 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001524 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001525
1526 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1527
1528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1529
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001530 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001531 injectMotionEvent(mDispatcher,
1532 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1533 AINPUT_SOURCE_MOUSE)
1534 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1535 .x(300)
1536 .y(400))
1537 .build()));
1538 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1539 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1540
1541 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001543 injectMotionEvent(mDispatcher,
1544 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1545 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1546 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1547 .x(300)
1548 .y(400))
1549 .build()));
1550 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
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_BUTTON_PRESS,
1555 AINPUT_SOURCE_MOUSE)
1556 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1557 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1558 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1559 .x(300)
1560 .y(400))
1561 .build()));
1562 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1563 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1564
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001565 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001566 injectMotionEvent(mDispatcher,
1567 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1568 AINPUT_SOURCE_MOUSE)
1569 .buttonState(0)
1570 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1571 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1572 .x(300)
1573 .y(400))
1574 .build()));
1575 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1576 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1577
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001579 injectMotionEvent(mDispatcher,
1580 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1581 .buttonState(0)
1582 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1583 .x(300)
1584 .y(400))
1585 .build()));
1586 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1587
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001589 injectMotionEvent(mDispatcher,
1590 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1591 AINPUT_SOURCE_MOUSE)
1592 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1593 .x(300)
1594 .y(400))
1595 .build()));
1596 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1597 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1598}
1599
Garfield Tan00f511d2019-06-12 16:55:40 -07001600TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001601 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001602
1603 sp<FakeWindowHandle> windowLeft =
1604 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1605 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001606 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001607 sp<FakeWindowHandle> windowRight =
1608 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1609 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001610 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001611
1612 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1613
Arthur Hung72d8dc32020-03-28 00:48:39 +00001614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001615
1616 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1617 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001619 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001620 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001621 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001622 windowRight->assertNoEvents();
1623}
1624
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001625TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001626 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001627 sp<FakeWindowHandle> window =
1628 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001629 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001630
Arthur Hung72d8dc32020-03-28 00:48:39 +00001631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001632 setFocusedWindow(window);
1633
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001634 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001635
1636 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1637 mDispatcher->notifyKey(&keyArgs);
1638
1639 // Window should receive key down event.
1640 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1641
1642 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1643 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001644 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001645 mDispatcher->notifyDeviceReset(&args);
1646 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1647 AKEY_EVENT_FLAG_CANCELED);
1648}
1649
1650TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001651 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001652 sp<FakeWindowHandle> window =
1653 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1654
Arthur Hung72d8dc32020-03-28 00:48:39 +00001655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001656
1657 NotifyMotionArgs motionArgs =
1658 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1659 ADISPLAY_ID_DEFAULT);
1660 mDispatcher->notifyMotion(&motionArgs);
1661
1662 // Window should receive motion down event.
1663 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1664
1665 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1666 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001667 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001668 mDispatcher->notifyDeviceReset(&args);
1669 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1670 0 /*expectedFlags*/);
1671}
1672
Svet Ganov5d3bc372020-01-26 23:11:07 -08001673TEST_F(InputDispatcherTest, TransferTouchFocus_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001674 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001675
1676 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001677 sp<FakeWindowHandle> firstWindow =
1678 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1679 sp<FakeWindowHandle> secondWindow =
1680 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001681
1682 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001684
1685 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001686 NotifyMotionArgs downMotionArgs =
1687 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1688 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001689 mDispatcher->notifyMotion(&downMotionArgs);
1690 // Only the first window should get the down event
1691 firstWindow->consumeMotionDown();
1692 secondWindow->assertNoEvents();
1693
1694 // Transfer touch focus to the second window
1695 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1696 // The first window gets cancel and the second gets down
1697 firstWindow->consumeMotionCancel();
1698 secondWindow->consumeMotionDown();
1699
1700 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001701 NotifyMotionArgs upMotionArgs =
1702 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1703 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001704 mDispatcher->notifyMotion(&upMotionArgs);
1705 // The first window gets no events and the second gets up
1706 firstWindow->assertNoEvents();
1707 secondWindow->consumeMotionUp();
1708}
1709
1710TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointerNoSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001711 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001712
1713 PointF touchPoint = {10, 10};
1714
1715 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001716 sp<FakeWindowHandle> firstWindow =
1717 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1718 sp<FakeWindowHandle> secondWindow =
1719 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001720
1721 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001723
1724 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001725 NotifyMotionArgs downMotionArgs =
1726 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1727 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001728 mDispatcher->notifyMotion(&downMotionArgs);
1729 // Only the first window should get the down event
1730 firstWindow->consumeMotionDown();
1731 secondWindow->assertNoEvents();
1732
1733 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001734 NotifyMotionArgs pointerDownMotionArgs =
1735 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1736 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1737 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1738 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001739 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1740 // Only the first window should get the pointer down event
1741 firstWindow->consumeMotionPointerDown(1);
1742 secondWindow->assertNoEvents();
1743
1744 // Transfer touch focus to the second window
1745 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1746 // The first window gets cancel and the second gets down and pointer down
1747 firstWindow->consumeMotionCancel();
1748 secondWindow->consumeMotionDown();
1749 secondWindow->consumeMotionPointerDown(1);
1750
1751 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001752 NotifyMotionArgs pointerUpMotionArgs =
1753 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1754 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1755 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1756 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001757 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1758 // The first window gets nothing and the second gets pointer up
1759 firstWindow->assertNoEvents();
1760 secondWindow->consumeMotionPointerUp(1);
1761
1762 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001763 NotifyMotionArgs upMotionArgs =
1764 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1765 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001766 mDispatcher->notifyMotion(&upMotionArgs);
1767 // The first window gets nothing and the second gets up
1768 firstWindow->assertNoEvents();
1769 secondWindow->consumeMotionUp();
1770}
1771
1772TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001773 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001774
1775 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001776 sp<FakeWindowHandle> firstWindow =
1777 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001778 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001779 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1780 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001781
1782 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001783 sp<FakeWindowHandle> secondWindow =
1784 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001785 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001786 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1787 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001788
1789 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001790 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001791
1792 PointF pointInFirst = {300, 200};
1793 PointF pointInSecond = {300, 600};
1794
1795 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001796 NotifyMotionArgs firstDownMotionArgs =
1797 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1798 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001799 mDispatcher->notifyMotion(&firstDownMotionArgs);
1800 // Only the first window should get the down event
1801 firstWindow->consumeMotionDown();
1802 secondWindow->assertNoEvents();
1803
1804 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001805 NotifyMotionArgs secondDownMotionArgs =
1806 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1807 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1808 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1809 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001810 mDispatcher->notifyMotion(&secondDownMotionArgs);
1811 // The first window gets a move and the second a down
1812 firstWindow->consumeMotionMove();
1813 secondWindow->consumeMotionDown();
1814
1815 // Transfer touch focus to the second window
1816 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1817 // The first window gets cancel and the new gets pointer down (it already saw down)
1818 firstWindow->consumeMotionCancel();
1819 secondWindow->consumeMotionPointerDown(1);
1820
1821 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001822 NotifyMotionArgs pointerUpMotionArgs =
1823 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1824 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1825 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1826 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001827 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1828 // The first window gets nothing and the second gets pointer up
1829 firstWindow->assertNoEvents();
1830 secondWindow->consumeMotionPointerUp(1);
1831
1832 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001833 NotifyMotionArgs upMotionArgs =
1834 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1835 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001836 mDispatcher->notifyMotion(&upMotionArgs);
1837 // The first window gets nothing and the second gets up
1838 firstWindow->assertNoEvents();
1839 secondWindow->consumeMotionUp();
1840}
1841
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001842TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001843 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001844 sp<FakeWindowHandle> window =
1845 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1846
Vishnu Nair47074b82020-08-14 11:54:47 -07001847 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001849 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001850
1851 window->consumeFocusEvent(true);
1852
1853 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1854 mDispatcher->notifyKey(&keyArgs);
1855
1856 // Window should receive key down event.
1857 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1858}
1859
1860TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001861 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001862 sp<FakeWindowHandle> window =
1863 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1864
Arthur Hung72d8dc32020-03-28 00:48:39 +00001865 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001866
1867 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1868 mDispatcher->notifyKey(&keyArgs);
1869 mDispatcher->waitForIdle();
1870
1871 window->assertNoEvents();
1872}
1873
1874// If a window is touchable, but does not have focus, it should receive motion events, but not keys
1875TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07001876 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001877 sp<FakeWindowHandle> window =
1878 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1879
Arthur Hung72d8dc32020-03-28 00:48:39 +00001880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001881
1882 // Send key
1883 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1884 mDispatcher->notifyKey(&keyArgs);
1885 // Send motion
1886 NotifyMotionArgs motionArgs =
1887 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1888 ADISPLAY_ID_DEFAULT);
1889 mDispatcher->notifyMotion(&motionArgs);
1890
1891 // Window should receive only the motion event
1892 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1893 window->assertNoEvents(); // Key event or focus event will not be received
1894}
1895
arthurhungea3f4fc2020-12-21 23:18:53 +08001896TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
1897 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1898
1899 // Create first non touch modal window that supports split touch
1900 sp<FakeWindowHandle> firstWindow =
1901 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1902 firstWindow->setFrame(Rect(0, 0, 600, 400));
1903 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1904 InputWindowInfo::Flag::SPLIT_TOUCH);
1905
1906 // Create second non touch modal window that supports split touch
1907 sp<FakeWindowHandle> secondWindow =
1908 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1909 secondWindow->setFrame(Rect(0, 400, 600, 800));
1910 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1911 InputWindowInfo::Flag::SPLIT_TOUCH);
1912
1913 // Add the windows to the dispatcher
1914 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1915
1916 PointF pointInFirst = {300, 200};
1917 PointF pointInSecond = {300, 600};
1918
1919 // Send down to the first window
1920 NotifyMotionArgs firstDownMotionArgs =
1921 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1922 ADISPLAY_ID_DEFAULT, {pointInFirst});
1923 mDispatcher->notifyMotion(&firstDownMotionArgs);
1924 // Only the first window should get the down event
1925 firstWindow->consumeMotionDown();
1926 secondWindow->assertNoEvents();
1927
1928 // Send down to the second window
1929 NotifyMotionArgs secondDownMotionArgs =
1930 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1931 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1932 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1933 {pointInFirst, pointInSecond});
1934 mDispatcher->notifyMotion(&secondDownMotionArgs);
1935 // The first window gets a move and the second a down
1936 firstWindow->consumeMotionMove();
1937 secondWindow->consumeMotionDown();
1938
1939 // Send pointer cancel to the second window
1940 NotifyMotionArgs pointerUpMotionArgs =
1941 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1942 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1943 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1944 {pointInFirst, pointInSecond});
1945 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
1946 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1947 // The first window gets move and the second gets cancel.
1948 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
1949 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
1950
1951 // Send up event.
1952 NotifyMotionArgs upMotionArgs =
1953 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1954 ADISPLAY_ID_DEFAULT);
1955 mDispatcher->notifyMotion(&upMotionArgs);
1956 // The first window gets up and the second gets nothing.
1957 firstWindow->consumeMotionUp();
1958 secondWindow->assertNoEvents();
1959}
1960
chaviwd1c23182019-12-20 18:44:56 -08001961class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00001962public:
1963 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08001964 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07001965 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00001966 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07001967 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00001968 }
1969
chaviwd1c23182019-12-20 18:44:56 -08001970 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
1971
1972 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1973 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
1974 expectedDisplayId, expectedFlags);
1975 }
1976
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001977 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
1978
1979 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
1980
chaviwd1c23182019-12-20 18:44:56 -08001981 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1982 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
1983 expectedDisplayId, expectedFlags);
1984 }
1985
1986 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1987 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
1988 expectedDisplayId, expectedFlags);
1989 }
1990
1991 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
1992
1993private:
1994 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00001995};
1996
1997// Tests for gesture monitors
1998TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07001999 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002000 sp<FakeWindowHandle> window =
2001 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002003
chaviwd1c23182019-12-20 18:44:56 -08002004 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2005 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002006
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002008 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002009 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002010 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002011 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002012}
2013
2014TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002015 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002016 sp<FakeWindowHandle> window =
2017 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2018
2019 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002020 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002021
Arthur Hung72d8dc32020-03-28 00:48:39 +00002022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002023 setFocusedWindow(window);
2024
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002025 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002026
chaviwd1c23182019-12-20 18:44:56 -08002027 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2028 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002029
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002030 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2031 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002032 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002033 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002034}
2035
2036TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002037 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002038 sp<FakeWindowHandle> window =
2039 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002041
chaviwd1c23182019-12-20 18:44:56 -08002042 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2043 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002044
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002046 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002047 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002048 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002049 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002050
2051 window->releaseChannel();
2052
chaviwd1c23182019-12-20 18:44:56 -08002053 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002054
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002056 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002058 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002059}
2060
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002061TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2062 FakeMonitorReceiver monitor =
2063 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2064 true /*isGestureMonitor*/);
2065
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002067 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2068 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2069 ASSERT_TRUE(consumeSeq);
2070
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002071 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002072 monitor.finishEvent(*consumeSeq);
2073 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002074 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002075}
2076
chaviw81e2bb92019-12-18 15:03:51 -08002077TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002078 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002079 sp<FakeWindowHandle> window =
2080 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2081
Arthur Hung72d8dc32020-03-28 00:48:39 +00002082 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002083
2084 NotifyMotionArgs motionArgs =
2085 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2086 ADISPLAY_ID_DEFAULT);
2087
2088 mDispatcher->notifyMotion(&motionArgs);
2089 // Window should receive motion down event.
2090 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2091
2092 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002093 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002094 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2095 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2096 motionArgs.pointerCoords[0].getX() - 10);
2097
2098 mDispatcher->notifyMotion(&motionArgs);
2099 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2100 0 /*expectedFlags*/);
2101}
2102
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002103/**
2104 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2105 * the device default right away. In the test scenario, we check both the default value,
2106 * and the action of enabling / disabling.
2107 */
2108TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002109 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002110 sp<FakeWindowHandle> window =
2111 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2112
2113 // Set focused application.
2114 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002115 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002116
2117 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002119 setFocusedWindow(window);
2120
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002121 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2122
2123 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002124 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002126 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2127
2128 SCOPED_TRACE("Disable touch mode");
2129 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002130 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002131 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002132 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002133 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2134
2135 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002136 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002138 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2139
2140 SCOPED_TRACE("Enable touch mode again");
2141 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002142 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002144 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002145 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2146
2147 window->assertNoEvents();
2148}
2149
Gang Wange9087892020-01-07 12:17:14 -05002150TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002151 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002152 sp<FakeWindowHandle> window =
2153 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2154
2155 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002156 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002157
Arthur Hung72d8dc32020-03-28 00:48:39 +00002158 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002159 setFocusedWindow(window);
2160
Gang Wange9087892020-01-07 12:17:14 -05002161 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2162
2163 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2164 mDispatcher->notifyKey(&keyArgs);
2165
2166 InputEvent* event = window->consume();
2167 ASSERT_NE(event, nullptr);
2168
2169 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2170 ASSERT_NE(verified, nullptr);
2171 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2172
2173 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2174 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2175 ASSERT_EQ(keyArgs.source, verified->source);
2176 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2177
2178 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2179
2180 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2181 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002182 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2183 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2184 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2185 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2186 ASSERT_EQ(0, verifiedKey.repeatCount);
2187}
2188
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002189TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002190 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002191 sp<FakeWindowHandle> window =
2192 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2193
2194 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2195
Arthur Hung72d8dc32020-03-28 00:48:39 +00002196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002197
2198 NotifyMotionArgs motionArgs =
2199 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2200 ADISPLAY_ID_DEFAULT);
2201 mDispatcher->notifyMotion(&motionArgs);
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::MOTION);
2209
2210 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2211 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2212 EXPECT_EQ(motionArgs.source, verified->source);
2213 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2214
2215 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2216
2217 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2218 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2219 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2220 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2221 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2222 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2223 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2224}
2225
Prabir Pradhanbd527712021-03-09 19:17:09 -08002226TEST_F(InputDispatcherTest, NonPointerMotionEvent_NotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002227 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2228 sp<FakeWindowHandle> window =
2229 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2230 const std::string name = window->getName();
2231
2232 // Window gets transformed by offset values.
2233 window->setWindowOffset(500.0f, 500.0f);
2234
2235 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2236 window->setFocusable(true);
2237
2238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2239
2240 // First, we set focused window so that focusedWindowHandle is not null.
2241 setFocusedWindow(window);
2242
2243 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2244 window->consumeFocusEvent(true);
2245
Prabir Pradhanbd527712021-03-09 19:17:09 -08002246 constexpr const std::array nonPointerSources = {AINPUT_SOURCE_TRACKBALL,
2247 AINPUT_SOURCE_MOUSE_RELATIVE,
2248 AINPUT_SOURCE_JOYSTICK};
2249 for (const int source : nonPointerSources) {
2250 // Notify motion with a non-pointer source.
2251 NotifyMotionArgs motionArgs =
2252 generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, source, ADISPLAY_ID_DEFAULT);
2253 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09002254
Prabir Pradhanbd527712021-03-09 19:17:09 -08002255 InputEvent* event = window->consume();
2256 ASSERT_NE(event, nullptr);
2257 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2258 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2259 << " event, got " << inputEventTypeToString(event->getType()) << " event";
yunho.shinf4a80b82020-11-16 21:13:57 +09002260
Prabir Pradhanbd527712021-03-09 19:17:09 -08002261 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2262 EXPECT_EQ(AMOTION_EVENT_ACTION_MOVE, motionEvent.getAction());
2263 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09002264
Prabir Pradhanbd527712021-03-09 19:17:09 -08002265 float expectedX = motionArgs.pointerCoords[0].getX();
2266 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09002267
Prabir Pradhanbd527712021-03-09 19:17:09 -08002268 // Ensure the axis values from the final motion event are not transformed.
2269 EXPECT_EQ(expectedX, motionEvent.getX(0))
2270 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2271 << motionEvent.getX(0);
2272 EXPECT_EQ(expectedY, motionEvent.getY(0))
2273 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2274 << motionEvent.getY(0);
2275 // Ensure the raw and transformed axis values for the motion event are the same.
2276 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2277 << "expected raw and transformed X-axis values to be equal";
2278 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2279 << "expected raw and transformed Y-axis values to be equal";
2280 }
yunho.shinf4a80b82020-11-16 21:13:57 +09002281}
2282
chaviw09c8d2d2020-08-24 15:48:26 -07002283/**
2284 * Ensure that separate calls to sign the same data are generating the same key.
2285 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2286 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2287 * tests.
2288 */
2289TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2290 KeyEvent event = getTestKeyEvent();
2291 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2292
2293 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2294 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2295 ASSERT_EQ(hmac1, hmac2);
2296}
2297
2298/**
2299 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2300 */
2301TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2302 KeyEvent event = getTestKeyEvent();
2303 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2304 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2305
2306 verifiedEvent.deviceId += 1;
2307 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2308
2309 verifiedEvent.source += 1;
2310 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2311
2312 verifiedEvent.eventTimeNanos += 1;
2313 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2314
2315 verifiedEvent.displayId += 1;
2316 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2317
2318 verifiedEvent.action += 1;
2319 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2320
2321 verifiedEvent.downTimeNanos += 1;
2322 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2323
2324 verifiedEvent.flags += 1;
2325 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2326
2327 verifiedEvent.keyCode += 1;
2328 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2329
2330 verifiedEvent.scanCode += 1;
2331 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2332
2333 verifiedEvent.metaState += 1;
2334 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2335
2336 verifiedEvent.repeatCount += 1;
2337 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2338}
2339
Vishnu Nair958da932020-08-21 17:12:37 -07002340TEST_F(InputDispatcherTest, SetFocusedWindow) {
2341 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2342 sp<FakeWindowHandle> windowTop =
2343 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2344 sp<FakeWindowHandle> windowSecond =
2345 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2346 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2347
2348 // Top window is also focusable but is not granted focus.
2349 windowTop->setFocusable(true);
2350 windowSecond->setFocusable(true);
2351 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2352 setFocusedWindow(windowSecond);
2353
2354 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2356 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002357
2358 // Focused window should receive event.
2359 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2360 windowTop->assertNoEvents();
2361}
2362
2363TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2364 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2365 sp<FakeWindowHandle> window =
2366 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2367 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2368
2369 window->setFocusable(true);
2370 // Release channel for window is no longer valid.
2371 window->releaseChannel();
2372 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2373 setFocusedWindow(window);
2374
2375 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002376 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2377 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002378
2379 // window channel is invalid, so it should not receive any input event.
2380 window->assertNoEvents();
2381}
2382
2383TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2384 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2385 sp<FakeWindowHandle> window =
2386 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2387 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2388
2389 // Window is not focusable.
2390 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2391 setFocusedWindow(window);
2392
2393 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002394 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2395 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002396
2397 // window is invalid, so it should not receive any input event.
2398 window->assertNoEvents();
2399}
2400
2401TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2402 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2403 sp<FakeWindowHandle> windowTop =
2404 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2405 sp<FakeWindowHandle> windowSecond =
2406 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2407 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2408
2409 windowTop->setFocusable(true);
2410 windowSecond->setFocusable(true);
2411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2412 setFocusedWindow(windowTop);
2413 windowTop->consumeFocusEvent(true);
2414
2415 setFocusedWindow(windowSecond, windowTop);
2416 windowSecond->consumeFocusEvent(true);
2417 windowTop->consumeFocusEvent(false);
2418
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2420 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002421
2422 // Focused window should receive event.
2423 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2424}
2425
2426TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2427 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2428 sp<FakeWindowHandle> windowTop =
2429 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2430 sp<FakeWindowHandle> windowSecond =
2431 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2432 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2433
2434 windowTop->setFocusable(true);
2435 windowSecond->setFocusable(true);
2436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2437 setFocusedWindow(windowSecond, windowTop);
2438
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002439 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2440 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002441
2442 // Event should be dropped.
2443 windowTop->assertNoEvents();
2444 windowSecond->assertNoEvents();
2445}
2446
2447TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2448 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2449 sp<FakeWindowHandle> window =
2450 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2451 sp<FakeWindowHandle> previousFocusedWindow =
2452 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2453 ADISPLAY_ID_DEFAULT);
2454 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2455
2456 window->setFocusable(true);
2457 previousFocusedWindow->setFocusable(true);
2458 window->setVisible(false);
2459 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2460 setFocusedWindow(previousFocusedWindow);
2461 previousFocusedWindow->consumeFocusEvent(true);
2462
2463 // Requesting focus on invisible window takes focus from currently focused window.
2464 setFocusedWindow(window);
2465 previousFocusedWindow->consumeFocusEvent(false);
2466
2467 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002469 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002470 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002471
2472 // Window does not get focus event or key down.
2473 window->assertNoEvents();
2474
2475 // Window becomes visible.
2476 window->setVisible(true);
2477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2478
2479 // Window receives focus event.
2480 window->consumeFocusEvent(true);
2481 // Focused window receives key down.
2482 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2483}
2484
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002485/**
2486 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2487 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2488 * of the 'slipperyEnterWindow'.
2489 *
2490 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2491 * a way so that the touched location is no longer covered by the top window.
2492 *
2493 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2494 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2495 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2496 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2497 * with ACTION_DOWN).
2498 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2499 * window moved itself away from the touched location and had Flag::SLIPPERY.
2500 *
2501 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2502 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2503 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2504 *
2505 * In this test, we ensure that the event received by the bottom window has
2506 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2507 */
2508TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2509 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2510 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2511
2512 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2513 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2514
2515 sp<FakeWindowHandle> slipperyExitWindow =
2516 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2517 slipperyExitWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2518 InputWindowInfo::Flag::SLIPPERY);
2519 // Make sure this one overlaps the bottom window
2520 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2521 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2522 // one. Windows with the same owner are not considered to be occluding each other.
2523 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2524
2525 sp<FakeWindowHandle> slipperyEnterWindow =
2526 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2527 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2528
2529 mDispatcher->setInputWindows(
2530 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2531
2532 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2533 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2534 ADISPLAY_ID_DEFAULT, {{50, 50}});
2535 mDispatcher->notifyMotion(&args);
2536 slipperyExitWindow->consumeMotionDown();
2537 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2538 mDispatcher->setInputWindows(
2539 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2540
2541 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2542 ADISPLAY_ID_DEFAULT, {{51, 51}});
2543 mDispatcher->notifyMotion(&args);
2544
2545 slipperyExitWindow->consumeMotionCancel();
2546
2547 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2548 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2549}
2550
Garfield Tan1c7bc862020-01-28 13:24:04 -08002551class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2552protected:
2553 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2554 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2555
Chris Yea209fde2020-07-22 13:54:51 -07002556 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002557 sp<FakeWindowHandle> mWindow;
2558
2559 virtual void SetUp() override {
2560 mFakePolicy = new FakeInputDispatcherPolicy();
2561 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2562 mDispatcher = new InputDispatcher(mFakePolicy);
2563 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2564 ASSERT_EQ(OK, mDispatcher->start());
2565
2566 setUpWindow();
2567 }
2568
2569 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002570 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002571 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2572
Vishnu Nair47074b82020-08-14 11:54:47 -07002573 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002575 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002576 mWindow->consumeFocusEvent(true);
2577 }
2578
Chris Ye2ad95392020-09-01 13:44:44 -07002579 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002580 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002581 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002582 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2583 mDispatcher->notifyKey(&keyArgs);
2584
2585 // Window should receive key down event.
2586 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2587 }
2588
2589 void expectKeyRepeatOnce(int32_t repeatCount) {
2590 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2591 InputEvent* repeatEvent = mWindow->consume();
2592 ASSERT_NE(nullptr, repeatEvent);
2593
2594 uint32_t eventType = repeatEvent->getType();
2595 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2596
2597 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2598 uint32_t eventAction = repeatKeyEvent->getAction();
2599 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2600 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2601 }
2602
Chris Ye2ad95392020-09-01 13:44:44 -07002603 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002604 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002605 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002606 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2607 mDispatcher->notifyKey(&keyArgs);
2608
2609 // Window should receive key down event.
2610 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2611 0 /*expectedFlags*/);
2612 }
2613};
2614
2615TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002616 sendAndConsumeKeyDown(1 /* deviceId */);
2617 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2618 expectKeyRepeatOnce(repeatCount);
2619 }
2620}
2621
2622TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2623 sendAndConsumeKeyDown(1 /* deviceId */);
2624 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2625 expectKeyRepeatOnce(repeatCount);
2626 }
2627 sendAndConsumeKeyDown(2 /* deviceId */);
2628 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002629 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2630 expectKeyRepeatOnce(repeatCount);
2631 }
2632}
2633
2634TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002635 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002636 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002637 sendAndConsumeKeyUp(1 /* deviceId */);
2638 mWindow->assertNoEvents();
2639}
2640
2641TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2642 sendAndConsumeKeyDown(1 /* deviceId */);
2643 expectKeyRepeatOnce(1 /*repeatCount*/);
2644 sendAndConsumeKeyDown(2 /* deviceId */);
2645 expectKeyRepeatOnce(1 /*repeatCount*/);
2646 // Stale key up from device 1.
2647 sendAndConsumeKeyUp(1 /* deviceId */);
2648 // Device 2 is still down, keep repeating
2649 expectKeyRepeatOnce(2 /*repeatCount*/);
2650 expectKeyRepeatOnce(3 /*repeatCount*/);
2651 // Device 2 key up
2652 sendAndConsumeKeyUp(2 /* deviceId */);
2653 mWindow->assertNoEvents();
2654}
2655
2656TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2657 sendAndConsumeKeyDown(1 /* deviceId */);
2658 expectKeyRepeatOnce(1 /*repeatCount*/);
2659 sendAndConsumeKeyDown(2 /* deviceId */);
2660 expectKeyRepeatOnce(1 /*repeatCount*/);
2661 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2662 sendAndConsumeKeyUp(2 /* deviceId */);
2663 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002664 mWindow->assertNoEvents();
2665}
2666
2667TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002668 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002669 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2670 InputEvent* repeatEvent = mWindow->consume();
2671 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2672 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2673 IdGenerator::getSource(repeatEvent->getId()));
2674 }
2675}
2676
2677TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002678 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002679
2680 std::unordered_set<int32_t> idSet;
2681 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2682 InputEvent* repeatEvent = mWindow->consume();
2683 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2684 int32_t id = repeatEvent->getId();
2685 EXPECT_EQ(idSet.end(), idSet.find(id));
2686 idSet.insert(id);
2687 }
2688}
2689
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002690/* Test InputDispatcher for MultiDisplay */
2691class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2692public:
2693 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002694 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002695 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002696
Chris Yea209fde2020-07-22 13:54:51 -07002697 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002698 windowInPrimary =
2699 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002700
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002701 // Set focus window for primary display, but focused display would be second one.
2702 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002703 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002705 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002706 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002707
Chris Yea209fde2020-07-22 13:54:51 -07002708 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002709 windowInSecondary =
2710 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002711 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002712 // Set focus display to second one.
2713 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2714 // Set focus window for second display.
2715 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002716 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002717 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002718 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002719 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002720 }
2721
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002722 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002723 InputDispatcherTest::TearDown();
2724
Chris Yea209fde2020-07-22 13:54:51 -07002725 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002726 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002727 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002728 windowInSecondary.clear();
2729 }
2730
2731protected:
Chris Yea209fde2020-07-22 13:54:51 -07002732 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002733 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002734 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002735 sp<FakeWindowHandle> windowInSecondary;
2736};
2737
2738TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2739 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002740 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2741 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2742 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002743 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002744 windowInSecondary->assertNoEvents();
2745
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002746 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002747 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2748 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2749 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002750 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002751 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002752}
2753
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002754TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002755 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2757 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002758 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002759 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002760 windowInSecondary->assertNoEvents();
2761
2762 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002763 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002764 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002765 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002766 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002767
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002768 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002769 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002770
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002771 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002772 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2773 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002774
2775 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002776 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002777 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08002778 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002779 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002780 windowInSecondary->assertNoEvents();
2781}
2782
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002783// Test per-display input monitors for motion event.
2784TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002785 FakeMonitorReceiver monitorInPrimary =
2786 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2787 FakeMonitorReceiver monitorInSecondary =
2788 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002789
2790 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2792 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2793 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002794 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002795 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002796 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002797 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002798
2799 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002800 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2801 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2802 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002803 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002804 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002805 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08002806 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002807
2808 // Test inject a non-pointer motion event.
2809 // If specific a display, it will dispatch to the focused window of particular display,
2810 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2812 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
2813 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002814 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002815 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002816 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002817 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002818}
2819
2820// Test per-display input monitors for key event.
2821TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002822 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08002823 FakeMonitorReceiver monitorInPrimary =
2824 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2825 FakeMonitorReceiver monitorInSecondary =
2826 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002827
2828 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2830 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002831 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08002832 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002833 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08002834 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002835}
2836
Vishnu Nair958da932020-08-21 17:12:37 -07002837TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
2838 sp<FakeWindowHandle> secondWindowInPrimary =
2839 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2840 secondWindowInPrimary->setFocusable(true);
2841 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
2842 setFocusedWindow(secondWindowInPrimary);
2843 windowInPrimary->consumeFocusEvent(false);
2844 secondWindowInPrimary->consumeFocusEvent(true);
2845
2846 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002847 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2848 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002849 windowInPrimary->assertNoEvents();
2850 windowInSecondary->assertNoEvents();
2851 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2852}
2853
Jackal Guof9696682018-10-05 12:23:23 +08002854class InputFilterTest : public InputDispatcherTest {
2855protected:
2856 static constexpr int32_t SECOND_DISPLAY_ID = 1;
2857
2858 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
2859 NotifyMotionArgs motionArgs;
2860
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002861 motionArgs =
2862 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08002863 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002864 motionArgs =
2865 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08002866 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002867 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002868 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002869 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002870 } else {
2871 mFakePolicy->assertFilterInputEventWasNotCalled();
2872 }
2873 }
2874
2875 void testNotifyKey(bool expectToBeFiltered) {
2876 NotifyKeyArgs keyArgs;
2877
2878 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2879 mDispatcher->notifyKey(&keyArgs);
2880 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
2881 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002882 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08002883
2884 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08002885 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08002886 } else {
2887 mFakePolicy->assertFilterInputEventWasNotCalled();
2888 }
2889 }
2890};
2891
2892// Test InputFilter for MotionEvent
2893TEST_F(InputFilterTest, MotionEvent_InputFilter) {
2894 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
2895 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2896 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2897
2898 // Enable InputFilter
2899 mDispatcher->setInputFilterEnabled(true);
2900 // Test touch on both primary and second display, and check if both events are filtered.
2901 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
2902 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
2903
2904 // Disable InputFilter
2905 mDispatcher->setInputFilterEnabled(false);
2906 // Test touch on both primary and second display, and check if both events aren't filtered.
2907 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
2908 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
2909}
2910
2911// Test InputFilter for KeyEvent
2912TEST_F(InputFilterTest, KeyEvent_InputFilter) {
2913 // Since the InputFilter is disabled by default, check if key event aren't filtered.
2914 testNotifyKey(/*expectToBeFiltered*/ false);
2915
2916 // Enable InputFilter
2917 mDispatcher->setInputFilterEnabled(true);
2918 // Send a key event, and check if it is filtered.
2919 testNotifyKey(/*expectToBeFiltered*/ true);
2920
2921 // Disable InputFilter
2922 mDispatcher->setInputFilterEnabled(false);
2923 // Send a key event, and check if it isn't filtered.
2924 testNotifyKey(/*expectToBeFiltered*/ false);
2925}
2926
chaviwfd6d3512019-03-25 13:23:49 -07002927class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002928 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07002929 InputDispatcherTest::SetUp();
2930
Chris Yea209fde2020-07-22 13:54:51 -07002931 std::shared_ptr<FakeApplicationHandle> application =
2932 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002933 mUnfocusedWindow =
2934 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07002935 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
2936 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
2937 // window.
Michael Wright44753b12020-07-08 13:48:11 +01002938 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002939
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002940 mFocusedWindow =
2941 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2942 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01002943 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07002944
2945 // Set focused application.
2946 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002947 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07002948
2949 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002950 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002951 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002952 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07002953 }
2954
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002955 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07002956 InputDispatcherTest::TearDown();
2957
2958 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002959 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07002960 }
2961
2962protected:
2963 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002964 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002965 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07002966};
2967
2968// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
2969// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
2970// the onPointerDownOutsideFocus callback.
2971TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002973 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2974 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002975 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002976 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002977
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002978 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07002979 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
2980}
2981
2982// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
2983// DOWN on the window that doesn't have focus. Ensure no window received the
2984// onPointerDownOutsideFocus callback.
2985TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002986 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07002987 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002988 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07002989 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07002990
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002991 ASSERT_TRUE(mDispatcher->waitForIdle());
2992 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07002993}
2994
2995// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
2996// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
2997TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2999 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003000 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003001 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003002
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003003 ASSERT_TRUE(mDispatcher->waitForIdle());
3004 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003005}
3006
3007// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3008// DOWN on the window that already has focus. Ensure no window received the
3009// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003010TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003012 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003013 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003014 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003015 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003016
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003017 ASSERT_TRUE(mDispatcher->waitForIdle());
3018 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003019}
3020
chaviwaf87b3e2019-10-01 16:59:28 -07003021// These tests ensures we can send touch events to a single client when there are multiple input
3022// windows that point to the same client token.
3023class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3024 virtual void SetUp() override {
3025 InputDispatcherTest::SetUp();
3026
Chris Yea209fde2020-07-22 13:54:51 -07003027 std::shared_ptr<FakeApplicationHandle> application =
3028 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003029 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3030 ADISPLAY_ID_DEFAULT);
3031 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3032 // 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 +01003033 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3034 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003035 mWindow1->setFrame(Rect(0, 0, 100, 100));
3036
3037 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3038 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01003039 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3040 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003041 mWindow2->setFrame(Rect(100, 100, 200, 200));
3042
Arthur Hung72d8dc32020-03-28 00:48:39 +00003043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003044 }
3045
3046protected:
3047 sp<FakeWindowHandle> mWindow1;
3048 sp<FakeWindowHandle> mWindow2;
3049
3050 // Helper function to convert the point from screen coordinates into the window's space
3051 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003052 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3053 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003054 }
3055
3056 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3057 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003058 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003059 InputEvent* event = window->consume();
3060
3061 ASSERT_NE(nullptr, event) << name.c_str()
3062 << ": consumer should have returned non-NULL event.";
3063
3064 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3065 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3066 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3067
3068 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3069 EXPECT_EQ(expectedAction, motionEvent.getAction());
3070
3071 for (size_t i = 0; i < points.size(); i++) {
3072 float expectedX = points[i].x;
3073 float expectedY = points[i].y;
3074
3075 EXPECT_EQ(expectedX, motionEvent.getX(i))
3076 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3077 << ", got " << motionEvent.getX(i);
3078 EXPECT_EQ(expectedY, motionEvent.getY(i))
3079 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3080 << ", got " << motionEvent.getY(i);
3081 }
3082 }
chaviw9eaa22c2020-07-01 16:21:27 -07003083
3084 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3085 std::vector<PointF> expectedPoints) {
3086 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3087 ADISPLAY_ID_DEFAULT, touchedPoints);
3088 mDispatcher->notifyMotion(&motionArgs);
3089
3090 // Always consume from window1 since it's the window that has the InputReceiver
3091 consumeMotionEvent(mWindow1, action, expectedPoints);
3092 }
chaviwaf87b3e2019-10-01 16:59:28 -07003093};
3094
3095TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3096 // Touch Window 1
3097 PointF touchedPoint = {10, 10};
3098 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003099 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003100
3101 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003102 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003103
3104 // Touch Window 2
3105 touchedPoint = {150, 150};
3106 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003107 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003108}
3109
chaviw9eaa22c2020-07-01 16:21:27 -07003110TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3111 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003112 mWindow2->setWindowScale(0.5f, 0.5f);
3113
3114 // Touch Window 1
3115 PointF touchedPoint = {10, 10};
3116 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003117 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003118 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003119 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003120
3121 // Touch Window 2
3122 touchedPoint = {150, 150};
3123 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003124 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3125 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003126
chaviw9eaa22c2020-07-01 16:21:27 -07003127 // Update the transform so rotation is set
3128 mWindow2->setWindowTransform(0, -1, 1, 0);
3129 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3130 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003131}
3132
chaviw9eaa22c2020-07-01 16:21:27 -07003133TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003134 mWindow2->setWindowScale(0.5f, 0.5f);
3135
3136 // Touch Window 1
3137 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3138 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003139 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003140
3141 // Touch Window 2
3142 int32_t actionPointerDown =
3143 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003144 touchedPoints.push_back(PointF{150, 150});
3145 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3146 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003147
chaviw9eaa22c2020-07-01 16:21:27 -07003148 // Release Window 2
3149 int32_t actionPointerUp =
3150 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3151 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3152 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003153
chaviw9eaa22c2020-07-01 16:21:27 -07003154 // Update the transform so rotation is set for Window 2
3155 mWindow2->setWindowTransform(0, -1, 1, 0);
3156 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3157 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003158}
3159
chaviw9eaa22c2020-07-01 16:21:27 -07003160TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003161 mWindow2->setWindowScale(0.5f, 0.5f);
3162
3163 // Touch Window 1
3164 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3165 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003166 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003167
3168 // Touch Window 2
3169 int32_t actionPointerDown =
3170 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003171 touchedPoints.push_back(PointF{150, 150});
3172 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003173
chaviw9eaa22c2020-07-01 16:21:27 -07003174 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003175
3176 // Move both windows
3177 touchedPoints = {{20, 20}, {175, 175}};
3178 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3179 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3180
chaviw9eaa22c2020-07-01 16:21:27 -07003181 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003182
chaviw9eaa22c2020-07-01 16:21:27 -07003183 // Release Window 2
3184 int32_t actionPointerUp =
3185 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3186 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3187 expectedPoints.pop_back();
3188
3189 // Touch Window 2
3190 mWindow2->setWindowTransform(0, -1, 1, 0);
3191 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3192 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3193
3194 // Move both windows
3195 touchedPoints = {{20, 20}, {175, 175}};
3196 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3197 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3198
3199 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003200}
3201
3202TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3203 mWindow1->setWindowScale(0.5f, 0.5f);
3204
3205 // Touch Window 1
3206 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3207 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003208 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003209
3210 // Touch Window 2
3211 int32_t actionPointerDown =
3212 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003213 touchedPoints.push_back(PointF{150, 150});
3214 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003215
chaviw9eaa22c2020-07-01 16:21:27 -07003216 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003217
3218 // Move both windows
3219 touchedPoints = {{20, 20}, {175, 175}};
3220 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3221 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3222
chaviw9eaa22c2020-07-01 16:21:27 -07003223 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003224}
3225
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003226class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3227 virtual void SetUp() override {
3228 InputDispatcherTest::SetUp();
3229
Chris Yea209fde2020-07-22 13:54:51 -07003230 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003231 mApplication->setDispatchingTimeout(20ms);
3232 mWindow =
3233 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3234 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003235 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003236 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003237 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3238 // window.
Michael Wright44753b12020-07-08 13:48:11 +01003239 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003240
3241 // Set focused application.
3242 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3243
3244 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003245 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003246 mWindow->consumeFocusEvent(true);
3247 }
3248
3249 virtual void TearDown() override {
3250 InputDispatcherTest::TearDown();
3251 mWindow.clear();
3252 }
3253
3254protected:
Chris Yea209fde2020-07-22 13:54:51 -07003255 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003256 sp<FakeWindowHandle> mWindow;
3257 static constexpr PointF WINDOW_LOCATION = {20, 20};
3258
3259 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003261 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3262 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003263 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003264 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3265 WINDOW_LOCATION));
3266 }
3267};
3268
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003269// Send a tap and respond, which should not cause an ANR.
3270TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3271 tapOnWindow();
3272 mWindow->consumeMotionDown();
3273 mWindow->consumeMotionUp();
3274 ASSERT_TRUE(mDispatcher->waitForIdle());
3275 mFakePolicy->assertNotifyAnrWasNotCalled();
3276}
3277
3278// Send a regular key and respond, which should not cause an ANR.
3279TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003280 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003281 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3282 ASSERT_TRUE(mDispatcher->waitForIdle());
3283 mFakePolicy->assertNotifyAnrWasNotCalled();
3284}
3285
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003286TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3287 mWindow->setFocusable(false);
3288 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3289 mWindow->consumeFocusEvent(false);
3290
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003291 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003292 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003293 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3294 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003295 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003296 // Key will not go to window because we have no focused window.
3297 // The 'no focused window' ANR timer should start instead.
3298
3299 // Now, the focused application goes away.
3300 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3301 // The key should get dropped and there should be no ANR.
3302
3303 ASSERT_TRUE(mDispatcher->waitForIdle());
3304 mFakePolicy->assertNotifyAnrWasNotCalled();
3305}
3306
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003307// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003308// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3309// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003310TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003311 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003312 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3313 WINDOW_LOCATION));
3314
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003315 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3316 ASSERT_TRUE(sequenceNum);
3317 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003318 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003319
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003320 mWindow->finishEvent(*sequenceNum);
3321 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3322 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003323 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003324 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003325}
3326
3327// Send a key to the app and have the app not respond right away.
3328TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3329 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003330 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003331 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3332 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003333 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003334 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003335 ASSERT_TRUE(mDispatcher->waitForIdle());
3336}
3337
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003338// We have a focused application, but no focused window
3339TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003340 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3342 mWindow->consumeFocusEvent(false);
3343
3344 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003345 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003346 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3347 WINDOW_LOCATION));
3348 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3349 mDispatcher->waitForIdle();
3350 mFakePolicy->assertNotifyAnrWasNotCalled();
3351
3352 // Once a focused event arrives, we get an ANR for this application
3353 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3354 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003355 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003356 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003357 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003358 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003359 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003360 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003361 ASSERT_TRUE(mDispatcher->waitForIdle());
3362}
3363
3364// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003365// Make sure that we don't notify policy twice about the same ANR.
3366TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003367 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3369 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003370
3371 // Once a focused event arrives, we get an ANR for this application
3372 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3373 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003374 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003375 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003376 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003377 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003378 const std::chrono::duration appTimeout =
3379 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003380 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003381
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003382 std::this_thread::sleep_for(appTimeout);
3383 // ANR should not be raised again. It is up to policy to do that if it desires.
3384 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003385
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003386 // If we now get a focused window, the ANR should stop, but the policy handles that via
3387 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003388 ASSERT_TRUE(mDispatcher->waitForIdle());
3389}
3390
3391// We have a focused application, but no focused window
3392TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003393 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003394 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3395 mWindow->consumeFocusEvent(false);
3396
3397 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003398 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003399 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003400 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3401 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003402
3403 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003404 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003405
3406 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003407 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003408 ASSERT_TRUE(mDispatcher->waitForIdle());
3409 mWindow->assertNoEvents();
3410}
3411
3412/**
3413 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3414 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3415 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3416 * the ANR mechanism should still work.
3417 *
3418 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3419 * DOWN event, while not responding on the second one.
3420 */
3421TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3422 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3423 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3424 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3425 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3426 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003427 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003428
3429 // Now send ACTION_UP, with identical timestamp
3430 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3431 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3432 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3433 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003434 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003435
3436 // We have now sent down and up. Let's consume first event and then ANR on the second.
3437 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3438 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003439 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003440}
3441
3442// If an app is not responding to a key event, gesture monitors should continue to receive
3443// new motion events
3444TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3445 FakeMonitorReceiver monitor =
3446 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3447 true /*isGestureMonitor*/);
3448
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3450 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003451 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003452 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003453
3454 // Stuck on the ACTION_UP
3455 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003456 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003457
3458 // New tap will go to the gesture monitor, but not to the window
3459 tapOnWindow();
3460 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3461 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3462
3463 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3464 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003465 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003466 mWindow->assertNoEvents();
3467 monitor.assertNoEvents();
3468}
3469
3470// If an app is not responding to a motion event, gesture monitors should continue to receive
3471// new motion events
3472TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3473 FakeMonitorReceiver monitor =
3474 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3475 true /*isGestureMonitor*/);
3476
3477 tapOnWindow();
3478 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3479 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3480
3481 mWindow->consumeMotionDown();
3482 // Stuck on the ACTION_UP
3483 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003484 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003485
3486 // New tap will go to the gesture monitor, but not to the window
3487 tapOnWindow();
3488 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3489 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3490
3491 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3492 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003493 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003494 mWindow->assertNoEvents();
3495 monitor.assertNoEvents();
3496}
3497
3498// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3499// process events, you don't get an anr. When the window later becomes unresponsive again, you
3500// get an ANR again.
3501// 1. tap -> block on ACTION_UP -> receive ANR
3502// 2. consume all pending events (= queue becomes healthy again)
3503// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3504TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3505 tapOnWindow();
3506
3507 mWindow->consumeMotionDown();
3508 // Block on ACTION_UP
3509 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003510 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003511 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3512 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003513 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003514 mWindow->assertNoEvents();
3515
3516 tapOnWindow();
3517 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003518 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003519 mWindow->consumeMotionUp();
3520
3521 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003522 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003523 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003524 mWindow->assertNoEvents();
3525}
3526
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003527// If a connection remains unresponsive for a while, make sure policy is only notified once about
3528// it.
3529TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003530 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003531 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3532 WINDOW_LOCATION));
3533
3534 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003535 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003536 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003537 // 'notifyConnectionUnresponsive' should only be called once per connection
3538 mFakePolicy->assertNotifyAnrWasNotCalled();
3539 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003540 mWindow->consumeMotionDown();
3541 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3542 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3543 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003544 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003545 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003546 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003547}
3548
3549/**
3550 * If a window is processing a motion event, and then a key event comes in, the key event should
3551 * not to to the focused window until the motion is processed.
3552 *
3553 * Warning!!!
3554 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3555 * and the injection timeout that we specify when injecting the key.
3556 * We must have the injection timeout (10ms) be smaller than
3557 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3558 *
3559 * If that value changes, this test should also change.
3560 */
3561TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3562 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3564
3565 tapOnWindow();
3566 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3567 ASSERT_TRUE(downSequenceNum);
3568 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3569 ASSERT_TRUE(upSequenceNum);
3570 // Don't finish the events yet, and send a key
3571 // Injection will "succeed" because we will eventually give up and send the key to the focused
3572 // window even if motions are still being processed. But because the injection timeout is short,
3573 // we will receive INJECTION_TIMED_OUT as the result.
3574
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003575 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003576 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003577 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3578 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003579 // Key will not be sent to the window, yet, because the window is still processing events
3580 // and the key remains pending, waiting for the touch events to be processed
3581 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3582 ASSERT_FALSE(keySequenceNum);
3583
3584 std::this_thread::sleep_for(500ms);
3585 // if we wait long enough though, dispatcher will give up, and still send the key
3586 // to the focused window, even though we have not yet finished the motion event
3587 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3588 mWindow->finishEvent(*downSequenceNum);
3589 mWindow->finishEvent(*upSequenceNum);
3590}
3591
3592/**
3593 * If a window is processing a motion event, and then a key event comes in, the key event should
3594 * not go to the focused window until the motion is processed.
3595 * If then a new motion comes in, then the pending key event should be going to the currently
3596 * focused window right away.
3597 */
3598TEST_F(InputDispatcherSingleWindowAnr,
3599 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3600 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3602
3603 tapOnWindow();
3604 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3605 ASSERT_TRUE(downSequenceNum);
3606 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3607 ASSERT_TRUE(upSequenceNum);
3608 // Don't finish the events yet, and send a key
3609 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003611 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003612 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003613 // At this point, key is still pending, and should not be sent to the application yet.
3614 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3615 ASSERT_FALSE(keySequenceNum);
3616
3617 // Now tap down again. It should cause the pending key to go to the focused window right away.
3618 tapOnWindow();
3619 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3620 // the other events yet. We can finish events in any order.
3621 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3622 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3623 mWindow->consumeMotionDown();
3624 mWindow->consumeMotionUp();
3625 mWindow->assertNoEvents();
3626}
3627
3628class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3629 virtual void SetUp() override {
3630 InputDispatcherTest::SetUp();
3631
Chris Yea209fde2020-07-22 13:54:51 -07003632 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003633 mApplication->setDispatchingTimeout(10ms);
3634 mUnfocusedWindow =
3635 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3636 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3637 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3638 // window.
3639 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003640 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3641 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3642 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003643
3644 mFocusedWindow =
3645 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003646 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003647 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003648 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3649 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003650
3651 // Set focused application.
3652 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003653 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003654
3655 // Expect one focus window exist in display.
3656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003657 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003658 mFocusedWindow->consumeFocusEvent(true);
3659 }
3660
3661 virtual void TearDown() override {
3662 InputDispatcherTest::TearDown();
3663
3664 mUnfocusedWindow.clear();
3665 mFocusedWindow.clear();
3666 }
3667
3668protected:
Chris Yea209fde2020-07-22 13:54:51 -07003669 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003670 sp<FakeWindowHandle> mUnfocusedWindow;
3671 sp<FakeWindowHandle> mFocusedWindow;
3672 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3673 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3674 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3675
3676 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3677
3678 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3679
3680private:
3681 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003683 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3684 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003685 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003686 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3687 location));
3688 }
3689};
3690
3691// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3692// should be ANR'd first.
3693TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003695 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3696 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003698 mFocusedWindow->consumeMotionDown();
3699 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3700 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3701 // We consumed all events, so no ANR
3702 ASSERT_TRUE(mDispatcher->waitForIdle());
3703 mFakePolicy->assertNotifyAnrWasNotCalled();
3704
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003705 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003706 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3707 FOCUSED_WINDOW_LOCATION));
3708 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
3709 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003710
3711 const std::chrono::duration timeout =
3712 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003713 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003714 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
3715 // sequence to make it consistent
3716 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003717 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003718 mFocusedWindow->consumeMotionDown();
3719 // This cancel is generated because the connection was unresponsive
3720 mFocusedWindow->consumeMotionCancel();
3721 mFocusedWindow->assertNoEvents();
3722 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003723 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003724 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003725 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003726}
3727
3728// If we have 2 windows with identical timeouts that are both unresponsive,
3729// it doesn't matter which order they should have ANR.
3730// But we should receive ANR for both.
3731TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
3732 // Set the timeout for unfocused window to match the focused window
3733 mUnfocusedWindow->setDispatchingTimeout(10ms);
3734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3735
3736 tapOnFocusedWindow();
3737 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003738 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
3739 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003740
3741 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003742 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
3743 mFocusedWindow->getToken() == anrConnectionToken2);
3744 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
3745 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003746
3747 ASSERT_TRUE(mDispatcher->waitForIdle());
3748 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003749
3750 mFocusedWindow->consumeMotionDown();
3751 mFocusedWindow->consumeMotionUp();
3752 mUnfocusedWindow->consumeMotionOutside();
3753
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003754 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
3755 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003756
3757 // Both applications should be marked as responsive, in any order
3758 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
3759 mFocusedWindow->getToken() == responsiveToken2);
3760 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
3761 mUnfocusedWindow->getToken() == responsiveToken2);
3762 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003763}
3764
3765// If a window is already not responding, the second tap on the same window should be ignored.
3766// We should also log an error to account for the dropped event (not tested here).
3767// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
3768TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
3769 tapOnFocusedWindow();
3770 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3771 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3772 // Receive the events, but don't respond
3773 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
3774 ASSERT_TRUE(downEventSequenceNum);
3775 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
3776 ASSERT_TRUE(upEventSequenceNum);
3777 const std::chrono::duration timeout =
3778 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003779 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003780
3781 // Tap once again
3782 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003783 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003784 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3785 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003786 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003787 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3788 FOCUSED_WINDOW_LOCATION));
3789 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
3790 // valid touch target
3791 mUnfocusedWindow->assertNoEvents();
3792
3793 // Consume the first tap
3794 mFocusedWindow->finishEvent(*downEventSequenceNum);
3795 mFocusedWindow->finishEvent(*upEventSequenceNum);
3796 ASSERT_TRUE(mDispatcher->waitForIdle());
3797 // The second tap did not go to the focused window
3798 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003799 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003800 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003801 mFakePolicy->assertNotifyAnrWasNotCalled();
3802}
3803
3804// If you tap outside of all windows, there will not be ANR
3805TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003806 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003807 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3808 LOCATION_OUTSIDE_ALL_WINDOWS));
3809 ASSERT_TRUE(mDispatcher->waitForIdle());
3810 mFakePolicy->assertNotifyAnrWasNotCalled();
3811}
3812
3813// Since the focused window is paused, tapping on it should not produce any events
3814TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
3815 mFocusedWindow->setPaused(true);
3816 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3817
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003818 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003819 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3820 FOCUSED_WINDOW_LOCATION));
3821
3822 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
3823 ASSERT_TRUE(mDispatcher->waitForIdle());
3824 // Should not ANR because the window is paused, and touches shouldn't go to it
3825 mFakePolicy->assertNotifyAnrWasNotCalled();
3826
3827 mFocusedWindow->assertNoEvents();
3828 mUnfocusedWindow->assertNoEvents();
3829}
3830
3831/**
3832 * If a window is processing a motion event, and then a key event comes in, the key event should
3833 * not to to the focused window until the motion is processed.
3834 * If a different window becomes focused at this time, the key should go to that window instead.
3835 *
3836 * Warning!!!
3837 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3838 * and the injection timeout that we specify when injecting the key.
3839 * We must have the injection timeout (10ms) be smaller than
3840 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3841 *
3842 * If that value changes, this test should also change.
3843 */
3844TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
3845 // Set a long ANR timeout to prevent it from triggering
3846 mFocusedWindow->setDispatchingTimeout(2s);
3847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3848
3849 tapOnUnfocusedWindow();
3850 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
3851 ASSERT_TRUE(downSequenceNum);
3852 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
3853 ASSERT_TRUE(upSequenceNum);
3854 // Don't finish the events yet, and send a key
3855 // Injection will succeed because we will eventually give up and send the key to the focused
3856 // window even if motions are still being processed.
3857
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003858 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003859 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003860 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
3861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003862 // Key will not be sent to the window, yet, because the window is still processing events
3863 // and the key remains pending, waiting for the touch events to be processed
3864 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
3865 ASSERT_FALSE(keySequenceNum);
3866
3867 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07003868 mFocusedWindow->setFocusable(false);
3869 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003871 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003872
3873 // Focus events should precede the key events
3874 mUnfocusedWindow->consumeFocusEvent(true);
3875 mFocusedWindow->consumeFocusEvent(false);
3876
3877 // Finish the tap events, which should unblock dispatcher
3878 mUnfocusedWindow->finishEvent(*downSequenceNum);
3879 mUnfocusedWindow->finishEvent(*upSequenceNum);
3880
3881 // Now that all queues are cleared and no backlog in the connections, the key event
3882 // can finally go to the newly focused "mUnfocusedWindow".
3883 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3884 mFocusedWindow->assertNoEvents();
3885 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003886 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003887}
3888
3889// When the touch stream is split across 2 windows, and one of them does not respond,
3890// then ANR should be raised and the touch should be canceled for the unresponsive window.
3891// The other window should not be affected by that.
3892TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
3893 // Touch Window 1
3894 NotifyMotionArgs motionArgs =
3895 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3896 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
3897 mDispatcher->notifyMotion(&motionArgs);
3898 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3899 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3900
3901 // Touch Window 2
3902 int32_t actionPointerDown =
3903 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3904
3905 motionArgs =
3906 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3907 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
3908 mDispatcher->notifyMotion(&motionArgs);
3909
3910 const std::chrono::duration timeout =
3911 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003912 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003913
3914 mUnfocusedWindow->consumeMotionDown();
3915 mFocusedWindow->consumeMotionDown();
3916 // Focused window may or may not receive ACTION_MOVE
3917 // But it should definitely receive ACTION_CANCEL due to the ANR
3918 InputEvent* event;
3919 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
3920 ASSERT_TRUE(moveOrCancelSequenceNum);
3921 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
3922 ASSERT_NE(nullptr, event);
3923 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
3924 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
3925 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
3926 mFocusedWindow->consumeMotionCancel();
3927 } else {
3928 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
3929 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003930 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003931 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003932
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003933 mUnfocusedWindow->assertNoEvents();
3934 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003935 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003936}
3937
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003938/**
3939 * If we have no focused window, and a key comes in, we start the ANR timer.
3940 * The focused application should add a focused window before the timer runs out to prevent ANR.
3941 *
3942 * If the user touches another application during this time, the key should be dropped.
3943 * Next, if a new focused window comes in, without toggling the focused application,
3944 * then no ANR should occur.
3945 *
3946 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
3947 * but in some cases the policy may not update the focused application.
3948 */
3949TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
3950 std::shared_ptr<FakeApplicationHandle> focusedApplication =
3951 std::make_shared<FakeApplicationHandle>();
3952 focusedApplication->setDispatchingTimeout(60ms);
3953 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
3954 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
3955 mFocusedWindow->setFocusable(false);
3956
3957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3958 mFocusedWindow->consumeFocusEvent(false);
3959
3960 // Send a key. The ANR timer should start because there is no focused window.
3961 // 'focusedApplication' will get blamed if this timer completes.
3962 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003963 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003964 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003965 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3966 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05003968
3969 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
3970 // then the injected touches won't cause the focused event to get dropped.
3971 // The dispatcher only checks for whether the queue should be pruned upon queueing.
3972 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
3973 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
3974 // For this test, it means that the key would get delivered to the window once it becomes
3975 // focused.
3976 std::this_thread::sleep_for(10ms);
3977
3978 // Touch unfocused window. This should force the pending key to get dropped.
3979 NotifyMotionArgs motionArgs =
3980 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3981 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
3982 mDispatcher->notifyMotion(&motionArgs);
3983
3984 // We do not consume the motion right away, because that would require dispatcher to first
3985 // process (== drop) the key event, and by that time, ANR will be raised.
3986 // Set the focused window first.
3987 mFocusedWindow->setFocusable(true);
3988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
3989 setFocusedWindow(mFocusedWindow);
3990 mFocusedWindow->consumeFocusEvent(true);
3991 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
3992 // to another application. This could be a bug / behaviour in the policy.
3993
3994 mUnfocusedWindow->consumeMotionDown();
3995
3996 ASSERT_TRUE(mDispatcher->waitForIdle());
3997 // Should not ANR because we actually have a focused window. It was just added too slowly.
3998 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
3999}
4000
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004001// These tests ensure we cannot send touch events to a window that's positioned behind a window
4002// that has feature NO_INPUT_CHANNEL.
4003// Layout:
4004// Top (closest to user)
4005// mNoInputWindow (above all windows)
4006// mBottomWindow
4007// Bottom (furthest from user)
4008class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4009 virtual void SetUp() override {
4010 InputDispatcherTest::SetUp();
4011
4012 mApplication = std::make_shared<FakeApplicationHandle>();
4013 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4014 "Window without input channel", ADISPLAY_ID_DEFAULT,
4015 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4016
4017 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4018 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4019 // It's perfectly valid for this window to not have an associated input channel
4020
4021 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4022 ADISPLAY_ID_DEFAULT);
4023 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4024
4025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4026 }
4027
4028protected:
4029 std::shared_ptr<FakeApplicationHandle> mApplication;
4030 sp<FakeWindowHandle> mNoInputWindow;
4031 sp<FakeWindowHandle> mBottomWindow;
4032};
4033
4034TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4035 PointF touchedPoint = {10, 10};
4036
4037 NotifyMotionArgs motionArgs =
4038 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4039 ADISPLAY_ID_DEFAULT, {touchedPoint});
4040 mDispatcher->notifyMotion(&motionArgs);
4041
4042 mNoInputWindow->assertNoEvents();
4043 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4044 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4045 // and therefore should prevent mBottomWindow from receiving touches
4046 mBottomWindow->assertNoEvents();
4047}
4048
4049/**
4050 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4051 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4052 */
4053TEST_F(InputDispatcherMultiWindowOcclusionTests,
4054 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4055 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4056 "Window with input channel and NO_INPUT_CHANNEL",
4057 ADISPLAY_ID_DEFAULT);
4058
4059 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4060 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4062
4063 PointF touchedPoint = {10, 10};
4064
4065 NotifyMotionArgs motionArgs =
4066 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4067 ADISPLAY_ID_DEFAULT, {touchedPoint});
4068 mDispatcher->notifyMotion(&motionArgs);
4069
4070 mNoInputWindow->assertNoEvents();
4071 mBottomWindow->assertNoEvents();
4072}
4073
Vishnu Nair958da932020-08-21 17:12:37 -07004074class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4075protected:
4076 std::shared_ptr<FakeApplicationHandle> mApp;
4077 sp<FakeWindowHandle> mWindow;
4078 sp<FakeWindowHandle> mMirror;
4079
4080 virtual void SetUp() override {
4081 InputDispatcherTest::SetUp();
4082 mApp = std::make_shared<FakeApplicationHandle>();
4083 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4084 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4085 mWindow->getToken());
4086 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4087 mWindow->setFocusable(true);
4088 mMirror->setFocusable(true);
4089 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4090 }
4091};
4092
4093TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4094 // Request focus on a mirrored window
4095 setFocusedWindow(mMirror);
4096
4097 // window gets focused
4098 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004099 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4100 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004101 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4102}
4103
4104// A focused & mirrored window remains focused only if the window and its mirror are both
4105// focusable.
4106TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4107 setFocusedWindow(mMirror);
4108
4109 // window gets focused
4110 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004111 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4112 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004113 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4115 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004116 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4117
4118 mMirror->setFocusable(false);
4119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4120
4121 // window loses focus since one of the windows associated with the token in not focusable
4122 mWindow->consumeFocusEvent(false);
4123
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004124 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4125 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004126 mWindow->assertNoEvents();
4127}
4128
4129// A focused & mirrored window remains focused until the window and its mirror both become
4130// invisible.
4131TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
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);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004139 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4140 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004141 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4142
4143 mMirror->setVisible(false);
4144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4145
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004146 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4147 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004148 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004149 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4150 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004151 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4152
4153 mWindow->setVisible(false);
4154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4155
4156 // window loses focus only after all windows associated with the token become invisible.
4157 mWindow->consumeFocusEvent(false);
4158
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004159 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4160 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004161 mWindow->assertNoEvents();
4162}
4163
4164// A focused & mirrored window remains focused until both windows are removed.
4165TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4166 setFocusedWindow(mMirror);
4167
4168 // window gets focused
4169 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4171 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004172 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4174 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004175 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4176
4177 // single window is removed but the window token remains focused
4178 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4179
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004180 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4181 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004182 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004183 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4184 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004185 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4186
4187 // Both windows are removed
4188 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4189 mWindow->consumeFocusEvent(false);
4190
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004191 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4192 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004193 mWindow->assertNoEvents();
4194}
4195
4196// Focus request can be pending until one window becomes visible.
4197TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4198 // Request focus on an invisible mirror.
4199 mWindow->setVisible(false);
4200 mMirror->setVisible(false);
4201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4202 setFocusedWindow(mMirror);
4203
4204 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004206 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004207 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004208
4209 mMirror->setVisible(true);
4210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4211
4212 // window gets focused
4213 mWindow->consumeFocusEvent(true);
4214 // window gets the pending key event
4215 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4216}
Prabir Pradhan99987712020-11-10 18:43:05 -08004217
4218class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4219protected:
4220 std::shared_ptr<FakeApplicationHandle> mApp;
4221 sp<FakeWindowHandle> mWindow;
4222 sp<FakeWindowHandle> mSecondWindow;
4223
4224 void SetUp() override {
4225 InputDispatcherTest::SetUp();
4226 mApp = std::make_shared<FakeApplicationHandle>();
4227 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4228 mWindow->setFocusable(true);
4229 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4230 mSecondWindow->setFocusable(true);
4231
4232 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4233 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4234
4235 setFocusedWindow(mWindow);
4236 mWindow->consumeFocusEvent(true);
4237 }
4238
4239 void notifyPointerCaptureChanged(bool enabled) {
4240 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
4241 mDispatcher->notifyPointerCaptureChanged(&args);
4242 }
4243
4244 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
4245 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4246 mFakePolicy->waitForSetPointerCapture(enabled);
4247 notifyPointerCaptureChanged(enabled);
4248 window->consumeCaptureEvent(enabled);
4249 }
4250};
4251
4252TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4253 // Ensure that capture cannot be obtained for unfocused windows.
4254 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4255 mFakePolicy->assertSetPointerCaptureNotCalled();
4256 mSecondWindow->assertNoEvents();
4257
4258 // Ensure that capture can be enabled from the focus window.
4259 requestAndVerifyPointerCapture(mWindow, true);
4260
4261 // Ensure that capture cannot be disabled from a window that does not have capture.
4262 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4263 mFakePolicy->assertSetPointerCaptureNotCalled();
4264
4265 // Ensure that capture can be disabled from the window with capture.
4266 requestAndVerifyPointerCapture(mWindow, false);
4267}
4268
4269TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4270 requestAndVerifyPointerCapture(mWindow, true);
4271
4272 setFocusedWindow(mSecondWindow);
4273
4274 // Ensure that the capture disabled event was sent first.
4275 mWindow->consumeCaptureEvent(false);
4276 mWindow->consumeFocusEvent(false);
4277 mSecondWindow->consumeFocusEvent(true);
4278 mFakePolicy->waitForSetPointerCapture(false);
4279
4280 // Ensure that additional state changes from InputReader are not sent to the window.
4281 notifyPointerCaptureChanged(false);
4282 notifyPointerCaptureChanged(true);
4283 notifyPointerCaptureChanged(false);
4284 mWindow->assertNoEvents();
4285 mSecondWindow->assertNoEvents();
4286 mFakePolicy->assertSetPointerCaptureNotCalled();
4287}
4288
4289TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4290 requestAndVerifyPointerCapture(mWindow, true);
4291
4292 // InputReader unexpectedly disables and enables pointer capture.
4293 notifyPointerCaptureChanged(false);
4294 notifyPointerCaptureChanged(true);
4295
4296 // Ensure that Pointer Capture is disabled.
Prabir Pradhan7d030382020-12-21 07:58:35 -08004297 mFakePolicy->waitForSetPointerCapture(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004298 mWindow->consumeCaptureEvent(false);
4299 mWindow->assertNoEvents();
4300}
4301
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004302TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4303 requestAndVerifyPointerCapture(mWindow, true);
4304
4305 // The first window loses focus.
4306 setFocusedWindow(mSecondWindow);
4307 mFakePolicy->waitForSetPointerCapture(false);
4308 mWindow->consumeCaptureEvent(false);
4309
4310 // Request Pointer Capture from the second window before the notification from InputReader
4311 // arrives.
4312 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4313 mFakePolicy->waitForSetPointerCapture(true);
4314
4315 // InputReader notifies Pointer Capture was disabled (because of the focus change).
4316 notifyPointerCaptureChanged(false);
4317
4318 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
4319 notifyPointerCaptureChanged(true);
4320
4321 mSecondWindow->consumeFocusEvent(true);
4322 mSecondWindow->consumeCaptureEvent(true);
4323}
4324
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004325class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4326protected:
4327 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00004328
4329 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4330 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4331
4332 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4333 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4334
4335 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4336 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4337 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4338 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4339 MAXIMUM_OBSCURING_OPACITY);
4340
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004341 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004342 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004343 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004344
4345 sp<FakeWindowHandle> mTouchWindow;
4346
4347 virtual void SetUp() override {
4348 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004349 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004350 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4351 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4352 }
4353
4354 virtual void TearDown() override {
4355 InputDispatcherTest::TearDown();
4356 mTouchWindow.clear();
4357 }
4358
4359 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name,
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004360 os::TouchOcclusionMode mode, float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004361 sp<FakeWindowHandle> window = getWindow(uid, name);
4362 window->setFlags(InputWindowInfo::Flag::NOT_TOUCHABLE);
4363 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004364 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004365 return window;
4366 }
4367
4368 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4369 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4370 sp<FakeWindowHandle> window =
4371 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4372 // Generate an arbitrary PID based on the UID
4373 window->setOwnerInfo(1777 + (uid % 10000), uid);
4374 return window;
4375 }
4376
4377 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4378 NotifyMotionArgs args =
4379 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4380 ADISPLAY_ID_DEFAULT, points);
4381 mDispatcher->notifyMotion(&args);
4382 }
4383};
4384
4385TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004386 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004387 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004389
4390 touch();
4391
4392 mTouchWindow->assertNoEvents();
4393}
4394
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004395TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00004396 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
4397 const sp<FakeWindowHandle>& w =
4398 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
4399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4400
4401 touch();
4402
4403 mTouchWindow->assertNoEvents();
4404}
4405
4406TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004407 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
4408 const sp<FakeWindowHandle>& w =
4409 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4410 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4411
4412 touch();
4413
4414 w->assertNoEvents();
4415}
4416
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004417TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004418 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
4419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004420
4421 touch();
4422
4423 mTouchWindow->consumeAnyMotionDown();
4424}
4425
4426TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004427 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004428 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004429 w->setFrame(Rect(0, 0, 50, 50));
4430 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004431
4432 touch({PointF{100, 100}});
4433
4434 mTouchWindow->consumeAnyMotionDown();
4435}
4436
4437TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004438 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004439 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004440 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4441
4442 touch();
4443
4444 mTouchWindow->consumeAnyMotionDown();
4445}
4446
4447TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
4448 const sp<FakeWindowHandle>& w =
4449 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4450 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004451
4452 touch();
4453
4454 mTouchWindow->consumeAnyMotionDown();
4455}
4456
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004457TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
4458 const sp<FakeWindowHandle>& w =
4459 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4461
4462 touch();
4463
4464 w->assertNoEvents();
4465}
4466
4467/**
4468 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
4469 * inside) while letting them pass-through. Note that even though touch passes through the occluding
4470 * window, the occluding window will still receive ACTION_OUTSIDE event.
4471 */
4472TEST_F(InputDispatcherUntrustedTouchesTest,
4473 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
4474 const sp<FakeWindowHandle>& w =
4475 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4476 w->addFlags(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
4477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4478
4479 touch();
4480
4481 w->consumeMotionOutside();
4482}
4483
4484TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
4485 const sp<FakeWindowHandle>& w =
4486 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4487 w->addFlags(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
4488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4489
4490 touch();
4491
4492 InputEvent* event = w->consume();
4493 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
4494 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4495 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
4496 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
4497}
4498
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004499TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004500 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004501 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4502 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004503 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4504
4505 touch();
4506
4507 mTouchWindow->consumeAnyMotionDown();
4508}
4509
4510TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
4511 const sp<FakeWindowHandle>& w =
4512 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4513 MAXIMUM_OBSCURING_OPACITY);
4514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004515
4516 touch();
4517
4518 mTouchWindow->consumeAnyMotionDown();
4519}
4520
4521TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004522 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004523 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4524 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4526
4527 touch();
4528
4529 mTouchWindow->assertNoEvents();
4530}
4531
4532TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
4533 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
4534 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004535 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4536 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004537 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004538 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4539 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4541
4542 touch();
4543
4544 mTouchWindow->assertNoEvents();
4545}
4546
4547TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
4548 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
4549 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004550 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4551 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004552 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004553 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4554 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4556
4557 touch();
4558
4559 mTouchWindow->consumeAnyMotionDown();
4560}
4561
4562TEST_F(InputDispatcherUntrustedTouchesTest,
4563 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
4564 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004565 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4566 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004567 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004568 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4569 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004570 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4571
4572 touch();
4573
4574 mTouchWindow->consumeAnyMotionDown();
4575}
4576
4577TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
4578 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004579 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4580 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004581 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004582 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4583 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004585
4586 touch();
4587
4588 mTouchWindow->assertNoEvents();
4589}
4590
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004591TEST_F(InputDispatcherUntrustedTouchesTest,
4592 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
4593 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004594 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4595 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004596 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004597 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4598 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004599 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4600
4601 touch();
4602
4603 mTouchWindow->assertNoEvents();
4604}
4605
4606TEST_F(InputDispatcherUntrustedTouchesTest,
4607 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
4608 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004609 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4610 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004611 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004612 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4613 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4615
4616 touch();
4617
4618 mTouchWindow->consumeAnyMotionDown();
4619}
4620
4621TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
4622 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004623 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4624 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4626
4627 touch();
4628
4629 mTouchWindow->consumeAnyMotionDown();
4630}
4631
4632TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
4633 const sp<FakeWindowHandle>& w =
4634 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
4635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4636
4637 touch();
4638
4639 mTouchWindow->consumeAnyMotionDown();
4640}
4641
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004642TEST_F(InputDispatcherUntrustedTouchesTest,
4643 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
4644 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4645 const sp<FakeWindowHandle>& w =
4646 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
4647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4648
4649 touch();
4650
4651 mTouchWindow->assertNoEvents();
4652}
4653
4654TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
4655 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4656 const sp<FakeWindowHandle>& w =
4657 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
4658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4659
4660 touch();
4661
4662 mTouchWindow->consumeAnyMotionDown();
4663}
4664
4665TEST_F(InputDispatcherUntrustedTouchesTest,
4666 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
4667 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
4668 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004669 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4670 OPACITY_ABOVE_THRESHOLD);
4671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4672
4673 touch();
4674
4675 mTouchWindow->consumeAnyMotionDown();
4676}
4677
4678TEST_F(InputDispatcherUntrustedTouchesTest,
4679 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
4680 const sp<FakeWindowHandle>& w1 =
4681 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4682 OPACITY_BELOW_THRESHOLD);
4683 const sp<FakeWindowHandle>& w2 =
4684 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4685 OPACITY_BELOW_THRESHOLD);
4686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4687
4688 touch();
4689
4690 mTouchWindow->assertNoEvents();
4691}
4692
4693/**
4694 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
4695 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
4696 * (which alone would result in allowing touches) does not affect the blocking behavior.
4697 */
4698TEST_F(InputDispatcherUntrustedTouchesTest,
4699 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
4700 const sp<FakeWindowHandle>& wB =
4701 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4702 OPACITY_BELOW_THRESHOLD);
4703 const sp<FakeWindowHandle>& wC =
4704 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4705 OPACITY_BELOW_THRESHOLD);
4706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4707
4708 touch();
4709
4710 mTouchWindow->assertNoEvents();
4711}
4712
4713/**
4714 * This test is testing that a window from a different UID but with same application token doesn't
4715 * block the touch. Apps can share the application token for close UI collaboration for example.
4716 */
4717TEST_F(InputDispatcherUntrustedTouchesTest,
4718 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
4719 const sp<FakeWindowHandle>& w =
4720 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4721 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4723
4724 touch();
4725
4726 mTouchWindow->consumeAnyMotionDown();
4727}
4728
arthurhungb89ccb02020-12-30 16:19:01 +08004729class InputDispatcherDragTests : public InputDispatcherTest {
4730protected:
4731 std::shared_ptr<FakeApplicationHandle> mApp;
4732 sp<FakeWindowHandle> mWindow;
4733 sp<FakeWindowHandle> mSecondWindow;
4734 sp<FakeWindowHandle> mDragWindow;
4735
4736 void SetUp() override {
4737 InputDispatcherTest::SetUp();
4738 mApp = std::make_shared<FakeApplicationHandle>();
4739 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4740 mWindow->setFrame(Rect(0, 0, 100, 100));
4741 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
4742
4743 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4744 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
4745 mSecondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
4746
4747 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4749 }
4750
4751 // Start performing drag, we will create a drag window and transfer touch to it.
4752 void performDrag() {
4753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4754 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4755 {50, 50}))
4756 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4757
4758 // Window should receive motion event.
4759 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4760
4761 // The drag window covers the entire display
4762 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
4763 mDispatcher->setInputWindows(
4764 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
4765
4766 // Transfer touch focus to the drag window
4767 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
4768 true /* isDragDrop */);
4769 mWindow->consumeMotionCancel();
4770 mDragWindow->consumeMotionDown();
4771 }
4772};
4773
4774TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
4775 performDrag();
4776
4777 // Move on window.
4778 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4779 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4780 ADISPLAY_ID_DEFAULT, {50, 50}))
4781 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4782 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4783 mWindow->consumeDragEvent(false, 50, 50);
4784 mSecondWindow->assertNoEvents();
4785
4786 // Move to another window.
4787 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4788 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4789 ADISPLAY_ID_DEFAULT, {150, 50}))
4790 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4791 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4792 mWindow->consumeDragEvent(true, 150, 50);
4793 mSecondWindow->consumeDragEvent(false, 50, 50);
4794
4795 // Move back to original window.
4796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4797 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4798 ADISPLAY_ID_DEFAULT, {50, 50}))
4799 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4800 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
4801 mWindow->consumeDragEvent(false, 50, 50);
4802 mSecondWindow->consumeDragEvent(true, -50, 50);
4803
4804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4805 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
4806 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4807 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
4808 mWindow->assertNoEvents();
4809 mSecondWindow->assertNoEvents();
4810}
4811
Garfield Tane84e6f92019-08-29 17:28:41 -07004812} // namespace android::inputdispatcher