blob: 09b6a796255189e94009dda662370017e1597369 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Garfield Tan1c7bc862020-01-28 13:24:04 -080019#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070020#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070021#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080022#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100023#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <linux/input.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100025
Garfield Tan1c7bc862020-01-28 13:24:04 -080026#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070027#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080028#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080029#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080030
Garfield Tan1c7bc862020-01-28 13:24:04 -080031using android::base::StringPrintf;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080032using android::os::InputEventInjectionResult;
33using android::os::InputEventInjectionSync;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +000034using android::os::TouchOcclusionMode;
Michael Wright44753b12020-07-08 13:48:11 +010035using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080036
Garfield Tane84e6f92019-08-29 17:28:41 -070037namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
39// An arbitrary time value.
40static const nsecs_t ARBITRARY_TIME = 1234;
41
42// An arbitrary device id.
43static const int32_t DEVICE_ID = 1;
44
Jeff Brownf086ddb2014-02-11 14:28:48 -080045// An arbitrary display id.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -080046static const int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
Jeff Brownf086ddb2014-02-11 14:28:48 -080047
Michael Wrightd02c5b62014-02-10 15:10:22 -080048// An arbitrary injector pid / uid pair that has permission to inject events.
49static const int32_t INJECTOR_PID = 999;
50static const int32_t INJECTOR_UID = 1001;
51
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000052// An arbitrary pid of the gesture monitor window
53static constexpr int32_t MONITOR_PID = 2001;
54
chaviwd1c23182019-12-20 18:44:56 -080055struct PointF {
56 float x;
57 float y;
58};
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
Gang Wang342c9272020-01-13 13:15:04 -050060/**
61 * Return a DOWN key event with KEYCODE_A.
62 */
63static KeyEvent getTestKeyEvent() {
64 KeyEvent event;
65
Garfield Tanfbe732e2020-01-24 11:26:14 -080066 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
67 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
68 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050069 return event;
70}
71
Michael Wrightd02c5b62014-02-10 15:10:22 -080072// --- FakeInputDispatcherPolicy ---
73
74class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
75 InputDispatcherConfiguration mConfig;
76
77protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100078 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100081 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080082
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080083 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080084 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
85 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080086 }
87
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080088 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080089 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
90 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080091 }
92
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070093 void assertFilterInputEventWasNotCalled() {
94 std::scoped_lock lock(mLock);
95 ASSERT_EQ(nullptr, mFilteredEvent);
96 }
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080098 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070099 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800100 ASSERT_TRUE(mConfigurationChangedTime)
101 << "Timed out waiting for configuration changed call";
102 ASSERT_EQ(*mConfigurationChangedTime, when);
103 mConfigurationChangedTime = std::nullopt;
104 }
105
106 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700107 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800108 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800109 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800110 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
111 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
112 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
113 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
114 mLastNotifySwitch = std::nullopt;
115 }
116
chaviwfd6d3512019-03-25 13:23:49 -0700117 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700118 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800119 ASSERT_EQ(touchedToken, mOnPointerDownToken);
120 mOnPointerDownToken.clear();
121 }
122
123 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700124 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800125 ASSERT_TRUE(mOnPointerDownToken == nullptr)
126 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700127 }
128
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700129 // This function must be called soon after the expected ANR timer starts,
130 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500131 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700132 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500133 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
134 std::shared_ptr<InputApplicationHandle> application;
135 { // acquire lock
136 std::unique_lock lock(mLock);
137 android::base::ScopedLockAssertion assumeLocked(mLock);
138 ASSERT_NO_FATAL_FAILURE(
139 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
140 } // release lock
141 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700142 }
143
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000144 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
145 const sp<IBinder>& expectedConnectionToken) {
146 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500147 ASSERT_EQ(expectedConnectionToken, connectionToken);
148 }
149
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000150 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
151 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500152 ASSERT_EQ(expectedConnectionToken, connectionToken);
153 }
154
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000155 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
156 int32_t pid = getUnresponsiveMonitorPid(timeout);
157 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500158 }
159
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000160 void assertNotifyMonitorResponsiveWasCalled() {
161 int32_t pid = getResponsiveMonitorPid();
162 ASSERT_EQ(MONITOR_PID, pid);
163 }
164
165 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500166 std::unique_lock lock(mLock);
167 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000168 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
169 }
170
171 sp<IBinder> getResponsiveWindowToken() {
172 std::unique_lock lock(mLock);
173 android::base::ScopedLockAssertion assumeLocked(mLock);
174 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
175 }
176
177 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
178 std::unique_lock lock(mLock);
179 android::base::ScopedLockAssertion assumeLocked(mLock);
180 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
181 }
182
183 int32_t getResponsiveMonitorPid() {
184 std::unique_lock lock(mLock);
185 android::base::ScopedLockAssertion assumeLocked(mLock);
186 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500187 }
188
189 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
190 // for a specific container to become non-empty. When the container is non-empty, return the
191 // first entry from the container and erase it.
192 template <class T>
193 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
194 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
195 const std::chrono::time_point start = std::chrono::steady_clock::now();
196 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700197
198 // If there is an ANR, Dispatcher won't be idle because there are still events
199 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
200 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500201 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
202 // to provide it some time to act. 100ms seems reasonable.
203 mNotifyAnr.wait_for(lock, timeToWait,
204 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700205 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500206 if (storage.empty()) {
207 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000208 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700209 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700210 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
211 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700212 if (std::chrono::abs(timeout - waited) > 100ms) {
213 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
214 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
215 << "ms, but waited "
216 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
217 << "ms instead";
218 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500219 T token = storage.front();
220 storage.pop();
221 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700222 }
223
224 void assertNotifyAnrWasNotCalled() {
225 std::scoped_lock lock(mLock);
226 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000227 ASSERT_TRUE(mAnrWindowTokens.empty());
228 ASSERT_TRUE(mAnrMonitorPids.empty());
229 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500230 << "ANR was not called, but please also consume the 'connection is responsive' "
231 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000232 ASSERT_TRUE(mResponsiveMonitorPids.empty())
233 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
234 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700235 }
236
Garfield Tan1c7bc862020-01-28 13:24:04 -0800237 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
238 mConfig.keyRepeatTimeout = timeout;
239 mConfig.keyRepeatDelay = delay;
240 }
241
Prabir Pradhan99987712020-11-10 18:43:05 -0800242 void waitForSetPointerCapture(bool enabled) {
243 std::unique_lock lock(mLock);
244 base::ScopedLockAssertion assumeLocked(mLock);
245
246 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
247 [this, enabled]() REQUIRES(mLock) {
248 return mPointerCaptureEnabled &&
249 *mPointerCaptureEnabled ==
250 enabled;
251 })) {
252 FAIL() << "Timed out waiting for setPointerCapture(" << enabled << ") to be called.";
253 }
254 mPointerCaptureEnabled.reset();
255 }
256
257 void assertSetPointerCaptureNotCalled() {
258 std::unique_lock lock(mLock);
259 base::ScopedLockAssertion assumeLocked(mLock);
260
261 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
262 FAIL() << "Expected setPointerCapture(enabled) to not be called, but was called. "
263 "enabled = "
264 << *mPointerCaptureEnabled;
265 }
266 mPointerCaptureEnabled.reset();
267 }
268
arthurhungf452d0b2021-01-06 00:19:52 +0800269 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
270 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800271 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800272 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800273 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800274 }
275
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700277 std::mutex mLock;
278 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
279 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
280 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
281 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800282
Prabir Pradhan99987712020-11-10 18:43:05 -0800283 std::condition_variable mPointerCaptureChangedCondition;
284 std::optional<bool> mPointerCaptureEnabled GUARDED_BY(mLock);
285
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700286 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700287 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000288 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
289 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
290 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
291 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700292 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700293
arthurhungf452d0b2021-01-06 00:19:52 +0800294 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800295 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800296
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600297 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700298 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800299 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800300 }
301
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000302 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700303 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000304 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700305 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500306 }
307
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000308 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500309 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000310 mAnrMonitorPids.push(pid);
311 mNotifyAnr.notify_all();
312 }
313
314 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
315 std::scoped_lock lock(mLock);
316 mResponsiveWindowTokens.push(connectionToken);
317 mNotifyAnr.notify_all();
318 }
319
320 void notifyMonitorResponsive(int32_t pid) override {
321 std::scoped_lock lock(mLock);
322 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500323 mNotifyAnr.notify_all();
324 }
325
326 void notifyNoFocusedWindowAnr(
327 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
328 std::scoped_lock lock(mLock);
329 mAnrApplications.push(applicationHandle);
330 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331 }
332
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600333 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600335 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700336
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600337 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700338 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
339 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
340 const std::vector<float>& values) override {}
341
342 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
343 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000344
Chris Yefb552902021-02-03 17:18:37 -0800345 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
346
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600347 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800348 *outConfig = mConfig;
349 }
350
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600351 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700352 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800353 switch (inputEvent->getType()) {
354 case AINPUT_EVENT_TYPE_KEY: {
355 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800356 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800357 break;
358 }
359
360 case AINPUT_EVENT_TYPE_MOTION: {
361 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800362 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800363 break;
364 }
365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800366 return true;
367 }
368
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600369 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800370
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600371 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600373 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800374 return 0;
375 }
376
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600377 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378 return false;
379 }
380
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600381 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
382 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700383 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800384 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
385 * essentially a passthrough for notifySwitch.
386 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800387 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388 }
389
Sean Stoutb4e0a592021-02-23 07:34:53 -0800390 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800392 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
393 return pid == INJECTOR_PID && uid == INJECTOR_UID;
394 }
Jackal Guof9696682018-10-05 12:23:23 +0800395
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600396 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700397 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700398 mOnPointerDownToken = newToken;
399 }
400
Prabir Pradhan99987712020-11-10 18:43:05 -0800401 void setPointerCapture(bool enabled) override {
402 std::scoped_lock lock(mLock);
403 mPointerCaptureEnabled = {enabled};
404 mPointerCaptureChangedCondition.notify_all();
405 }
406
arthurhungf452d0b2021-01-06 00:19:52 +0800407 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
408 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800409 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800410 mDropTargetWindowToken = token;
411 }
412
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800413 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
414 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700415 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800416 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
417 ASSERT_EQ(mFilteredEvent->getType(), type);
418
419 if (type == AINPUT_EVENT_TYPE_KEY) {
420 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
421 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
422 EXPECT_EQ(keyEvent.getAction(), action);
423 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
424 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
425 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
426 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
427 EXPECT_EQ(motionEvent.getAction(), action);
428 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
429 } else {
430 FAIL() << "Unknown type: " << type;
431 }
432
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800433 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435};
436
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437// --- InputDispatcherTest ---
438
439class InputDispatcherTest : public testing::Test {
440protected:
441 sp<FakeInputDispatcherPolicy> mFakePolicy;
442 sp<InputDispatcher> mDispatcher;
443
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000444 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445 mFakePolicy = new FakeInputDispatcherPolicy();
446 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800447 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000448 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700449 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 }
451
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000452 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700453 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454 mFakePolicy.clear();
455 mDispatcher.clear();
456 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700457
458 /**
459 * Used for debugging when writing the test
460 */
461 void dumpDispatcherState() {
462 std::string dump;
463 mDispatcher->dump(dump);
464 std::stringstream ss(dump);
465 std::string to;
466
467 while (std::getline(ss, to, '\n')) {
468 ALOGE("%s", to.c_str());
469 }
470 }
Vishnu Nair958da932020-08-21 17:12:37 -0700471
472 void setFocusedWindow(const sp<InputWindowHandle>& window,
473 const sp<InputWindowHandle>& focusedWindow = nullptr) {
474 FocusRequest request;
475 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000476 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700477 if (focusedWindow) {
478 request.focusedToken = focusedWindow->getToken();
479 }
480 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
481 request.displayId = window->getInfo()->displayId;
482 mDispatcher->setFocusedWindow(request);
483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484};
485
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
487 KeyEvent event;
488
489 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800490 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
491 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600492 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
493 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800494 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700495 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800496 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 << "Should reject key events with undefined action.";
498
499 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800500 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
501 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600502 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800503 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700504 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800505 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 << "Should reject key events with ACTION_MULTIPLE.";
507}
508
509TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
510 MotionEvent event;
511 PointerProperties pointerProperties[MAX_POINTERS + 1];
512 PointerCoords pointerCoords[MAX_POINTERS + 1];
513 for (int i = 0; i <= MAX_POINTERS; i++) {
514 pointerProperties[i].clear();
515 pointerProperties[i].id = i;
516 pointerCoords[i].clear();
517 }
518
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800519 // Some constants commonly used below
520 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
521 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
522 constexpr int32_t metaState = AMETA_NONE;
523 constexpr MotionClassification classification = MotionClassification::NONE;
524
chaviw9eaa22c2020-07-01 16:21:27 -0700525 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800527 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700528 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
529 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700530 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
531 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700532 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800533 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700534 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800535 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536 << "Should reject motion events with undefined action.";
537
538 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800539 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700540 AMOTION_EVENT_ACTION_POINTER_DOWN |
541 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700542 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
543 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700544 AMOTION_EVENT_INVALID_DISPLAY_SIZE, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
chaviw9eaa22c2020-07-01 16:21:27 -0700545 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
546 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800547 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700548 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800549 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 << "Should reject motion events with pointer down index too large.";
551
Garfield Tanfbe732e2020-01-24 11:26:14 -0800552 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700553 AMOTION_EVENT_ACTION_POINTER_DOWN |
554 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700555 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
556 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700557 AMOTION_EVENT_INVALID_DISPLAY_SIZE, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
chaviw9eaa22c2020-07-01 16:21:27 -0700558 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
559 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800560 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700561 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800562 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 << "Should reject motion events with pointer down index too small.";
564
565 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800566 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700567 AMOTION_EVENT_ACTION_POINTER_UP |
568 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700569 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
570 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700571 AMOTION_EVENT_INVALID_DISPLAY_SIZE, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
chaviw9eaa22c2020-07-01 16:21:27 -0700572 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
573 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800574 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700575 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800576 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 << "Should reject motion events with pointer up index too large.";
578
Garfield Tanfbe732e2020-01-24 11:26:14 -0800579 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700580 AMOTION_EVENT_ACTION_POINTER_UP |
581 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700582 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
583 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700584 AMOTION_EVENT_INVALID_DISPLAY_SIZE, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
chaviw9eaa22c2020-07-01 16:21:27 -0700585 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
586 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800587 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700588 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800589 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 << "Should reject motion events with pointer up index too small.";
591
592 // Rejects motion events with invalid number of pointers.
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,
Evan Rosky84f07f02021-04-16 10:42:42 -0700596 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
597 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700598 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800599 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700600 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800601 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 << "Should reject motion events with 0 pointers.";
603
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,
Evan Rosky84f07f02021-04-16 10:42:42 -0700607 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
608 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700609 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800610 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700611 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800612 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613 << "Should reject motion events with more than MAX_POINTERS pointers.";
614
615 // Rejects motion events with invalid pointer ids.
616 pointerProperties[0].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,
Evan Rosky84f07f02021-04-16 10:42:42 -0700620 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
621 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700622 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800623 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700624 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800625 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 << "Should reject motion events with pointer ids less than 0.";
627
628 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800629 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
630 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700631 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700632 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
633 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700634 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800635 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700636 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800637 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
639
640 // Rejects motion events with duplicate pointer ids.
641 pointerProperties[0].id = 1;
642 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800643 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
644 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700645 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700646 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
647 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700648 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800649 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700650 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800651 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800652 << "Should reject motion events with duplicate pointer ids.";
653}
654
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800655/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
656
657TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
658 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800659 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800660 mDispatcher->notifyConfigurationChanged(&args);
661 ASSERT_TRUE(mDispatcher->waitForIdle());
662
663 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
664}
665
666TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800667 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
668 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800669 mDispatcher->notifySwitch(&args);
670
671 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
672 args.policyFlags |= POLICY_FLAG_TRUSTED;
673 mFakePolicy->assertNotifySwitchWasCalled(args);
674}
675
Arthur Hungb92218b2018-08-14 12:00:21 +0800676// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700677static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700678static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800679
680class FakeApplicationHandle : public InputApplicationHandle {
681public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700682 FakeApplicationHandle() {
683 mInfo.name = "Fake Application";
684 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500685 mInfo.dispatchingTimeoutMillis =
686 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700687 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800688 virtual ~FakeApplicationHandle() {}
689
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000690 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700691
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500692 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
693 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700694 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800695};
696
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800697class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800698public:
Garfield Tan15601662020-09-22 15:32:38 -0700699 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800700 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700701 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800702 }
703
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800704 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700705 InputEvent* event;
706 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
707 if (!consumeSeq) {
708 return nullptr;
709 }
710 finishEvent(*consumeSeq);
711 return event;
712 }
713
714 /**
715 * Receive an event without acknowledging it.
716 * Return the sequence number that could later be used to send finished signal.
717 */
718 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800719 uint32_t consumeSeq;
720 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800721
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800722 std::chrono::time_point start = std::chrono::steady_clock::now();
723 status_t status = WOULD_BLOCK;
724 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800725 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800726 &event);
727 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
728 if (elapsed > 100ms) {
729 break;
730 }
731 }
732
733 if (status == WOULD_BLOCK) {
734 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700735 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800736 }
737
738 if (status != OK) {
739 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700740 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800741 }
742 if (event == nullptr) {
743 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700744 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800745 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700746 if (outEvent != nullptr) {
747 *outEvent = event;
748 }
749 return consumeSeq;
750 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800751
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700752 /**
753 * To be used together with "receiveEvent" to complete the consumption of an event.
754 */
755 void finishEvent(uint32_t consumeSeq) {
756 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
757 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800758 }
759
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000760 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
761 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
762 ASSERT_EQ(OK, status);
763 }
764
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000765 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
766 std::optional<int32_t> expectedDisplayId,
767 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800768 InputEvent* event = consume();
769
770 ASSERT_NE(nullptr, event) << mName.c_str()
771 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800772 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700773 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800774 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800775
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000776 if (expectedDisplayId.has_value()) {
777 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
778 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800779
Tiger Huang8664f8c2018-10-11 19:14:35 +0800780 switch (expectedEventType) {
781 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800782 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
783 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000784 if (expectedFlags.has_value()) {
785 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
786 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800787 break;
788 }
789 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800790 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
791 EXPECT_EQ(expectedAction, motionEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000792 if (expectedFlags.has_value()) {
793 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
794 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800795 break;
796 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100797 case AINPUT_EVENT_TYPE_FOCUS: {
798 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
799 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800800 case AINPUT_EVENT_TYPE_CAPTURE: {
801 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
802 }
arthurhungb89ccb02020-12-30 16:19:01 +0800803 case AINPUT_EVENT_TYPE_DRAG: {
804 FAIL() << "Use 'consumeDragEvent' for DRAG events";
805 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800806 default: {
807 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
808 }
809 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800810 }
811
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100812 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
813 InputEvent* event = consume();
814 ASSERT_NE(nullptr, event) << mName.c_str()
815 << ": consumer should have returned non-NULL event.";
816 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
817 << "Got " << inputEventTypeToString(event->getType())
818 << " event instead of FOCUS event";
819
820 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
821 << mName.c_str() << ": event displayId should always be NONE.";
822
823 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
824 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
825 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
826 }
827
Prabir Pradhan99987712020-11-10 18:43:05 -0800828 void consumeCaptureEvent(bool hasCapture) {
829 const InputEvent* event = consume();
830 ASSERT_NE(nullptr, event) << mName.c_str()
831 << ": consumer should have returned non-NULL event.";
832 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
833 << "Got " << inputEventTypeToString(event->getType())
834 << " event instead of CAPTURE event";
835
836 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
837 << mName.c_str() << ": event displayId should always be NONE.";
838
839 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
840 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
841 }
842
arthurhungb89ccb02020-12-30 16:19:01 +0800843 void consumeDragEvent(bool isExiting, float x, float y) {
844 const InputEvent* event = consume();
845 ASSERT_NE(nullptr, event) << mName.c_str()
846 << ": consumer should have returned non-NULL event.";
847 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
848 << "Got " << inputEventTypeToString(event->getType())
849 << " event instead of DRAG event";
850
851 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
852 << mName.c_str() << ": event displayId should always be NONE.";
853
854 const auto& dragEvent = static_cast<const DragEvent&>(*event);
855 EXPECT_EQ(isExiting, dragEvent.isExiting());
856 EXPECT_EQ(x, dragEvent.getX());
857 EXPECT_EQ(y, dragEvent.getY());
858 }
859
chaviwd1c23182019-12-20 18:44:56 -0800860 void assertNoEvents() {
861 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700862 if (event == nullptr) {
863 return;
864 }
865 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
866 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
867 ADD_FAILURE() << "Received key event "
868 << KeyEvent::actionToString(keyEvent.getAction());
869 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
870 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
871 ADD_FAILURE() << "Received motion event "
872 << MotionEvent::actionToString(motionEvent.getAction());
873 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
874 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
875 ADD_FAILURE() << "Received focus event, hasFocus = "
876 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800877 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
878 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
879 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
880 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700881 }
882 FAIL() << mName.c_str()
883 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800884 }
885
886 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
887
888protected:
889 std::unique_ptr<InputConsumer> mConsumer;
890 PreallocatedInputEventFactory mEventFactory;
891
892 std::string mName;
893};
894
895class FakeWindowHandle : public InputWindowHandle {
896public:
897 static const int32_t WIDTH = 600;
898 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800899
Chris Yea209fde2020-07-22 13:54:51 -0700900 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800901 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500902 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800903 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500904 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700905 base::Result<std::unique_ptr<InputChannel>> channel =
906 dispatcher->createInputChannel(name);
907 token = (*channel)->getConnectionToken();
908 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800909 }
910
911 inputApplicationHandle->updateInfo();
912 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
913
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500914 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700915 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800916 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100917 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500918 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000919 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800920 mInfo.frameLeft = 0;
921 mInfo.frameTop = 0;
922 mInfo.frameRight = WIDTH;
923 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700924 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800925 mInfo.globalScaleFactor = 1.0;
926 mInfo.touchableRegion.clear();
927 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
928 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700929 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800930 mInfo.hasWallpaper = false;
931 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800932 mInfo.ownerPid = INJECTOR_PID;
933 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800934 mInfo.displayId = displayId;
935 }
936
937 virtual bool updateInfo() { return true; }
938
Vishnu Nair47074b82020-08-14 11:54:47 -0700939 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800940
Vishnu Nair958da932020-08-21 17:12:37 -0700941 void setVisible(bool visible) { mInfo.visible = visible; }
942
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700943 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500944 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700945 }
946
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700947 void setPaused(bool paused) { mInfo.paused = paused; }
948
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000949 void setAlpha(float alpha) { mInfo.alpha = alpha; }
950
951 void setTouchOcclusionMode(android::os::TouchOcclusionMode mode) {
952 mInfo.touchOcclusionMode = mode;
953 }
954
Bernardo Rufino7393d172021-02-26 13:56:11 +0000955 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
956
chaviwd1c23182019-12-20 18:44:56 -0800957 void setFrame(const Rect& frame) {
958 mInfo.frameLeft = frame.left;
959 mInfo.frameTop = frame.top;
960 mInfo.frameRight = frame.right;
961 mInfo.frameBottom = frame.bottom;
arthurhungb89ccb02020-12-30 16:19:01 +0800962 mInfo.transform.set(-frame.left, -frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800963 mInfo.touchableRegion.clear();
964 mInfo.addTouchableRegion(frame);
965 }
966
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000967 void addFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags |= flags; }
968
Michael Wright44753b12020-07-08 13:48:11 +0100969 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800970
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500971 void setInputFeatures(InputWindowInfo::Feature features) { mInfo.inputFeatures = features; }
972
chaviw9eaa22c2020-07-01 16:21:27 -0700973 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
974 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
975 }
976
977 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700978
yunho.shinf4a80b82020-11-16 21:13:57 +0900979 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
980
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800981 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
982 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
983 expectedFlags);
984 }
985
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700986 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
987 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
988 }
989
Svet Ganov5d3bc372020-01-26 23:11:07 -0800990 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000991 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800992 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
993 expectedFlags);
994 }
995
996 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000997 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800998 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
999 expectedFlags);
1000 }
1001
1002 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001003 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001004 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1005 }
1006
1007 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1008 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001009 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1010 expectedFlags);
1011 }
1012
Svet Ganov5d3bc372020-01-26 23:11:07 -08001013 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001014 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1015 int32_t expectedFlags = 0) {
1016 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1017 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001018 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1019 }
1020
1021 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001022 int32_t expectedFlags = 0) {
1023 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1024 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001025 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1026 }
1027
1028 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001029 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001030 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1031 expectedFlags);
1032 }
1033
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001034 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1035 int32_t expectedFlags = 0) {
1036 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1037 expectedFlags);
1038 }
1039
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001040 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1041 ASSERT_NE(mInputReceiver, nullptr)
1042 << "Cannot consume events from a window with no receiver";
1043 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1044 }
1045
Prabir Pradhan99987712020-11-10 18:43:05 -08001046 void consumeCaptureEvent(bool hasCapture) {
1047 ASSERT_NE(mInputReceiver, nullptr)
1048 << "Cannot consume events from a window with no receiver";
1049 mInputReceiver->consumeCaptureEvent(hasCapture);
1050 }
1051
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001052 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1053 std::optional<int32_t> expectedDisplayId,
1054 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001055 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1056 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1057 expectedFlags);
1058 }
1059
arthurhungb89ccb02020-12-30 16:19:01 +08001060 void consumeDragEvent(bool isExiting, float x, float y) {
1061 mInputReceiver->consumeDragEvent(isExiting, x, y);
1062 }
1063
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001064 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001065 if (mInputReceiver == nullptr) {
1066 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1067 return std::nullopt;
1068 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001069 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001070 }
1071
1072 void finishEvent(uint32_t sequenceNum) {
1073 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1074 mInputReceiver->finishEvent(sequenceNum);
1075 }
1076
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001077 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1078 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1079 mInputReceiver->sendTimeline(inputEventId, timeline);
1080 }
1081
chaviwaf87b3e2019-10-01 16:59:28 -07001082 InputEvent* consume() {
1083 if (mInputReceiver == nullptr) {
1084 return nullptr;
1085 }
1086 return mInputReceiver->consume();
1087 }
1088
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001089 MotionEvent* consumeMotion() {
1090 InputEvent* event = consume();
1091 if (event == nullptr) {
1092 ADD_FAILURE() << "Consume failed : no event";
1093 return nullptr;
1094 }
1095 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1096 ADD_FAILURE() << "Instead of motion event, got "
1097 << inputEventTypeToString(event->getType());
1098 return nullptr;
1099 }
1100 return static_cast<MotionEvent*>(event);
1101 }
1102
Arthur Hungb92218b2018-08-14 12:00:21 +08001103 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001104 if (mInputReceiver == nullptr &&
1105 mInfo.inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL)) {
1106 return; // Can't receive events if the window does not have input channel
1107 }
1108 ASSERT_NE(nullptr, mInputReceiver)
1109 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001110 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001111 }
1112
chaviwaf87b3e2019-10-01 16:59:28 -07001113 sp<IBinder> getToken() { return mInfo.token; }
1114
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001115 const std::string& getName() { return mName; }
1116
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001117 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1118 mInfo.ownerPid = ownerPid;
1119 mInfo.ownerUid = ownerUid;
1120 }
1121
chaviwd1c23182019-12-20 18:44:56 -08001122private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001123 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001124 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001125 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001126};
1127
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001128std::atomic<int32_t> FakeWindowHandle::sId{1};
1129
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001130static InputEventInjectionResult injectKey(
1131 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1132 int32_t displayId = ADISPLAY_ID_NONE,
1133 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001134 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1135 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001136 KeyEvent event;
1137 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1138
1139 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001140 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001141 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1142 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001143
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001144 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1145 if (!allowKeyRepeat) {
1146 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1147 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001148 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001149 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001150 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001151}
1152
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001153static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1154 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001155 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1156}
1157
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001158// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1159// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1160// has to be woken up to process the repeating key.
1161static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1162 int32_t displayId = ADISPLAY_ID_NONE) {
1163 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1164 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1165 /* allowKeyRepeat */ false);
1166}
1167
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001168static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1169 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001170 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1171}
1172
Garfield Tandf26e862020-07-01 20:18:19 -07001173class PointerBuilder {
1174public:
1175 PointerBuilder(int32_t id, int32_t toolType) {
1176 mProperties.clear();
1177 mProperties.id = id;
1178 mProperties.toolType = toolType;
1179 mCoords.clear();
1180 }
1181
1182 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1183
1184 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1185
1186 PointerBuilder& axis(int32_t axis, float value) {
1187 mCoords.setAxisValue(axis, value);
1188 return *this;
1189 }
1190
1191 PointerProperties buildProperties() const { return mProperties; }
1192
1193 PointerCoords buildCoords() const { return mCoords; }
1194
1195private:
1196 PointerProperties mProperties;
1197 PointerCoords mCoords;
1198};
1199
1200class MotionEventBuilder {
1201public:
1202 MotionEventBuilder(int32_t action, int32_t source) {
1203 mAction = action;
1204 mSource = source;
1205 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1206 }
1207
1208 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1209 mEventTime = eventTime;
1210 return *this;
1211 }
1212
1213 MotionEventBuilder& displayId(int32_t displayId) {
1214 mDisplayId = displayId;
1215 return *this;
1216 }
1217
1218 MotionEventBuilder& actionButton(int32_t actionButton) {
1219 mActionButton = actionButton;
1220 return *this;
1221 }
1222
arthurhung6d4bed92021-03-17 11:59:33 +08001223 MotionEventBuilder& buttonState(int32_t buttonState) {
1224 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001225 return *this;
1226 }
1227
1228 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1229 mRawXCursorPosition = rawXCursorPosition;
1230 return *this;
1231 }
1232
1233 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1234 mRawYCursorPosition = rawYCursorPosition;
1235 return *this;
1236 }
1237
1238 MotionEventBuilder& pointer(PointerBuilder pointer) {
1239 mPointers.push_back(pointer);
1240 return *this;
1241 }
1242
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001243 MotionEventBuilder& addFlag(uint32_t flags) {
1244 mFlags |= flags;
1245 return *this;
1246 }
1247
Garfield Tandf26e862020-07-01 20:18:19 -07001248 MotionEvent build() {
1249 std::vector<PointerProperties> pointerProperties;
1250 std::vector<PointerCoords> pointerCoords;
1251 for (const PointerBuilder& pointer : mPointers) {
1252 pointerProperties.push_back(pointer.buildProperties());
1253 pointerCoords.push_back(pointer.buildCoords());
1254 }
1255
1256 // Set mouse cursor position for the most common cases to avoid boilerplate.
1257 if (mSource == AINPUT_SOURCE_MOUSE &&
1258 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1259 mPointers.size() == 1) {
1260 mRawXCursorPosition = pointerCoords[0].getX();
1261 mRawYCursorPosition = pointerCoords[0].getY();
1262 }
1263
1264 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001265 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001266 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001267 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001268 mButtonState, MotionClassification::NONE, identityTransform,
1269 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07001270 mRawYCursorPosition, mDisplayWidth, mDisplayHeight, mEventTime, mEventTime,
1271 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001272
1273 return event;
1274 }
1275
1276private:
1277 int32_t mAction;
1278 int32_t mSource;
1279 nsecs_t mEventTime;
1280 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1281 int32_t mActionButton{0};
1282 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001283 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001284 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1285 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
Evan Rosky84f07f02021-04-16 10:42:42 -07001286 int32_t mDisplayWidth{AMOTION_EVENT_INVALID_DISPLAY_SIZE};
1287 int32_t mDisplayHeight{AMOTION_EVENT_INVALID_DISPLAY_SIZE};
Garfield Tandf26e862020-07-01 20:18:19 -07001288
1289 std::vector<PointerBuilder> mPointers;
1290};
1291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001293 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1294 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001295 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001296 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1297 injectionTimeout,
1298 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1299}
1300
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001301static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001302 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1303 const PointF& position,
1304 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001305 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1306 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001307 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001308 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001309 MotionEvent event = MotionEventBuilder(action, source)
1310 .displayId(displayId)
1311 .eventTime(eventTime)
1312 .rawXCursorPosition(cursorPosition.x)
1313 .rawYCursorPosition(cursorPosition.y)
1314 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1315 .x(position.x)
1316 .y(position.y))
1317 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001318
1319 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001320 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001321}
1322
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001323static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1324 int32_t source, int32_t displayId,
1325 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001326 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001327}
1328
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001329static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1330 int32_t source, int32_t displayId,
1331 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001332 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001333}
1334
Jackal Guof9696682018-10-05 12:23:23 +08001335static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1336 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1337 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001338 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1339 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1340 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001341
1342 return args;
1343}
1344
chaviwd1c23182019-12-20 18:44:56 -08001345static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1346 const std::vector<PointF>& points) {
1347 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001348 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1349 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1350 }
1351
chaviwd1c23182019-12-20 18:44:56 -08001352 PointerProperties pointerProperties[pointerCount];
1353 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001354
chaviwd1c23182019-12-20 18:44:56 -08001355 for (size_t i = 0; i < pointerCount; i++) {
1356 pointerProperties[i].clear();
1357 pointerProperties[i].id = i;
1358 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001359
chaviwd1c23182019-12-20 18:44:56 -08001360 pointerCoords[i].clear();
1361 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1362 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1363 }
Jackal Guof9696682018-10-05 12:23:23 +08001364
1365 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1366 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001367 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001368 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1369 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001370 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1371 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001372 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1373 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001374
1375 return args;
1376}
1377
chaviwd1c23182019-12-20 18:44:56 -08001378static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1379 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1380}
1381
Prabir Pradhan99987712020-11-10 18:43:05 -08001382static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(bool enabled) {
1383 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), enabled);
1384}
1385
Arthur Hungb92218b2018-08-14 12:00:21 +08001386TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001387 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001388 sp<FakeWindowHandle> window =
1389 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001390
Arthur Hung72d8dc32020-03-28 00:48:39 +00001391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1393 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1394 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001395
1396 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001397 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001398}
1399
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001400/**
1401 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1402 * To ensure that window receives only events that were directly inside of it, add
1403 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1404 * when finding touched windows.
1405 * This test serves as a sanity check for the next test, where setInputWindows is
1406 * called twice.
1407 */
1408TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001409 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001410 sp<FakeWindowHandle> window =
1411 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1412 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001413 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001414
1415 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001417 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1418 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001419 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001420
1421 // Window should receive motion event.
1422 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1423}
1424
1425/**
1426 * Calling setInputWindows twice, with the same info, should not cause any issues.
1427 * To ensure that window receives only events that were directly inside of it, add
1428 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1429 * when finding touched windows.
1430 */
1431TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001432 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001433 sp<FakeWindowHandle> window =
1434 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1435 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001436 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001437
1438 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001441 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1442 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001443 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001444
1445 // Window should receive motion event.
1446 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1447}
1448
Arthur Hungb92218b2018-08-14 12:00:21 +08001449// The foreground window should receive the first touch down event.
1450TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001451 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001452 sp<FakeWindowHandle> windowTop =
1453 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1454 sp<FakeWindowHandle> windowSecond =
1455 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001456
Arthur Hung72d8dc32020-03-28 00:48:39 +00001457 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001458 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1459 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001461
1462 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001463 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001464 windowSecond->assertNoEvents();
1465}
1466
Garfield Tandf26e862020-07-01 20:18:19 -07001467TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001468 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001469 sp<FakeWindowHandle> windowLeft =
1470 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1471 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001472 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001473 sp<FakeWindowHandle> windowRight =
1474 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1475 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001476 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001477
1478 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1479
1480 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1481
1482 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001483 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001484 injectMotionEvent(mDispatcher,
1485 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1486 AINPUT_SOURCE_MOUSE)
1487 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1488 .x(900)
1489 .y(400))
1490 .build()));
1491 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1492 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1493 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1494 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1495
1496 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001497 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001498 injectMotionEvent(mDispatcher,
1499 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1500 AINPUT_SOURCE_MOUSE)
1501 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1502 .x(300)
1503 .y(400))
1504 .build()));
1505 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1506 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1507 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1508 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1509 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1510 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1511
1512 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001514 injectMotionEvent(mDispatcher,
1515 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1516 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1517 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1518 .x(300)
1519 .y(400))
1520 .build()));
1521 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1522
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001524 injectMotionEvent(mDispatcher,
1525 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1526 AINPUT_SOURCE_MOUSE)
1527 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1528 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1529 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1530 .x(300)
1531 .y(400))
1532 .build()));
1533 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1534 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1535
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001537 injectMotionEvent(mDispatcher,
1538 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1539 AINPUT_SOURCE_MOUSE)
1540 .buttonState(0)
1541 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1542 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1543 .x(300)
1544 .y(400))
1545 .build()));
1546 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1547 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1548
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001550 injectMotionEvent(mDispatcher,
1551 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1552 .buttonState(0)
1553 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1554 .x(300)
1555 .y(400))
1556 .build()));
1557 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1558
1559 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001561 injectMotionEvent(mDispatcher,
1562 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1563 AINPUT_SOURCE_MOUSE)
1564 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1565 .x(900)
1566 .y(400))
1567 .build()));
1568 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1569 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1570 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1571 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1572 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1573 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1574}
1575
1576// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1577// directly in this test.
1578TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001579 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001580 sp<FakeWindowHandle> window =
1581 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1582 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001583 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001584
1585 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1586
1587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1588
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001590 injectMotionEvent(mDispatcher,
1591 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1592 AINPUT_SOURCE_MOUSE)
1593 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1594 .x(300)
1595 .y(400))
1596 .build()));
1597 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1598 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1599
1600 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001602 injectMotionEvent(mDispatcher,
1603 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1604 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1605 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1606 .x(300)
1607 .y(400))
1608 .build()));
1609 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1610
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001612 injectMotionEvent(mDispatcher,
1613 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1614 AINPUT_SOURCE_MOUSE)
1615 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1616 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1617 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1618 .x(300)
1619 .y(400))
1620 .build()));
1621 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1622 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1623
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001624 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001625 injectMotionEvent(mDispatcher,
1626 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1627 AINPUT_SOURCE_MOUSE)
1628 .buttonState(0)
1629 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1630 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1631 .x(300)
1632 .y(400))
1633 .build()));
1634 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1635 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1636
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001638 injectMotionEvent(mDispatcher,
1639 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1640 .buttonState(0)
1641 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1642 .x(300)
1643 .y(400))
1644 .build()));
1645 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1646
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001647 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001648 injectMotionEvent(mDispatcher,
1649 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1650 AINPUT_SOURCE_MOUSE)
1651 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1652 .x(300)
1653 .y(400))
1654 .build()));
1655 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1656 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1657}
1658
Garfield Tan00f511d2019-06-12 16:55:40 -07001659TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001660 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001661
1662 sp<FakeWindowHandle> windowLeft =
1663 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1664 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001665 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001666 sp<FakeWindowHandle> windowRight =
1667 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1668 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001669 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001670
1671 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1672
Arthur Hung72d8dc32020-03-28 00:48:39 +00001673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001674
1675 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1676 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001678 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001679 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001680 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001681 windowRight->assertNoEvents();
1682}
1683
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001684TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001685 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001686 sp<FakeWindowHandle> window =
1687 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001688 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001689
Arthur Hung72d8dc32020-03-28 00:48:39 +00001690 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001691 setFocusedWindow(window);
1692
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001693 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001694
1695 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1696 mDispatcher->notifyKey(&keyArgs);
1697
1698 // Window should receive key down event.
1699 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1700
1701 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1702 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001703 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001704 mDispatcher->notifyDeviceReset(&args);
1705 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1706 AKEY_EVENT_FLAG_CANCELED);
1707}
1708
1709TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001710 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001711 sp<FakeWindowHandle> window =
1712 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1713
Arthur Hung72d8dc32020-03-28 00:48:39 +00001714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001715
1716 NotifyMotionArgs motionArgs =
1717 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1718 ADISPLAY_ID_DEFAULT);
1719 mDispatcher->notifyMotion(&motionArgs);
1720
1721 // Window should receive motion down event.
1722 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1723
1724 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1725 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001726 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001727 mDispatcher->notifyDeviceReset(&args);
1728 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1729 0 /*expectedFlags*/);
1730}
1731
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001732using TransferFunction =
1733 std::function<bool(sp<InputDispatcher> dispatcher, sp<IBinder>, sp<IBinder>)>;
1734
1735class TransferTouchFixture : public InputDispatcherTest,
1736 public ::testing::WithParamInterface<TransferFunction> {};
1737
1738TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001739 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001740
1741 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001742 sp<FakeWindowHandle> firstWindow =
1743 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1744 sp<FakeWindowHandle> secondWindow =
1745 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001746
1747 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001749
1750 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001751 NotifyMotionArgs downMotionArgs =
1752 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1753 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001754 mDispatcher->notifyMotion(&downMotionArgs);
1755 // Only the first window should get the down event
1756 firstWindow->consumeMotionDown();
1757 secondWindow->assertNoEvents();
1758
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001759 // Transfer touch to the second window
1760 TransferFunction f = GetParam();
1761 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1762 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001763 // The first window gets cancel and the second gets down
1764 firstWindow->consumeMotionCancel();
1765 secondWindow->consumeMotionDown();
1766
1767 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001768 NotifyMotionArgs upMotionArgs =
1769 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1770 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001771 mDispatcher->notifyMotion(&upMotionArgs);
1772 // The first window gets no events and the second gets up
1773 firstWindow->assertNoEvents();
1774 secondWindow->consumeMotionUp();
1775}
1776
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001777TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001778 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001779
1780 PointF touchPoint = {10, 10};
1781
1782 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001783 sp<FakeWindowHandle> firstWindow =
1784 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1785 sp<FakeWindowHandle> secondWindow =
1786 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001787
1788 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001790
1791 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001792 NotifyMotionArgs downMotionArgs =
1793 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1794 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001795 mDispatcher->notifyMotion(&downMotionArgs);
1796 // Only the first window should get the down event
1797 firstWindow->consumeMotionDown();
1798 secondWindow->assertNoEvents();
1799
1800 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001801 NotifyMotionArgs pointerDownMotionArgs =
1802 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1803 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1804 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1805 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001806 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1807 // Only the first window should get the pointer down event
1808 firstWindow->consumeMotionPointerDown(1);
1809 secondWindow->assertNoEvents();
1810
1811 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001812 TransferFunction f = GetParam();
1813 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1814 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001815 // The first window gets cancel and the second gets down and pointer down
1816 firstWindow->consumeMotionCancel();
1817 secondWindow->consumeMotionDown();
1818 secondWindow->consumeMotionPointerDown(1);
1819
1820 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001821 NotifyMotionArgs pointerUpMotionArgs =
1822 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1823 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1824 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1825 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001826 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1827 // The first window gets nothing and the second gets pointer up
1828 firstWindow->assertNoEvents();
1829 secondWindow->consumeMotionPointerUp(1);
1830
1831 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001832 NotifyMotionArgs upMotionArgs =
1833 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1834 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001835 mDispatcher->notifyMotion(&upMotionArgs);
1836 // The first window gets nothing and the second gets up
1837 firstWindow->assertNoEvents();
1838 secondWindow->consumeMotionUp();
1839}
1840
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001841// For the cases of single pointer touch and two pointers non-split touch, the api's
1842// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
1843// for the case where there are multiple pointers split across several windows.
1844INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
1845 ::testing::Values(
1846 [&](sp<InputDispatcher> dispatcher, sp<IBinder> /*ignored*/,
1847 sp<IBinder> destChannelToken) {
1848 return dispatcher->transferTouch(destChannelToken);
1849 },
1850 [&](sp<InputDispatcher> dispatcher, sp<IBinder> from,
1851 sp<IBinder> to) {
1852 return dispatcher->transferTouchFocus(from, to,
1853 false /*isDragAndDrop*/);
1854 }));
1855
Svet Ganov5d3bc372020-01-26 23:11:07 -08001856TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001857 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001858
1859 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001860 sp<FakeWindowHandle> firstWindow =
1861 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001862 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001863 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1864 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001865
1866 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001867 sp<FakeWindowHandle> secondWindow =
1868 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001869 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001870 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1871 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001872
1873 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001874 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001875
1876 PointF pointInFirst = {300, 200};
1877 PointF pointInSecond = {300, 600};
1878
1879 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001880 NotifyMotionArgs firstDownMotionArgs =
1881 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1882 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001883 mDispatcher->notifyMotion(&firstDownMotionArgs);
1884 // Only the first window should get the down event
1885 firstWindow->consumeMotionDown();
1886 secondWindow->assertNoEvents();
1887
1888 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001889 NotifyMotionArgs secondDownMotionArgs =
1890 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1891 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1892 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1893 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001894 mDispatcher->notifyMotion(&secondDownMotionArgs);
1895 // The first window gets a move and the second a down
1896 firstWindow->consumeMotionMove();
1897 secondWindow->consumeMotionDown();
1898
1899 // Transfer touch focus to the second window
1900 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1901 // The first window gets cancel and the new gets pointer down (it already saw down)
1902 firstWindow->consumeMotionCancel();
1903 secondWindow->consumeMotionPointerDown(1);
1904
1905 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001906 NotifyMotionArgs pointerUpMotionArgs =
1907 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1908 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1909 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1910 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001911 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1912 // The first window gets nothing and the second gets pointer up
1913 firstWindow->assertNoEvents();
1914 secondWindow->consumeMotionPointerUp(1);
1915
1916 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001917 NotifyMotionArgs upMotionArgs =
1918 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1919 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001920 mDispatcher->notifyMotion(&upMotionArgs);
1921 // The first window gets nothing and the second gets up
1922 firstWindow->assertNoEvents();
1923 secondWindow->consumeMotionUp();
1924}
1925
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001926// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
1927// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
1928// touch is not supported, so the touch should continue on those windows and the transferred-to
1929// window should get nothing.
1930TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
1931 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1932
1933 // Create a non touch modal window that supports split touch
1934 sp<FakeWindowHandle> firstWindow =
1935 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1936 firstWindow->setFrame(Rect(0, 0, 600, 400));
1937 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1938 InputWindowInfo::Flag::SPLIT_TOUCH);
1939
1940 // Create a non touch modal window that supports split touch
1941 sp<FakeWindowHandle> secondWindow =
1942 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1943 secondWindow->setFrame(Rect(0, 400, 600, 800));
1944 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1945 InputWindowInfo::Flag::SPLIT_TOUCH);
1946
1947 // Add the windows to the dispatcher
1948 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1949
1950 PointF pointInFirst = {300, 200};
1951 PointF pointInSecond = {300, 600};
1952
1953 // Send down to the first window
1954 NotifyMotionArgs firstDownMotionArgs =
1955 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1956 ADISPLAY_ID_DEFAULT, {pointInFirst});
1957 mDispatcher->notifyMotion(&firstDownMotionArgs);
1958 // Only the first window should get the down event
1959 firstWindow->consumeMotionDown();
1960 secondWindow->assertNoEvents();
1961
1962 // Send down to the second window
1963 NotifyMotionArgs secondDownMotionArgs =
1964 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1965 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1966 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1967 {pointInFirst, pointInSecond});
1968 mDispatcher->notifyMotion(&secondDownMotionArgs);
1969 // The first window gets a move and the second a down
1970 firstWindow->consumeMotionMove();
1971 secondWindow->consumeMotionDown();
1972
1973 // Transfer touch focus to the second window
1974 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
1975 // The 'transferTouch' call should not succeed, because there are 2 touched windows
1976 ASSERT_FALSE(transferred);
1977 firstWindow->assertNoEvents();
1978 secondWindow->assertNoEvents();
1979
1980 // The rest of the dispatch should proceed as normal
1981 // Send pointer up to the second window
1982 NotifyMotionArgs pointerUpMotionArgs =
1983 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1984 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1985 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1986 {pointInFirst, pointInSecond});
1987 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1988 // The first window gets MOVE and the second gets pointer up
1989 firstWindow->consumeMotionMove();
1990 secondWindow->consumeMotionUp();
1991
1992 // Send up event to the first window
1993 NotifyMotionArgs upMotionArgs =
1994 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1995 ADISPLAY_ID_DEFAULT);
1996 mDispatcher->notifyMotion(&upMotionArgs);
1997 // The first window gets nothing and the second gets up
1998 firstWindow->consumeMotionUp();
1999 secondWindow->assertNoEvents();
2000}
2001
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002002TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002003 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002004 sp<FakeWindowHandle> window =
2005 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2006
Vishnu Nair47074b82020-08-14 11:54:47 -07002007 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002009 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002010
2011 window->consumeFocusEvent(true);
2012
2013 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2014 mDispatcher->notifyKey(&keyArgs);
2015
2016 // Window should receive key down event.
2017 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2018}
2019
2020TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002021 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002022 sp<FakeWindowHandle> window =
2023 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2024
Arthur Hung72d8dc32020-03-28 00:48:39 +00002025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002026
2027 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2028 mDispatcher->notifyKey(&keyArgs);
2029 mDispatcher->waitForIdle();
2030
2031 window->assertNoEvents();
2032}
2033
2034// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2035TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002036 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002037 sp<FakeWindowHandle> window =
2038 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2039
Arthur Hung72d8dc32020-03-28 00:48:39 +00002040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002041
2042 // Send key
2043 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2044 mDispatcher->notifyKey(&keyArgs);
2045 // Send motion
2046 NotifyMotionArgs motionArgs =
2047 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2048 ADISPLAY_ID_DEFAULT);
2049 mDispatcher->notifyMotion(&motionArgs);
2050
2051 // Window should receive only the motion event
2052 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2053 window->assertNoEvents(); // Key event or focus event will not be received
2054}
2055
arthurhungea3f4fc2020-12-21 23:18:53 +08002056TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2057 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2058
2059 // Create first non touch modal window that supports split touch
2060 sp<FakeWindowHandle> firstWindow =
2061 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2062 firstWindow->setFrame(Rect(0, 0, 600, 400));
2063 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2064 InputWindowInfo::Flag::SPLIT_TOUCH);
2065
2066 // Create second non touch modal window that supports split touch
2067 sp<FakeWindowHandle> secondWindow =
2068 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2069 secondWindow->setFrame(Rect(0, 400, 600, 800));
2070 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2071 InputWindowInfo::Flag::SPLIT_TOUCH);
2072
2073 // Add the windows to the dispatcher
2074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2075
2076 PointF pointInFirst = {300, 200};
2077 PointF pointInSecond = {300, 600};
2078
2079 // Send down to the first window
2080 NotifyMotionArgs firstDownMotionArgs =
2081 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2082 ADISPLAY_ID_DEFAULT, {pointInFirst});
2083 mDispatcher->notifyMotion(&firstDownMotionArgs);
2084 // Only the first window should get the down event
2085 firstWindow->consumeMotionDown();
2086 secondWindow->assertNoEvents();
2087
2088 // Send down to the second window
2089 NotifyMotionArgs secondDownMotionArgs =
2090 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2091 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2092 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2093 {pointInFirst, pointInSecond});
2094 mDispatcher->notifyMotion(&secondDownMotionArgs);
2095 // The first window gets a move and the second a down
2096 firstWindow->consumeMotionMove();
2097 secondWindow->consumeMotionDown();
2098
2099 // Send pointer cancel to the second window
2100 NotifyMotionArgs pointerUpMotionArgs =
2101 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2102 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2103 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2104 {pointInFirst, pointInSecond});
2105 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2106 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2107 // The first window gets move and the second gets cancel.
2108 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2109 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2110
2111 // Send up event.
2112 NotifyMotionArgs upMotionArgs =
2113 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2114 ADISPLAY_ID_DEFAULT);
2115 mDispatcher->notifyMotion(&upMotionArgs);
2116 // The first window gets up and the second gets nothing.
2117 firstWindow->consumeMotionUp();
2118 secondWindow->assertNoEvents();
2119}
2120
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002121TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2122 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2123
2124 sp<FakeWindowHandle> window =
2125 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2127 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2128 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2129 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2130
2131 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2132 window->assertNoEvents();
2133 mDispatcher->waitForIdle();
2134}
2135
chaviwd1c23182019-12-20 18:44:56 -08002136class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002137public:
2138 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002139 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002140 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002141 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002142 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002143 }
2144
chaviwd1c23182019-12-20 18:44:56 -08002145 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2146
2147 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2148 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2149 expectedDisplayId, expectedFlags);
2150 }
2151
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002152 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2153
2154 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2155
chaviwd1c23182019-12-20 18:44:56 -08002156 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2157 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2158 expectedDisplayId, expectedFlags);
2159 }
2160
2161 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2162 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2163 expectedDisplayId, expectedFlags);
2164 }
2165
Evan Rosky84f07f02021-04-16 10:42:42 -07002166 MotionEvent* consumeMotion() {
2167 InputEvent* event = mInputReceiver->consume();
2168 if (!event) {
2169 ADD_FAILURE() << "No event was produced";
2170 return nullptr;
2171 }
2172 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2173 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2174 return nullptr;
2175 }
2176 return static_cast<MotionEvent*>(event);
2177 }
2178
chaviwd1c23182019-12-20 18:44:56 -08002179 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2180
2181private:
2182 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002183};
2184
2185// Tests for gesture monitors
2186TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002187 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002188 sp<FakeWindowHandle> window =
2189 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002191
chaviwd1c23182019-12-20 18:44:56 -08002192 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2193 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002194
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002196 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002198 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002199 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002200}
2201
2202TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002203 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002204 sp<FakeWindowHandle> window =
2205 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2206
2207 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002208 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002209
Arthur Hung72d8dc32020-03-28 00:48:39 +00002210 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002211 setFocusedWindow(window);
2212
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002213 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002214
chaviwd1c23182019-12-20 18:44:56 -08002215 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2216 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002217
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2219 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002220 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002221 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002222}
2223
2224TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002225 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002226 sp<FakeWindowHandle> window =
2227 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002229
chaviwd1c23182019-12-20 18:44:56 -08002230 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2231 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002232
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002233 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002234 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002235 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002236 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002237 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002238
2239 window->releaseChannel();
2240
chaviwd1c23182019-12-20 18:44:56 -08002241 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002242
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002244 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002245 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002246 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002247}
2248
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002249TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2250 FakeMonitorReceiver monitor =
2251 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2252 true /*isGestureMonitor*/);
2253
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002255 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2256 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2257 ASSERT_TRUE(consumeSeq);
2258
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002259 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002260 monitor.finishEvent(*consumeSeq);
2261 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002262 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002263}
2264
Evan Rosky84f07f02021-04-16 10:42:42 -07002265// Tests for gesture monitors
2266TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2267 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2268 sp<FakeWindowHandle> window =
2269 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2271 window->setWindowOffset(20, 40);
2272 window->setWindowTransform(0, 1, -1, 0);
2273
2274 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2275 true /*isGestureMonitor*/);
2276
2277 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2278 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2279 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2280 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2281 MotionEvent* event = monitor.consumeMotion();
2282 // Even though window has transform, gesture monitor must not.
2283 ASSERT_EQ(ui::Transform(), event->getTransform());
2284}
2285
chaviw81e2bb92019-12-18 15:03:51 -08002286TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002287 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002288 sp<FakeWindowHandle> window =
2289 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2290
Arthur Hung72d8dc32020-03-28 00:48:39 +00002291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002292
2293 NotifyMotionArgs motionArgs =
2294 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2295 ADISPLAY_ID_DEFAULT);
2296
2297 mDispatcher->notifyMotion(&motionArgs);
2298 // Window should receive motion down event.
2299 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2300
2301 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002302 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002303 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2304 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2305 motionArgs.pointerCoords[0].getX() - 10);
2306
2307 mDispatcher->notifyMotion(&motionArgs);
2308 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2309 0 /*expectedFlags*/);
2310}
2311
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002312/**
2313 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2314 * the device default right away. In the test scenario, we check both the default value,
2315 * and the action of enabling / disabling.
2316 */
2317TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002318 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002319 sp<FakeWindowHandle> window =
2320 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2321
2322 // Set focused application.
2323 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002324 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002325
2326 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002327 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002328 setFocusedWindow(window);
2329
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002330 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2331
2332 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002333 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002334 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002335 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2336
2337 SCOPED_TRACE("Disable touch mode");
2338 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002339 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002340 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002341 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002342 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2343
2344 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002345 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002347 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2348
2349 SCOPED_TRACE("Enable touch mode again");
2350 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002351 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002352 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002353 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002354 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2355
2356 window->assertNoEvents();
2357}
2358
Gang Wange9087892020-01-07 12:17:14 -05002359TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002360 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002361 sp<FakeWindowHandle> window =
2362 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2363
2364 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002365 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002366
Arthur Hung72d8dc32020-03-28 00:48:39 +00002367 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002368 setFocusedWindow(window);
2369
Gang Wange9087892020-01-07 12:17:14 -05002370 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2371
2372 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2373 mDispatcher->notifyKey(&keyArgs);
2374
2375 InputEvent* event = window->consume();
2376 ASSERT_NE(event, nullptr);
2377
2378 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2379 ASSERT_NE(verified, nullptr);
2380 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2381
2382 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2383 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2384 ASSERT_EQ(keyArgs.source, verified->source);
2385 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2386
2387 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2388
2389 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2390 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002391 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2392 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2393 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2394 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2395 ASSERT_EQ(0, verifiedKey.repeatCount);
2396}
2397
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002398TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002399 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002400 sp<FakeWindowHandle> window =
2401 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2402
2403 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2404
Arthur Hung72d8dc32020-03-28 00:48:39 +00002405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002406
2407 NotifyMotionArgs motionArgs =
2408 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2409 ADISPLAY_ID_DEFAULT);
2410 mDispatcher->notifyMotion(&motionArgs);
2411
2412 InputEvent* event = window->consume();
2413 ASSERT_NE(event, nullptr);
2414
2415 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2416 ASSERT_NE(verified, nullptr);
2417 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2418
2419 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2420 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2421 EXPECT_EQ(motionArgs.source, verified->source);
2422 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2423
2424 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2425
2426 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2427 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2428 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2429 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2430 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2431 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2432 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2433}
2434
Prabir Pradhan664834b2021-05-20 16:00:42 -07002435TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002436 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2437 sp<FakeWindowHandle> window =
2438 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2439 const std::string name = window->getName();
2440
2441 // Window gets transformed by offset values.
2442 window->setWindowOffset(500.0f, 500.0f);
2443
2444 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2445 window->setFocusable(true);
2446
2447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2448
2449 // First, we set focused window so that focusedWindowHandle is not null.
2450 setFocusedWindow(window);
2451
2452 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2453 window->consumeFocusEvent(true);
2454
Prabir Pradhan664834b2021-05-20 16:00:42 -07002455 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
2456 AMOTION_EVENT_ACTION_DOWN),
2457 std::pair(AINPUT_SOURCE_JOYSTICK,
2458 AMOTION_EVENT_ACTION_MOVE)};
2459 for (const auto& [source, action] : nonTransformedSources) {
2460 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
Prabir Pradhanbd527712021-03-09 19:17:09 -08002461 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09002462
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002463 MotionEvent* event = window->consumeMotion();
Prabir Pradhanbd527712021-03-09 19:17:09 -08002464 ASSERT_NE(event, nullptr);
yunho.shinf4a80b82020-11-16 21:13:57 +09002465
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002466 const MotionEvent& motionEvent = *event;
Prabir Pradhan664834b2021-05-20 16:00:42 -07002467 EXPECT_EQ(action, motionEvent.getAction());
Prabir Pradhanbd527712021-03-09 19:17:09 -08002468 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09002469
Prabir Pradhanbd527712021-03-09 19:17:09 -08002470 float expectedX = motionArgs.pointerCoords[0].getX();
2471 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09002472
Prabir Pradhanbd527712021-03-09 19:17:09 -08002473 // Ensure the axis values from the final motion event are not transformed.
2474 EXPECT_EQ(expectedX, motionEvent.getX(0))
2475 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2476 << motionEvent.getX(0);
2477 EXPECT_EQ(expectedY, motionEvent.getY(0))
2478 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2479 << motionEvent.getY(0);
2480 // Ensure the raw and transformed axis values for the motion event are the same.
2481 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2482 << "expected raw and transformed X-axis values to be equal";
2483 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2484 << "expected raw and transformed Y-axis values to be equal";
2485 }
yunho.shinf4a80b82020-11-16 21:13:57 +09002486}
2487
chaviw09c8d2d2020-08-24 15:48:26 -07002488/**
2489 * Ensure that separate calls to sign the same data are generating the same key.
2490 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2491 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2492 * tests.
2493 */
2494TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2495 KeyEvent event = getTestKeyEvent();
2496 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2497
2498 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2499 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2500 ASSERT_EQ(hmac1, hmac2);
2501}
2502
2503/**
2504 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2505 */
2506TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2507 KeyEvent event = getTestKeyEvent();
2508 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2509 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2510
2511 verifiedEvent.deviceId += 1;
2512 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2513
2514 verifiedEvent.source += 1;
2515 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2516
2517 verifiedEvent.eventTimeNanos += 1;
2518 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2519
2520 verifiedEvent.displayId += 1;
2521 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2522
2523 verifiedEvent.action += 1;
2524 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2525
2526 verifiedEvent.downTimeNanos += 1;
2527 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2528
2529 verifiedEvent.flags += 1;
2530 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2531
2532 verifiedEvent.keyCode += 1;
2533 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2534
2535 verifiedEvent.scanCode += 1;
2536 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2537
2538 verifiedEvent.metaState += 1;
2539 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2540
2541 verifiedEvent.repeatCount += 1;
2542 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2543}
2544
Vishnu Nair958da932020-08-21 17:12:37 -07002545TEST_F(InputDispatcherTest, SetFocusedWindow) {
2546 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2547 sp<FakeWindowHandle> windowTop =
2548 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2549 sp<FakeWindowHandle> windowSecond =
2550 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2551 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2552
2553 // Top window is also focusable but is not granted focus.
2554 windowTop->setFocusable(true);
2555 windowSecond->setFocusable(true);
2556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2557 setFocusedWindow(windowSecond);
2558
2559 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002560 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2561 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002562
2563 // Focused window should receive event.
2564 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2565 windowTop->assertNoEvents();
2566}
2567
2568TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2569 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2570 sp<FakeWindowHandle> window =
2571 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2572 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2573
2574 window->setFocusable(true);
2575 // Release channel for window is no longer valid.
2576 window->releaseChannel();
2577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2578 setFocusedWindow(window);
2579
2580 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002581 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2582 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002583
2584 // window channel is invalid, so it should not receive any input event.
2585 window->assertNoEvents();
2586}
2587
2588TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2589 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2590 sp<FakeWindowHandle> window =
2591 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2592 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2593
2594 // Window is not focusable.
2595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2596 setFocusedWindow(window);
2597
2598 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002599 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2600 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002601
2602 // window is invalid, so it should not receive any input event.
2603 window->assertNoEvents();
2604}
2605
2606TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2607 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2608 sp<FakeWindowHandle> windowTop =
2609 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2610 sp<FakeWindowHandle> windowSecond =
2611 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2612 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2613
2614 windowTop->setFocusable(true);
2615 windowSecond->setFocusable(true);
2616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2617 setFocusedWindow(windowTop);
2618 windowTop->consumeFocusEvent(true);
2619
2620 setFocusedWindow(windowSecond, windowTop);
2621 windowSecond->consumeFocusEvent(true);
2622 windowTop->consumeFocusEvent(false);
2623
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002624 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2625 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002626
2627 // Focused window should receive event.
2628 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2629}
2630
2631TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2632 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2633 sp<FakeWindowHandle> windowTop =
2634 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2635 sp<FakeWindowHandle> windowSecond =
2636 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2637 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2638
2639 windowTop->setFocusable(true);
2640 windowSecond->setFocusable(true);
2641 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2642 setFocusedWindow(windowSecond, windowTop);
2643
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002644 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2645 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002646
2647 // Event should be dropped.
2648 windowTop->assertNoEvents();
2649 windowSecond->assertNoEvents();
2650}
2651
2652TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2653 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2654 sp<FakeWindowHandle> window =
2655 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2656 sp<FakeWindowHandle> previousFocusedWindow =
2657 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2658 ADISPLAY_ID_DEFAULT);
2659 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2660
2661 window->setFocusable(true);
2662 previousFocusedWindow->setFocusable(true);
2663 window->setVisible(false);
2664 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2665 setFocusedWindow(previousFocusedWindow);
2666 previousFocusedWindow->consumeFocusEvent(true);
2667
2668 // Requesting focus on invisible window takes focus from currently focused window.
2669 setFocusedWindow(window);
2670 previousFocusedWindow->consumeFocusEvent(false);
2671
2672 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002674 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002675 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002676
2677 // Window does not get focus event or key down.
2678 window->assertNoEvents();
2679
2680 // Window becomes visible.
2681 window->setVisible(true);
2682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2683
2684 // Window receives focus event.
2685 window->consumeFocusEvent(true);
2686 // Focused window receives key down.
2687 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2688}
2689
Vishnu Nair599f1412021-06-21 10:39:58 -07002690TEST_F(InputDispatcherTest, DisplayRemoved) {
2691 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2692 sp<FakeWindowHandle> window =
2693 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
2694 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2695
2696 // window is granted focus.
2697 window->setFocusable(true);
2698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2699 setFocusedWindow(window);
2700 window->consumeFocusEvent(true);
2701
2702 // When a display is removed window loses focus.
2703 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
2704 window->consumeFocusEvent(false);
2705}
2706
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002707/**
2708 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2709 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2710 * of the 'slipperyEnterWindow'.
2711 *
2712 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2713 * a way so that the touched location is no longer covered by the top window.
2714 *
2715 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2716 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2717 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2718 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2719 * with ACTION_DOWN).
2720 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2721 * window moved itself away from the touched location and had Flag::SLIPPERY.
2722 *
2723 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2724 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2725 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2726 *
2727 * In this test, we ensure that the event received by the bottom window has
2728 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2729 */
2730TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2731 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2732 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2733
2734 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2735 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2736
2737 sp<FakeWindowHandle> slipperyExitWindow =
2738 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2739 slipperyExitWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2740 InputWindowInfo::Flag::SLIPPERY);
2741 // Make sure this one overlaps the bottom window
2742 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2743 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2744 // one. Windows with the same owner are not considered to be occluding each other.
2745 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2746
2747 sp<FakeWindowHandle> slipperyEnterWindow =
2748 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2749 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2750
2751 mDispatcher->setInputWindows(
2752 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2753
2754 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2755 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2756 ADISPLAY_ID_DEFAULT, {{50, 50}});
2757 mDispatcher->notifyMotion(&args);
2758 slipperyExitWindow->consumeMotionDown();
2759 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2760 mDispatcher->setInputWindows(
2761 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2762
2763 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2764 ADISPLAY_ID_DEFAULT, {{51, 51}});
2765 mDispatcher->notifyMotion(&args);
2766
2767 slipperyExitWindow->consumeMotionCancel();
2768
2769 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2770 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2771}
2772
Garfield Tan1c7bc862020-01-28 13:24:04 -08002773class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2774protected:
2775 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2776 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2777
Chris Yea209fde2020-07-22 13:54:51 -07002778 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002779 sp<FakeWindowHandle> mWindow;
2780
2781 virtual void SetUp() override {
2782 mFakePolicy = new FakeInputDispatcherPolicy();
2783 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2784 mDispatcher = new InputDispatcher(mFakePolicy);
2785 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2786 ASSERT_EQ(OK, mDispatcher->start());
2787
2788 setUpWindow();
2789 }
2790
2791 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002792 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002793 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2794
Vishnu Nair47074b82020-08-14 11:54:47 -07002795 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002797 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002798 mWindow->consumeFocusEvent(true);
2799 }
2800
Chris Ye2ad95392020-09-01 13:44:44 -07002801 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002802 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002803 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002804 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2805 mDispatcher->notifyKey(&keyArgs);
2806
2807 // Window should receive key down event.
2808 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2809 }
2810
2811 void expectKeyRepeatOnce(int32_t repeatCount) {
2812 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2813 InputEvent* repeatEvent = mWindow->consume();
2814 ASSERT_NE(nullptr, repeatEvent);
2815
2816 uint32_t eventType = repeatEvent->getType();
2817 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2818
2819 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2820 uint32_t eventAction = repeatKeyEvent->getAction();
2821 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2822 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2823 }
2824
Chris Ye2ad95392020-09-01 13:44:44 -07002825 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002826 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002827 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002828 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2829 mDispatcher->notifyKey(&keyArgs);
2830
2831 // Window should receive key down event.
2832 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2833 0 /*expectedFlags*/);
2834 }
2835};
2836
2837TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002838 sendAndConsumeKeyDown(1 /* deviceId */);
2839 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2840 expectKeyRepeatOnce(repeatCount);
2841 }
2842}
2843
2844TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2845 sendAndConsumeKeyDown(1 /* deviceId */);
2846 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2847 expectKeyRepeatOnce(repeatCount);
2848 }
2849 sendAndConsumeKeyDown(2 /* deviceId */);
2850 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002851 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2852 expectKeyRepeatOnce(repeatCount);
2853 }
2854}
2855
2856TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002857 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002858 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002859 sendAndConsumeKeyUp(1 /* deviceId */);
2860 mWindow->assertNoEvents();
2861}
2862
2863TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2864 sendAndConsumeKeyDown(1 /* deviceId */);
2865 expectKeyRepeatOnce(1 /*repeatCount*/);
2866 sendAndConsumeKeyDown(2 /* deviceId */);
2867 expectKeyRepeatOnce(1 /*repeatCount*/);
2868 // Stale key up from device 1.
2869 sendAndConsumeKeyUp(1 /* deviceId */);
2870 // Device 2 is still down, keep repeating
2871 expectKeyRepeatOnce(2 /*repeatCount*/);
2872 expectKeyRepeatOnce(3 /*repeatCount*/);
2873 // Device 2 key up
2874 sendAndConsumeKeyUp(2 /* deviceId */);
2875 mWindow->assertNoEvents();
2876}
2877
2878TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2879 sendAndConsumeKeyDown(1 /* deviceId */);
2880 expectKeyRepeatOnce(1 /*repeatCount*/);
2881 sendAndConsumeKeyDown(2 /* deviceId */);
2882 expectKeyRepeatOnce(1 /*repeatCount*/);
2883 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2884 sendAndConsumeKeyUp(2 /* deviceId */);
2885 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002886 mWindow->assertNoEvents();
2887}
2888
2889TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002890 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002891 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2892 InputEvent* repeatEvent = mWindow->consume();
2893 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2894 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2895 IdGenerator::getSource(repeatEvent->getId()));
2896 }
2897}
2898
2899TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002900 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002901
2902 std::unordered_set<int32_t> idSet;
2903 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2904 InputEvent* repeatEvent = mWindow->consume();
2905 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2906 int32_t id = repeatEvent->getId();
2907 EXPECT_EQ(idSet.end(), idSet.find(id));
2908 idSet.insert(id);
2909 }
2910}
2911
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002912/* Test InputDispatcher for MultiDisplay */
2913class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2914public:
2915 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002916 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002917 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002918
Chris Yea209fde2020-07-22 13:54:51 -07002919 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002920 windowInPrimary =
2921 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002922
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002923 // Set focus window for primary display, but focused display would be second one.
2924 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002925 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002927 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002928 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002929
Chris Yea209fde2020-07-22 13:54:51 -07002930 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002931 windowInSecondary =
2932 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002933 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002934 // Set focus display to second one.
2935 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2936 // Set focus window for second display.
2937 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002938 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002939 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002940 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002941 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002942 }
2943
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002944 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002945 InputDispatcherTest::TearDown();
2946
Chris Yea209fde2020-07-22 13:54:51 -07002947 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002948 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002949 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002950 windowInSecondary.clear();
2951 }
2952
2953protected:
Chris Yea209fde2020-07-22 13:54:51 -07002954 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002955 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002956 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002957 sp<FakeWindowHandle> windowInSecondary;
2958};
2959
2960TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2961 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2963 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002965 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002966 windowInSecondary->assertNoEvents();
2967
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002968 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2970 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2971 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002972 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002973 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002974}
2975
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002976TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002977 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002978 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2979 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002980 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002981 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002982 windowInSecondary->assertNoEvents();
2983
2984 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002986 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002987 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002988 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002989
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002990 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002991 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002992
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002993 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002994 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2995 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002996
2997 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002998 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002999 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003000 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003001 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003002 windowInSecondary->assertNoEvents();
3003}
3004
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003005// Test per-display input monitors for motion event.
3006TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003007 FakeMonitorReceiver monitorInPrimary =
3008 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3009 FakeMonitorReceiver monitorInSecondary =
3010 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003011
3012 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3014 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3015 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003016 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003017 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003018 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003019 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003020
3021 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3023 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3024 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003025 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003026 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003027 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003028 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003029
3030 // Test inject a non-pointer motion event.
3031 // If specific a display, it will dispatch to the focused window of particular display,
3032 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003033 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3034 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3035 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003036 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003037 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003038 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003039 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003040}
3041
3042// Test per-display input monitors for key event.
3043TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003044 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003045 FakeMonitorReceiver monitorInPrimary =
3046 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3047 FakeMonitorReceiver monitorInSecondary =
3048 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003049
3050 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3052 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003053 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003054 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003055 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003056 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003057}
3058
Vishnu Nair958da932020-08-21 17:12:37 -07003059TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3060 sp<FakeWindowHandle> secondWindowInPrimary =
3061 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3062 secondWindowInPrimary->setFocusable(true);
3063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3064 setFocusedWindow(secondWindowInPrimary);
3065 windowInPrimary->consumeFocusEvent(false);
3066 secondWindowInPrimary->consumeFocusEvent(true);
3067
3068 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3070 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003071 windowInPrimary->assertNoEvents();
3072 windowInSecondary->assertNoEvents();
3073 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3074}
3075
Jackal Guof9696682018-10-05 12:23:23 +08003076class InputFilterTest : public InputDispatcherTest {
3077protected:
3078 static constexpr int32_t SECOND_DISPLAY_ID = 1;
3079
3080 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
3081 NotifyMotionArgs motionArgs;
3082
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003083 motionArgs =
3084 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003085 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003086 motionArgs =
3087 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003088 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003089 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003090 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003091 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003092 } else {
3093 mFakePolicy->assertFilterInputEventWasNotCalled();
3094 }
3095 }
3096
3097 void testNotifyKey(bool expectToBeFiltered) {
3098 NotifyKeyArgs keyArgs;
3099
3100 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3101 mDispatcher->notifyKey(&keyArgs);
3102 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3103 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003104 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003105
3106 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003107 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003108 } else {
3109 mFakePolicy->assertFilterInputEventWasNotCalled();
3110 }
3111 }
3112};
3113
3114// Test InputFilter for MotionEvent
3115TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3116 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3117 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3118 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3119
3120 // Enable InputFilter
3121 mDispatcher->setInputFilterEnabled(true);
3122 // Test touch on both primary and second display, and check if both events are filtered.
3123 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3124 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3125
3126 // Disable InputFilter
3127 mDispatcher->setInputFilterEnabled(false);
3128 // Test touch on both primary and second display, and check if both events aren't filtered.
3129 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3130 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3131}
3132
3133// Test InputFilter for KeyEvent
3134TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3135 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3136 testNotifyKey(/*expectToBeFiltered*/ false);
3137
3138 // Enable InputFilter
3139 mDispatcher->setInputFilterEnabled(true);
3140 // Send a key event, and check if it is filtered.
3141 testNotifyKey(/*expectToBeFiltered*/ true);
3142
3143 // Disable InputFilter
3144 mDispatcher->setInputFilterEnabled(false);
3145 // Send a key event, and check if it isn't filtered.
3146 testNotifyKey(/*expectToBeFiltered*/ false);
3147}
3148
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003149class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3150protected:
3151 virtual void SetUp() override {
3152 InputDispatcherTest::SetUp();
3153
3154 /**
3155 * We don't need to enable input filter to test the injected event policy, but we enabled it
3156 * here to make the tests more realistic, since this policy only matters when inputfilter is
3157 * on.
3158 */
3159 mDispatcher->setInputFilterEnabled(true);
3160
3161 std::shared_ptr<InputApplicationHandle> application =
3162 std::make_shared<FakeApplicationHandle>();
3163 mWindow =
3164 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3165
3166 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3167 mWindow->setFocusable(true);
3168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3169 setFocusedWindow(mWindow);
3170 mWindow->consumeFocusEvent(true);
3171 }
3172
3173 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId) {
3174 KeyEvent event;
3175
3176 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3177 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3178 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3179 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3180 const int32_t additionalPolicyFlags =
3181 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3183 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3184 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3185 policyFlags | additionalPolicyFlags));
3186
3187 InputEvent* received = mWindow->consume();
3188 ASSERT_NE(nullptr, received);
3189 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3190 }
3191
3192private:
3193 sp<FakeWindowHandle> mWindow;
3194};
3195
3196TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
3197 // We don't need POLICY_FLAG_FILTERED here, but it will be set in practice, so keep it to make
3198 // the test more closely resemble the real usage
3199 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INPUTFILTER_TRUSTED, 3 /*injectedDeviceId*/,
3200 3 /*resolvedDeviceId*/);
3201}
3202
3203TEST_F(InputFilterInjectionPolicyTest, EventsInjectedFromAccessibility_HaveAccessibilityDeviceId) {
3204 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3205 3 /*injectedDeviceId*/, ACCESSIBILITY_DEVICE_ID /*resolvedDeviceId*/);
3206}
3207
3208TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3209 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
3210 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/);
3211}
3212
chaviwfd6d3512019-03-25 13:23:49 -07003213class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003214 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003215 InputDispatcherTest::SetUp();
3216
Chris Yea209fde2020-07-22 13:54:51 -07003217 std::shared_ptr<FakeApplicationHandle> application =
3218 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003219 mUnfocusedWindow =
3220 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003221 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3222 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3223 // window.
Michael Wright44753b12020-07-08 13:48:11 +01003224 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003225
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003226 mFocusedWindow =
3227 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3228 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003229 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003230
3231 // Set focused application.
3232 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003233 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003234
3235 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003236 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003237 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003238 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003239 }
3240
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003241 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003242 InputDispatcherTest::TearDown();
3243
3244 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003245 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003246 }
3247
3248protected:
3249 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003250 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003251 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003252};
3253
3254// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3255// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3256// the onPointerDownOutsideFocus callback.
3257TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003258 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003259 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3260 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003261 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003262 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003263
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003264 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003265 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3266}
3267
3268// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3269// DOWN on the window that doesn't have focus. Ensure no window received the
3270// onPointerDownOutsideFocus callback.
3271TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003272 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003273 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003274 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003275 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003276
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003277 ASSERT_TRUE(mDispatcher->waitForIdle());
3278 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003279}
3280
3281// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3282// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3283TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3285 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003286 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003287 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003288
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003289 ASSERT_TRUE(mDispatcher->waitForIdle());
3290 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003291}
3292
3293// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3294// DOWN on the window that already has focus. Ensure no window received the
3295// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003296TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003298 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003299 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003300 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003301 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003302
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003303 ASSERT_TRUE(mDispatcher->waitForIdle());
3304 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003305}
3306
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003307// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3308// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3309TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3310 const MotionEvent event =
3311 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3312 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3313 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3314 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3315 .build();
3316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3317 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3318 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3319
3320 ASSERT_TRUE(mDispatcher->waitForIdle());
3321 mFakePolicy->assertOnPointerDownWasNotCalled();
3322 // Ensure that the unfocused window did not receive any FOCUS events.
3323 mUnfocusedWindow->assertNoEvents();
3324}
3325
chaviwaf87b3e2019-10-01 16:59:28 -07003326// These tests ensures we can send touch events to a single client when there are multiple input
3327// windows that point to the same client token.
3328class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3329 virtual void SetUp() override {
3330 InputDispatcherTest::SetUp();
3331
Chris Yea209fde2020-07-22 13:54:51 -07003332 std::shared_ptr<FakeApplicationHandle> application =
3333 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003334 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3335 ADISPLAY_ID_DEFAULT);
3336 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3337 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
Michael Wright44753b12020-07-08 13:48:11 +01003338 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3339 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003340 mWindow1->setFrame(Rect(0, 0, 100, 100));
3341
3342 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3343 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01003344 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3345 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003346 mWindow2->setFrame(Rect(100, 100, 200, 200));
3347
Arthur Hung72d8dc32020-03-28 00:48:39 +00003348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003349 }
3350
3351protected:
3352 sp<FakeWindowHandle> mWindow1;
3353 sp<FakeWindowHandle> mWindow2;
3354
3355 // Helper function to convert the point from screen coordinates into the window's space
3356 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003357 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3358 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003359 }
3360
3361 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3362 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003363 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003364 InputEvent* event = window->consume();
3365
3366 ASSERT_NE(nullptr, event) << name.c_str()
3367 << ": consumer should have returned non-NULL event.";
3368
3369 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3370 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3371 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3372
3373 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3374 EXPECT_EQ(expectedAction, motionEvent.getAction());
3375
3376 for (size_t i = 0; i < points.size(); i++) {
3377 float expectedX = points[i].x;
3378 float expectedY = points[i].y;
3379
3380 EXPECT_EQ(expectedX, motionEvent.getX(i))
3381 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3382 << ", got " << motionEvent.getX(i);
3383 EXPECT_EQ(expectedY, motionEvent.getY(i))
3384 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3385 << ", got " << motionEvent.getY(i);
3386 }
3387 }
chaviw9eaa22c2020-07-01 16:21:27 -07003388
3389 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3390 std::vector<PointF> expectedPoints) {
3391 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3392 ADISPLAY_ID_DEFAULT, touchedPoints);
3393 mDispatcher->notifyMotion(&motionArgs);
3394
3395 // Always consume from window1 since it's the window that has the InputReceiver
3396 consumeMotionEvent(mWindow1, action, expectedPoints);
3397 }
chaviwaf87b3e2019-10-01 16:59:28 -07003398};
3399
3400TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3401 // Touch Window 1
3402 PointF touchedPoint = {10, 10};
3403 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003404 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003405
3406 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003407 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003408
3409 // Touch Window 2
3410 touchedPoint = {150, 150};
3411 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003412 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003413}
3414
chaviw9eaa22c2020-07-01 16:21:27 -07003415TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3416 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003417 mWindow2->setWindowScale(0.5f, 0.5f);
3418
3419 // Touch Window 1
3420 PointF touchedPoint = {10, 10};
3421 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003422 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003423 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003424 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003425
3426 // Touch Window 2
3427 touchedPoint = {150, 150};
3428 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003429 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3430 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003431
chaviw9eaa22c2020-07-01 16:21:27 -07003432 // Update the transform so rotation is set
3433 mWindow2->setWindowTransform(0, -1, 1, 0);
3434 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3435 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003436}
3437
chaviw9eaa22c2020-07-01 16:21:27 -07003438TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003439 mWindow2->setWindowScale(0.5f, 0.5f);
3440
3441 // Touch Window 1
3442 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3443 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003444 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003445
3446 // Touch Window 2
3447 int32_t actionPointerDown =
3448 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003449 touchedPoints.push_back(PointF{150, 150});
3450 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3451 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003452
chaviw9eaa22c2020-07-01 16:21:27 -07003453 // Release Window 2
3454 int32_t actionPointerUp =
3455 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3456 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3457 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003458
chaviw9eaa22c2020-07-01 16:21:27 -07003459 // Update the transform so rotation is set for Window 2
3460 mWindow2->setWindowTransform(0, -1, 1, 0);
3461 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3462 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003463}
3464
chaviw9eaa22c2020-07-01 16:21:27 -07003465TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003466 mWindow2->setWindowScale(0.5f, 0.5f);
3467
3468 // Touch Window 1
3469 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3470 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003471 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003472
3473 // Touch Window 2
3474 int32_t actionPointerDown =
3475 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003476 touchedPoints.push_back(PointF{150, 150});
3477 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003478
chaviw9eaa22c2020-07-01 16:21:27 -07003479 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003480
3481 // Move both windows
3482 touchedPoints = {{20, 20}, {175, 175}};
3483 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3484 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3485
chaviw9eaa22c2020-07-01 16:21:27 -07003486 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003487
chaviw9eaa22c2020-07-01 16:21:27 -07003488 // Release Window 2
3489 int32_t actionPointerUp =
3490 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3491 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3492 expectedPoints.pop_back();
3493
3494 // Touch Window 2
3495 mWindow2->setWindowTransform(0, -1, 1, 0);
3496 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3497 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3498
3499 // Move both windows
3500 touchedPoints = {{20, 20}, {175, 175}};
3501 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3502 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3503
3504 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003505}
3506
3507TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3508 mWindow1->setWindowScale(0.5f, 0.5f);
3509
3510 // Touch Window 1
3511 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3512 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003513 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003514
3515 // Touch Window 2
3516 int32_t actionPointerDown =
3517 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003518 touchedPoints.push_back(PointF{150, 150});
3519 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003520
chaviw9eaa22c2020-07-01 16:21:27 -07003521 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003522
3523 // Move both windows
3524 touchedPoints = {{20, 20}, {175, 175}};
3525 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3526 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3527
chaviw9eaa22c2020-07-01 16:21:27 -07003528 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003529}
3530
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003531class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3532 virtual void SetUp() override {
3533 InputDispatcherTest::SetUp();
3534
Chris Yea209fde2020-07-22 13:54:51 -07003535 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003536 mApplication->setDispatchingTimeout(20ms);
3537 mWindow =
3538 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3539 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003540 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003541 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003542 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3543 // window.
Michael Wright44753b12020-07-08 13:48:11 +01003544 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003545
3546 // Set focused application.
3547 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3548
3549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003550 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003551 mWindow->consumeFocusEvent(true);
3552 }
3553
3554 virtual void TearDown() override {
3555 InputDispatcherTest::TearDown();
3556 mWindow.clear();
3557 }
3558
3559protected:
Chris Yea209fde2020-07-22 13:54:51 -07003560 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003561 sp<FakeWindowHandle> mWindow;
3562 static constexpr PointF WINDOW_LOCATION = {20, 20};
3563
3564 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003565 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003566 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3567 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003568 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003569 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3570 WINDOW_LOCATION));
3571 }
3572};
3573
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003574// Send a tap and respond, which should not cause an ANR.
3575TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3576 tapOnWindow();
3577 mWindow->consumeMotionDown();
3578 mWindow->consumeMotionUp();
3579 ASSERT_TRUE(mDispatcher->waitForIdle());
3580 mFakePolicy->assertNotifyAnrWasNotCalled();
3581}
3582
3583// Send a regular key and respond, which should not cause an ANR.
3584TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003585 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003586 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3587 ASSERT_TRUE(mDispatcher->waitForIdle());
3588 mFakePolicy->assertNotifyAnrWasNotCalled();
3589}
3590
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003591TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3592 mWindow->setFocusable(false);
3593 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3594 mWindow->consumeFocusEvent(false);
3595
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003596 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003597 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003598 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3599 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003601 // Key will not go to window because we have no focused window.
3602 // The 'no focused window' ANR timer should start instead.
3603
3604 // Now, the focused application goes away.
3605 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3606 // The key should get dropped and there should be no ANR.
3607
3608 ASSERT_TRUE(mDispatcher->waitForIdle());
3609 mFakePolicy->assertNotifyAnrWasNotCalled();
3610}
3611
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003612// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003613// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3614// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003615TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003617 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3618 WINDOW_LOCATION));
3619
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003620 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3621 ASSERT_TRUE(sequenceNum);
3622 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003623 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003624
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003625 mWindow->finishEvent(*sequenceNum);
3626 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3627 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003628 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003629 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003630}
3631
3632// Send a key to the app and have the app not respond right away.
3633TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3634 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003636 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3637 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003638 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003639 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003640 ASSERT_TRUE(mDispatcher->waitForIdle());
3641}
3642
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003643// We have a focused application, but no focused window
3644TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003645 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3647 mWindow->consumeFocusEvent(false);
3648
3649 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003650 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003651 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3652 WINDOW_LOCATION));
3653 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3654 mDispatcher->waitForIdle();
3655 mFakePolicy->assertNotifyAnrWasNotCalled();
3656
3657 // Once a focused event arrives, we get an ANR for this application
3658 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3659 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003660 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003661 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003662 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003663 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003664 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003665 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003666 ASSERT_TRUE(mDispatcher->waitForIdle());
3667}
3668
3669// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003670// Make sure that we don't notify policy twice about the same ANR.
3671TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003672 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3674 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003675
3676 // Once a focused event arrives, we get an ANR for this application
3677 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3678 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003679 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003680 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003681 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003682 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003683 const std::chrono::duration appTimeout =
3684 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003685 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003686
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003687 std::this_thread::sleep_for(appTimeout);
3688 // ANR should not be raised again. It is up to policy to do that if it desires.
3689 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003690
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003691 // If we now get a focused window, the ANR should stop, but the policy handles that via
3692 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003693 ASSERT_TRUE(mDispatcher->waitForIdle());
3694}
3695
3696// We have a focused application, but no focused window
3697TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003698 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3700 mWindow->consumeFocusEvent(false);
3701
3702 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003703 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003704 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003705 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3706 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003707
3708 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003709 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003710
3711 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003712 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003713 ASSERT_TRUE(mDispatcher->waitForIdle());
3714 mWindow->assertNoEvents();
3715}
3716
3717/**
3718 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3719 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3720 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3721 * the ANR mechanism should still work.
3722 *
3723 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3724 * DOWN event, while not responding on the second one.
3725 */
3726TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3727 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3728 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3729 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3730 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3731 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003732 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003733
3734 // Now send ACTION_UP, with identical timestamp
3735 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3736 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3737 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3738 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003739 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003740
3741 // We have now sent down and up. Let's consume first event and then ANR on the second.
3742 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3743 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003744 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003745}
3746
3747// If an app is not responding to a key event, gesture monitors should continue to receive
3748// new motion events
3749TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3750 FakeMonitorReceiver monitor =
3751 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3752 true /*isGestureMonitor*/);
3753
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3755 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003756 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003757 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003758
3759 // Stuck on the ACTION_UP
3760 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003761 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003762
3763 // New tap will go to the gesture monitor, but not to the window
3764 tapOnWindow();
3765 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3766 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3767
3768 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3769 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003770 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003771 mWindow->assertNoEvents();
3772 monitor.assertNoEvents();
3773}
3774
3775// If an app is not responding to a motion event, gesture monitors should continue to receive
3776// new motion events
3777TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3778 FakeMonitorReceiver monitor =
3779 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3780 true /*isGestureMonitor*/);
3781
3782 tapOnWindow();
3783 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3784 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3785
3786 mWindow->consumeMotionDown();
3787 // Stuck on the ACTION_UP
3788 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003789 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003790
3791 // New tap will go to the gesture monitor, but not to the window
3792 tapOnWindow();
3793 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3794 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3795
3796 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3797 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003798 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003799 mWindow->assertNoEvents();
3800 monitor.assertNoEvents();
3801}
3802
3803// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3804// process events, you don't get an anr. When the window later becomes unresponsive again, you
3805// get an ANR again.
3806// 1. tap -> block on ACTION_UP -> receive ANR
3807// 2. consume all pending events (= queue becomes healthy again)
3808// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3809TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3810 tapOnWindow();
3811
3812 mWindow->consumeMotionDown();
3813 // Block on ACTION_UP
3814 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003815 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003816 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3817 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003818 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003819 mWindow->assertNoEvents();
3820
3821 tapOnWindow();
3822 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003823 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003824 mWindow->consumeMotionUp();
3825
3826 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003827 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003828 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003829 mWindow->assertNoEvents();
3830}
3831
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003832// If a connection remains unresponsive for a while, make sure policy is only notified once about
3833// it.
3834TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003836 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3837 WINDOW_LOCATION));
3838
3839 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003840 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003841 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003842 // 'notifyConnectionUnresponsive' should only be called once per connection
3843 mFakePolicy->assertNotifyAnrWasNotCalled();
3844 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003845 mWindow->consumeMotionDown();
3846 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3847 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3848 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003849 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003850 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003851 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003852}
3853
3854/**
3855 * If a window is processing a motion event, and then a key event comes in, the key event should
3856 * not to to the focused window until the motion is processed.
3857 *
3858 * Warning!!!
3859 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3860 * and the injection timeout that we specify when injecting the key.
3861 * We must have the injection timeout (10ms) be smaller than
3862 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3863 *
3864 * If that value changes, this test should also change.
3865 */
3866TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3867 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3868 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3869
3870 tapOnWindow();
3871 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3872 ASSERT_TRUE(downSequenceNum);
3873 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3874 ASSERT_TRUE(upSequenceNum);
3875 // Don't finish the events yet, and send a key
3876 // Injection will "succeed" because we will eventually give up and send the key to the focused
3877 // window even if motions are still being processed. But because the injection timeout is short,
3878 // we will receive INJECTION_TIMED_OUT as the result.
3879
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003880 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003881 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003882 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3883 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003884 // Key will not be sent to the window, yet, because the window is still processing events
3885 // and the key remains pending, waiting for the touch events to be processed
3886 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3887 ASSERT_FALSE(keySequenceNum);
3888
3889 std::this_thread::sleep_for(500ms);
3890 // if we wait long enough though, dispatcher will give up, and still send the key
3891 // to the focused window, even though we have not yet finished the motion event
3892 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3893 mWindow->finishEvent(*downSequenceNum);
3894 mWindow->finishEvent(*upSequenceNum);
3895}
3896
3897/**
3898 * If a window is processing a motion event, and then a key event comes in, the key event should
3899 * not go to the focused window until the motion is processed.
3900 * If then a new motion comes in, then the pending key event should be going to the currently
3901 * focused window right away.
3902 */
3903TEST_F(InputDispatcherSingleWindowAnr,
3904 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3905 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3906 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3907
3908 tapOnWindow();
3909 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3910 ASSERT_TRUE(downSequenceNum);
3911 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3912 ASSERT_TRUE(upSequenceNum);
3913 // Don't finish the events yet, and send a key
3914 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003916 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003917 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003918 // At this point, key is still pending, and should not be sent to the application yet.
3919 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3920 ASSERT_FALSE(keySequenceNum);
3921
3922 // Now tap down again. It should cause the pending key to go to the focused window right away.
3923 tapOnWindow();
3924 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3925 // the other events yet. We can finish events in any order.
3926 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3927 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3928 mWindow->consumeMotionDown();
3929 mWindow->consumeMotionUp();
3930 mWindow->assertNoEvents();
3931}
3932
3933class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3934 virtual void SetUp() override {
3935 InputDispatcherTest::SetUp();
3936
Chris Yea209fde2020-07-22 13:54:51 -07003937 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003938 mApplication->setDispatchingTimeout(10ms);
3939 mUnfocusedWindow =
3940 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3941 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3942 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3943 // window.
3944 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003945 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3946 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3947 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003948
3949 mFocusedWindow =
3950 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003951 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003952 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003953 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3954 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003955
3956 // Set focused application.
3957 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003958 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003959
3960 // Expect one focus window exist in display.
3961 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003962 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003963 mFocusedWindow->consumeFocusEvent(true);
3964 }
3965
3966 virtual void TearDown() override {
3967 InputDispatcherTest::TearDown();
3968
3969 mUnfocusedWindow.clear();
3970 mFocusedWindow.clear();
3971 }
3972
3973protected:
Chris Yea209fde2020-07-22 13:54:51 -07003974 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003975 sp<FakeWindowHandle> mUnfocusedWindow;
3976 sp<FakeWindowHandle> mFocusedWindow;
3977 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3978 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3979 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3980
3981 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3982
3983 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3984
3985private:
3986 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003988 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3989 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003991 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3992 location));
3993 }
3994};
3995
3996// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3997// should be ANR'd first.
3998TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004000 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4001 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004003 mFocusedWindow->consumeMotionDown();
4004 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4005 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4006 // We consumed all events, so no ANR
4007 ASSERT_TRUE(mDispatcher->waitForIdle());
4008 mFakePolicy->assertNotifyAnrWasNotCalled();
4009
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004010 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004011 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4012 FOCUSED_WINDOW_LOCATION));
4013 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4014 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004015
4016 const std::chrono::duration timeout =
4017 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004018 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004019 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4020 // sequence to make it consistent
4021 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004022 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004023 mFocusedWindow->consumeMotionDown();
4024 // This cancel is generated because the connection was unresponsive
4025 mFocusedWindow->consumeMotionCancel();
4026 mFocusedWindow->assertNoEvents();
4027 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004028 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004029 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004030 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004031}
4032
4033// If we have 2 windows with identical timeouts that are both unresponsive,
4034// it doesn't matter which order they should have ANR.
4035// But we should receive ANR for both.
4036TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4037 // Set the timeout for unfocused window to match the focused window
4038 mUnfocusedWindow->setDispatchingTimeout(10ms);
4039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4040
4041 tapOnFocusedWindow();
4042 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004043 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4044 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004045
4046 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004047 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4048 mFocusedWindow->getToken() == anrConnectionToken2);
4049 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4050 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004051
4052 ASSERT_TRUE(mDispatcher->waitForIdle());
4053 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004054
4055 mFocusedWindow->consumeMotionDown();
4056 mFocusedWindow->consumeMotionUp();
4057 mUnfocusedWindow->consumeMotionOutside();
4058
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004059 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4060 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004061
4062 // Both applications should be marked as responsive, in any order
4063 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4064 mFocusedWindow->getToken() == responsiveToken2);
4065 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4066 mUnfocusedWindow->getToken() == responsiveToken2);
4067 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004068}
4069
4070// If a window is already not responding, the second tap on the same window should be ignored.
4071// We should also log an error to account for the dropped event (not tested here).
4072// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4073TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4074 tapOnFocusedWindow();
4075 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4076 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4077 // Receive the events, but don't respond
4078 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4079 ASSERT_TRUE(downEventSequenceNum);
4080 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4081 ASSERT_TRUE(upEventSequenceNum);
4082 const std::chrono::duration timeout =
4083 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004084 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004085
4086 // Tap once again
4087 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004088 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004089 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4090 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004091 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004092 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4093 FOCUSED_WINDOW_LOCATION));
4094 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4095 // valid touch target
4096 mUnfocusedWindow->assertNoEvents();
4097
4098 // Consume the first tap
4099 mFocusedWindow->finishEvent(*downEventSequenceNum);
4100 mFocusedWindow->finishEvent(*upEventSequenceNum);
4101 ASSERT_TRUE(mDispatcher->waitForIdle());
4102 // The second tap did not go to the focused window
4103 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004104 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004105 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004106 mFakePolicy->assertNotifyAnrWasNotCalled();
4107}
4108
4109// If you tap outside of all windows, there will not be ANR
4110TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004111 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004112 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4113 LOCATION_OUTSIDE_ALL_WINDOWS));
4114 ASSERT_TRUE(mDispatcher->waitForIdle());
4115 mFakePolicy->assertNotifyAnrWasNotCalled();
4116}
4117
4118// Since the focused window is paused, tapping on it should not produce any events
4119TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4120 mFocusedWindow->setPaused(true);
4121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4122
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004123 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004124 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4125 FOCUSED_WINDOW_LOCATION));
4126
4127 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4128 ASSERT_TRUE(mDispatcher->waitForIdle());
4129 // Should not ANR because the window is paused, and touches shouldn't go to it
4130 mFakePolicy->assertNotifyAnrWasNotCalled();
4131
4132 mFocusedWindow->assertNoEvents();
4133 mUnfocusedWindow->assertNoEvents();
4134}
4135
4136/**
4137 * If a window is processing a motion event, and then a key event comes in, the key event should
4138 * not to to the focused window until the motion is processed.
4139 * If a different window becomes focused at this time, the key should go to that window instead.
4140 *
4141 * Warning!!!
4142 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4143 * and the injection timeout that we specify when injecting the key.
4144 * We must have the injection timeout (10ms) be smaller than
4145 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4146 *
4147 * If that value changes, this test should also change.
4148 */
4149TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4150 // Set a long ANR timeout to prevent it from triggering
4151 mFocusedWindow->setDispatchingTimeout(2s);
4152 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4153
4154 tapOnUnfocusedWindow();
4155 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4156 ASSERT_TRUE(downSequenceNum);
4157 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4158 ASSERT_TRUE(upSequenceNum);
4159 // Don't finish the events yet, and send a key
4160 // Injection will succeed because we will eventually give up and send the key to the focused
4161 // window even if motions are still being processed.
4162
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004163 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004164 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004165 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4166 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004167 // Key will not be sent to the window, yet, because the window is still processing events
4168 // and the key remains pending, waiting for the touch events to be processed
4169 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4170 ASSERT_FALSE(keySequenceNum);
4171
4172 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004173 mFocusedWindow->setFocusable(false);
4174 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004176 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004177
4178 // Focus events should precede the key events
4179 mUnfocusedWindow->consumeFocusEvent(true);
4180 mFocusedWindow->consumeFocusEvent(false);
4181
4182 // Finish the tap events, which should unblock dispatcher
4183 mUnfocusedWindow->finishEvent(*downSequenceNum);
4184 mUnfocusedWindow->finishEvent(*upSequenceNum);
4185
4186 // Now that all queues are cleared and no backlog in the connections, the key event
4187 // can finally go to the newly focused "mUnfocusedWindow".
4188 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4189 mFocusedWindow->assertNoEvents();
4190 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004191 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004192}
4193
4194// When the touch stream is split across 2 windows, and one of them does not respond,
4195// then ANR should be raised and the touch should be canceled for the unresponsive window.
4196// The other window should not be affected by that.
4197TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4198 // Touch Window 1
4199 NotifyMotionArgs motionArgs =
4200 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4201 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4202 mDispatcher->notifyMotion(&motionArgs);
4203 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4204 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4205
4206 // Touch Window 2
4207 int32_t actionPointerDown =
4208 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4209
4210 motionArgs =
4211 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4212 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4213 mDispatcher->notifyMotion(&motionArgs);
4214
4215 const std::chrono::duration timeout =
4216 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004217 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004218
4219 mUnfocusedWindow->consumeMotionDown();
4220 mFocusedWindow->consumeMotionDown();
4221 // Focused window may or may not receive ACTION_MOVE
4222 // But it should definitely receive ACTION_CANCEL due to the ANR
4223 InputEvent* event;
4224 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4225 ASSERT_TRUE(moveOrCancelSequenceNum);
4226 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4227 ASSERT_NE(nullptr, event);
4228 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4229 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4230 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4231 mFocusedWindow->consumeMotionCancel();
4232 } else {
4233 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4234 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004235 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004236 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004237
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004238 mUnfocusedWindow->assertNoEvents();
4239 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004240 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004241}
4242
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004243/**
4244 * If we have no focused window, and a key comes in, we start the ANR timer.
4245 * The focused application should add a focused window before the timer runs out to prevent ANR.
4246 *
4247 * If the user touches another application during this time, the key should be dropped.
4248 * Next, if a new focused window comes in, without toggling the focused application,
4249 * then no ANR should occur.
4250 *
4251 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4252 * but in some cases the policy may not update the focused application.
4253 */
4254TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4255 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4256 std::make_shared<FakeApplicationHandle>();
4257 focusedApplication->setDispatchingTimeout(60ms);
4258 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4259 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4260 mFocusedWindow->setFocusable(false);
4261
4262 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4263 mFocusedWindow->consumeFocusEvent(false);
4264
4265 // Send a key. The ANR timer should start because there is no focused window.
4266 // 'focusedApplication' will get blamed if this timer completes.
4267 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004268 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004269 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004270 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4271 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004272 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004273
4274 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4275 // then the injected touches won't cause the focused event to get dropped.
4276 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4277 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4278 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4279 // For this test, it means that the key would get delivered to the window once it becomes
4280 // focused.
4281 std::this_thread::sleep_for(10ms);
4282
4283 // Touch unfocused window. This should force the pending key to get dropped.
4284 NotifyMotionArgs motionArgs =
4285 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4286 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4287 mDispatcher->notifyMotion(&motionArgs);
4288
4289 // We do not consume the motion right away, because that would require dispatcher to first
4290 // process (== drop) the key event, and by that time, ANR will be raised.
4291 // Set the focused window first.
4292 mFocusedWindow->setFocusable(true);
4293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4294 setFocusedWindow(mFocusedWindow);
4295 mFocusedWindow->consumeFocusEvent(true);
4296 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4297 // to another application. This could be a bug / behaviour in the policy.
4298
4299 mUnfocusedWindow->consumeMotionDown();
4300
4301 ASSERT_TRUE(mDispatcher->waitForIdle());
4302 // Should not ANR because we actually have a focused window. It was just added too slowly.
4303 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4304}
4305
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004306// These tests ensure we cannot send touch events to a window that's positioned behind a window
4307// that has feature NO_INPUT_CHANNEL.
4308// Layout:
4309// Top (closest to user)
4310// mNoInputWindow (above all windows)
4311// mBottomWindow
4312// Bottom (furthest from user)
4313class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4314 virtual void SetUp() override {
4315 InputDispatcherTest::SetUp();
4316
4317 mApplication = std::make_shared<FakeApplicationHandle>();
4318 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4319 "Window without input channel", ADISPLAY_ID_DEFAULT,
4320 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4321
4322 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4323 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4324 // It's perfectly valid for this window to not have an associated input channel
4325
4326 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4327 ADISPLAY_ID_DEFAULT);
4328 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4329
4330 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4331 }
4332
4333protected:
4334 std::shared_ptr<FakeApplicationHandle> mApplication;
4335 sp<FakeWindowHandle> mNoInputWindow;
4336 sp<FakeWindowHandle> mBottomWindow;
4337};
4338
4339TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4340 PointF touchedPoint = {10, 10};
4341
4342 NotifyMotionArgs motionArgs =
4343 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4344 ADISPLAY_ID_DEFAULT, {touchedPoint});
4345 mDispatcher->notifyMotion(&motionArgs);
4346
4347 mNoInputWindow->assertNoEvents();
4348 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4349 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4350 // and therefore should prevent mBottomWindow from receiving touches
4351 mBottomWindow->assertNoEvents();
4352}
4353
4354/**
4355 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4356 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4357 */
4358TEST_F(InputDispatcherMultiWindowOcclusionTests,
4359 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4360 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4361 "Window with input channel and NO_INPUT_CHANNEL",
4362 ADISPLAY_ID_DEFAULT);
4363
4364 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4365 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4366 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4367
4368 PointF touchedPoint = {10, 10};
4369
4370 NotifyMotionArgs motionArgs =
4371 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4372 ADISPLAY_ID_DEFAULT, {touchedPoint});
4373 mDispatcher->notifyMotion(&motionArgs);
4374
4375 mNoInputWindow->assertNoEvents();
4376 mBottomWindow->assertNoEvents();
4377}
4378
Vishnu Nair958da932020-08-21 17:12:37 -07004379class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4380protected:
4381 std::shared_ptr<FakeApplicationHandle> mApp;
4382 sp<FakeWindowHandle> mWindow;
4383 sp<FakeWindowHandle> mMirror;
4384
4385 virtual void SetUp() override {
4386 InputDispatcherTest::SetUp();
4387 mApp = std::make_shared<FakeApplicationHandle>();
4388 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4389 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4390 mWindow->getToken());
4391 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4392 mWindow->setFocusable(true);
4393 mMirror->setFocusable(true);
4394 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4395 }
4396};
4397
4398TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4399 // Request focus on a mirrored window
4400 setFocusedWindow(mMirror);
4401
4402 // window gets focused
4403 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4405 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004406 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4407}
4408
4409// A focused & mirrored window remains focused only if the window and its mirror are both
4410// focusable.
4411TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4412 setFocusedWindow(mMirror);
4413
4414 // window gets focused
4415 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4417 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004418 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4420 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004421 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4422
4423 mMirror->setFocusable(false);
4424 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4425
4426 // window loses focus since one of the windows associated with the token in not focusable
4427 mWindow->consumeFocusEvent(false);
4428
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004429 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4430 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004431 mWindow->assertNoEvents();
4432}
4433
4434// A focused & mirrored window remains focused until the window and its mirror both become
4435// invisible.
4436TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4437 setFocusedWindow(mMirror);
4438
4439 // window gets focused
4440 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4442 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004443 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004444 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4445 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004446 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4447
4448 mMirror->setVisible(false);
4449 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4450
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4452 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004453 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4455 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004456 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4457
4458 mWindow->setVisible(false);
4459 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4460
4461 // window loses focus only after all windows associated with the token become invisible.
4462 mWindow->consumeFocusEvent(false);
4463
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004464 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4465 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004466 mWindow->assertNoEvents();
4467}
4468
4469// A focused & mirrored window remains focused until both windows are removed.
4470TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4471 setFocusedWindow(mMirror);
4472
4473 // window gets focused
4474 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004475 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4476 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004477 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004478 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4479 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004480 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4481
4482 // single window is removed but the window token remains focused
4483 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4484
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4486 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004487 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004488 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4489 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004490 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4491
4492 // Both windows are removed
4493 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4494 mWindow->consumeFocusEvent(false);
4495
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004496 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4497 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004498 mWindow->assertNoEvents();
4499}
4500
4501// Focus request can be pending until one window becomes visible.
4502TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4503 // Request focus on an invisible mirror.
4504 mWindow->setVisible(false);
4505 mMirror->setVisible(false);
4506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4507 setFocusedWindow(mMirror);
4508
4509 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004511 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004512 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004513
4514 mMirror->setVisible(true);
4515 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4516
4517 // window gets focused
4518 mWindow->consumeFocusEvent(true);
4519 // window gets the pending key event
4520 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4521}
Prabir Pradhan99987712020-11-10 18:43:05 -08004522
4523class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4524protected:
4525 std::shared_ptr<FakeApplicationHandle> mApp;
4526 sp<FakeWindowHandle> mWindow;
4527 sp<FakeWindowHandle> mSecondWindow;
4528
4529 void SetUp() override {
4530 InputDispatcherTest::SetUp();
4531 mApp = std::make_shared<FakeApplicationHandle>();
4532 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4533 mWindow->setFocusable(true);
4534 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4535 mSecondWindow->setFocusable(true);
4536
4537 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4538 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4539
4540 setFocusedWindow(mWindow);
4541 mWindow->consumeFocusEvent(true);
4542 }
4543
4544 void notifyPointerCaptureChanged(bool enabled) {
4545 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
4546 mDispatcher->notifyPointerCaptureChanged(&args);
4547 }
4548
4549 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
4550 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4551 mFakePolicy->waitForSetPointerCapture(enabled);
4552 notifyPointerCaptureChanged(enabled);
4553 window->consumeCaptureEvent(enabled);
4554 }
4555};
4556
4557TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4558 // Ensure that capture cannot be obtained for unfocused windows.
4559 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4560 mFakePolicy->assertSetPointerCaptureNotCalled();
4561 mSecondWindow->assertNoEvents();
4562
4563 // Ensure that capture can be enabled from the focus window.
4564 requestAndVerifyPointerCapture(mWindow, true);
4565
4566 // Ensure that capture cannot be disabled from a window that does not have capture.
4567 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4568 mFakePolicy->assertSetPointerCaptureNotCalled();
4569
4570 // Ensure that capture can be disabled from the window with capture.
4571 requestAndVerifyPointerCapture(mWindow, false);
4572}
4573
4574TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4575 requestAndVerifyPointerCapture(mWindow, true);
4576
4577 setFocusedWindow(mSecondWindow);
4578
4579 // Ensure that the capture disabled event was sent first.
4580 mWindow->consumeCaptureEvent(false);
4581 mWindow->consumeFocusEvent(false);
4582 mSecondWindow->consumeFocusEvent(true);
4583 mFakePolicy->waitForSetPointerCapture(false);
4584
4585 // Ensure that additional state changes from InputReader are not sent to the window.
4586 notifyPointerCaptureChanged(false);
4587 notifyPointerCaptureChanged(true);
4588 notifyPointerCaptureChanged(false);
4589 mWindow->assertNoEvents();
4590 mSecondWindow->assertNoEvents();
4591 mFakePolicy->assertSetPointerCaptureNotCalled();
4592}
4593
4594TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4595 requestAndVerifyPointerCapture(mWindow, true);
4596
4597 // InputReader unexpectedly disables and enables pointer capture.
4598 notifyPointerCaptureChanged(false);
4599 notifyPointerCaptureChanged(true);
4600
4601 // Ensure that Pointer Capture is disabled.
Prabir Pradhan7d030382020-12-21 07:58:35 -08004602 mFakePolicy->waitForSetPointerCapture(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004603 mWindow->consumeCaptureEvent(false);
4604 mWindow->assertNoEvents();
4605}
4606
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004607TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4608 requestAndVerifyPointerCapture(mWindow, true);
4609
4610 // The first window loses focus.
4611 setFocusedWindow(mSecondWindow);
4612 mFakePolicy->waitForSetPointerCapture(false);
4613 mWindow->consumeCaptureEvent(false);
4614
4615 // Request Pointer Capture from the second window before the notification from InputReader
4616 // arrives.
4617 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4618 mFakePolicy->waitForSetPointerCapture(true);
4619
4620 // InputReader notifies Pointer Capture was disabled (because of the focus change).
4621 notifyPointerCaptureChanged(false);
4622
4623 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
4624 notifyPointerCaptureChanged(true);
4625
4626 mSecondWindow->consumeFocusEvent(true);
4627 mSecondWindow->consumeCaptureEvent(true);
4628}
4629
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004630class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4631protected:
4632 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00004633
4634 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4635 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4636
4637 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4638 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4639
4640 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4641 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4642 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4643 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4644 MAXIMUM_OBSCURING_OPACITY);
4645
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004646 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004647 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004648 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004649
4650 sp<FakeWindowHandle> mTouchWindow;
4651
4652 virtual void SetUp() override {
4653 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004654 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004655 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4656 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4657 }
4658
4659 virtual void TearDown() override {
4660 InputDispatcherTest::TearDown();
4661 mTouchWindow.clear();
4662 }
4663
4664 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name,
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004665 os::TouchOcclusionMode mode, float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004666 sp<FakeWindowHandle> window = getWindow(uid, name);
4667 window->setFlags(InputWindowInfo::Flag::NOT_TOUCHABLE);
4668 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004669 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004670 return window;
4671 }
4672
4673 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4674 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4675 sp<FakeWindowHandle> window =
4676 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4677 // Generate an arbitrary PID based on the UID
4678 window->setOwnerInfo(1777 + (uid % 10000), uid);
4679 return window;
4680 }
4681
4682 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4683 NotifyMotionArgs args =
4684 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4685 ADISPLAY_ID_DEFAULT, points);
4686 mDispatcher->notifyMotion(&args);
4687 }
4688};
4689
4690TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004691 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004692 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004694
4695 touch();
4696
4697 mTouchWindow->assertNoEvents();
4698}
4699
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004700TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00004701 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
4702 const sp<FakeWindowHandle>& w =
4703 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
4704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4705
4706 touch();
4707
4708 mTouchWindow->assertNoEvents();
4709}
4710
4711TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004712 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
4713 const sp<FakeWindowHandle>& w =
4714 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4716
4717 touch();
4718
4719 w->assertNoEvents();
4720}
4721
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004722TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004723 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
4724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004725
4726 touch();
4727
4728 mTouchWindow->consumeAnyMotionDown();
4729}
4730
4731TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004732 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004733 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004734 w->setFrame(Rect(0, 0, 50, 50));
4735 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004736
4737 touch({PointF{100, 100}});
4738
4739 mTouchWindow->consumeAnyMotionDown();
4740}
4741
4742TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004743 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004744 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4746
4747 touch();
4748
4749 mTouchWindow->consumeAnyMotionDown();
4750}
4751
4752TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
4753 const sp<FakeWindowHandle>& w =
4754 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004756
4757 touch();
4758
4759 mTouchWindow->consumeAnyMotionDown();
4760}
4761
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004762TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
4763 const sp<FakeWindowHandle>& w =
4764 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4765 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4766
4767 touch();
4768
4769 w->assertNoEvents();
4770}
4771
4772/**
4773 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
4774 * inside) while letting them pass-through. Note that even though touch passes through the occluding
4775 * window, the occluding window will still receive ACTION_OUTSIDE event.
4776 */
4777TEST_F(InputDispatcherUntrustedTouchesTest,
4778 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
4779 const sp<FakeWindowHandle>& w =
4780 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4781 w->addFlags(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
4782 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4783
4784 touch();
4785
4786 w->consumeMotionOutside();
4787}
4788
4789TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
4790 const sp<FakeWindowHandle>& w =
4791 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4792 w->addFlags(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
4793 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4794
4795 touch();
4796
4797 InputEvent* event = w->consume();
4798 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
4799 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4800 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
4801 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
4802}
4803
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004804TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004805 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004806 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4807 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004808 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4809
4810 touch();
4811
4812 mTouchWindow->consumeAnyMotionDown();
4813}
4814
4815TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
4816 const sp<FakeWindowHandle>& w =
4817 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4818 MAXIMUM_OBSCURING_OPACITY);
4819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004820
4821 touch();
4822
4823 mTouchWindow->consumeAnyMotionDown();
4824}
4825
4826TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004827 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004828 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4829 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004830 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4831
4832 touch();
4833
4834 mTouchWindow->assertNoEvents();
4835}
4836
4837TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
4838 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
4839 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004840 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4841 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004842 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004843 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4844 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4846
4847 touch();
4848
4849 mTouchWindow->assertNoEvents();
4850}
4851
4852TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
4853 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
4854 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004855 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4856 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004857 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004858 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4859 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4861
4862 touch();
4863
4864 mTouchWindow->consumeAnyMotionDown();
4865}
4866
4867TEST_F(InputDispatcherUntrustedTouchesTest,
4868 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
4869 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004870 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4871 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004872 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004873 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4874 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004875 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4876
4877 touch();
4878
4879 mTouchWindow->consumeAnyMotionDown();
4880}
4881
4882TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
4883 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004884 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4885 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004886 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004887 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4888 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004890
4891 touch();
4892
4893 mTouchWindow->assertNoEvents();
4894}
4895
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004896TEST_F(InputDispatcherUntrustedTouchesTest,
4897 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
4898 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004899 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4900 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004901 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004902 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4903 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4905
4906 touch();
4907
4908 mTouchWindow->assertNoEvents();
4909}
4910
4911TEST_F(InputDispatcherUntrustedTouchesTest,
4912 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
4913 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004914 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4915 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004916 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004917 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4918 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004919 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4920
4921 touch();
4922
4923 mTouchWindow->consumeAnyMotionDown();
4924}
4925
4926TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
4927 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004928 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4929 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004930 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4931
4932 touch();
4933
4934 mTouchWindow->consumeAnyMotionDown();
4935}
4936
4937TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
4938 const sp<FakeWindowHandle>& w =
4939 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
4940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4941
4942 touch();
4943
4944 mTouchWindow->consumeAnyMotionDown();
4945}
4946
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004947TEST_F(InputDispatcherUntrustedTouchesTest,
4948 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
4949 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4950 const sp<FakeWindowHandle>& w =
4951 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
4952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4953
4954 touch();
4955
4956 mTouchWindow->assertNoEvents();
4957}
4958
4959TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
4960 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4961 const sp<FakeWindowHandle>& w =
4962 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
4963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4964
4965 touch();
4966
4967 mTouchWindow->consumeAnyMotionDown();
4968}
4969
4970TEST_F(InputDispatcherUntrustedTouchesTest,
4971 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
4972 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
4973 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004974 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4975 OPACITY_ABOVE_THRESHOLD);
4976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4977
4978 touch();
4979
4980 mTouchWindow->consumeAnyMotionDown();
4981}
4982
4983TEST_F(InputDispatcherUntrustedTouchesTest,
4984 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
4985 const sp<FakeWindowHandle>& w1 =
4986 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4987 OPACITY_BELOW_THRESHOLD);
4988 const sp<FakeWindowHandle>& w2 =
4989 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4990 OPACITY_BELOW_THRESHOLD);
4991 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4992
4993 touch();
4994
4995 mTouchWindow->assertNoEvents();
4996}
4997
4998/**
4999 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5000 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5001 * (which alone would result in allowing touches) does not affect the blocking behavior.
5002 */
5003TEST_F(InputDispatcherUntrustedTouchesTest,
5004 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5005 const sp<FakeWindowHandle>& wB =
5006 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5007 OPACITY_BELOW_THRESHOLD);
5008 const sp<FakeWindowHandle>& wC =
5009 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5010 OPACITY_BELOW_THRESHOLD);
5011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5012
5013 touch();
5014
5015 mTouchWindow->assertNoEvents();
5016}
5017
5018/**
5019 * This test is testing that a window from a different UID but with same application token doesn't
5020 * block the touch. Apps can share the application token for close UI collaboration for example.
5021 */
5022TEST_F(InputDispatcherUntrustedTouchesTest,
5023 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5024 const sp<FakeWindowHandle>& w =
5025 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5026 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005027 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5028
5029 touch();
5030
5031 mTouchWindow->consumeAnyMotionDown();
5032}
5033
arthurhungb89ccb02020-12-30 16:19:01 +08005034class InputDispatcherDragTests : public InputDispatcherTest {
5035protected:
5036 std::shared_ptr<FakeApplicationHandle> mApp;
5037 sp<FakeWindowHandle> mWindow;
5038 sp<FakeWindowHandle> mSecondWindow;
5039 sp<FakeWindowHandle> mDragWindow;
5040
5041 void SetUp() override {
5042 InputDispatcherTest::SetUp();
5043 mApp = std::make_shared<FakeApplicationHandle>();
5044 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5045 mWindow->setFrame(Rect(0, 0, 100, 100));
5046 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
5047
5048 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5049 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
5050 mSecondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
5051
5052 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5054 }
5055
5056 // Start performing drag, we will create a drag window and transfer touch to it.
5057 void performDrag() {
5058 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5059 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5060 {50, 50}))
5061 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5062
5063 // Window should receive motion event.
5064 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5065
5066 // The drag window covers the entire display
5067 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5068 mDispatcher->setInputWindows(
5069 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5070
5071 // Transfer touch focus to the drag window
5072 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5073 true /* isDragDrop */);
5074 mWindow->consumeMotionCancel();
5075 mDragWindow->consumeMotionDown();
5076 }
arthurhung6d4bed92021-03-17 11:59:33 +08005077
5078 // Start performing drag, we will create a drag window and transfer touch to it.
5079 void performStylusDrag() {
5080 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5081 injectMotionEvent(mDispatcher,
5082 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5083 AINPUT_SOURCE_STYLUS)
5084 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5085 .pointer(PointerBuilder(0,
5086 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5087 .x(50)
5088 .y(50))
5089 .build()));
5090 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5091
5092 // The drag window covers the entire display
5093 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5094 mDispatcher->setInputWindows(
5095 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5096
5097 // Transfer touch focus to the drag window
5098 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5099 true /* isDragDrop */);
5100 mWindow->consumeMotionCancel();
5101 mDragWindow->consumeMotionDown();
5102 }
arthurhungb89ccb02020-12-30 16:19:01 +08005103};
5104
5105TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5106 performDrag();
5107
5108 // Move on window.
5109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5110 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5111 ADISPLAY_ID_DEFAULT, {50, 50}))
5112 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5113 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5114 mWindow->consumeDragEvent(false, 50, 50);
5115 mSecondWindow->assertNoEvents();
5116
5117 // Move to another window.
5118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5119 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5120 ADISPLAY_ID_DEFAULT, {150, 50}))
5121 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5122 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5123 mWindow->consumeDragEvent(true, 150, 50);
5124 mSecondWindow->consumeDragEvent(false, 50, 50);
5125
5126 // Move back to original window.
5127 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5128 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5129 ADISPLAY_ID_DEFAULT, {50, 50}))
5130 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5131 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5132 mWindow->consumeDragEvent(false, 50, 50);
5133 mSecondWindow->consumeDragEvent(true, -50, 50);
5134
5135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5136 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5138 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5139 mWindow->assertNoEvents();
5140 mSecondWindow->assertNoEvents();
5141}
5142
arthurhungf452d0b2021-01-06 00:19:52 +08005143TEST_F(InputDispatcherDragTests, DragAndDrop) {
5144 performDrag();
5145
5146 // Move on window.
5147 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5148 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5149 ADISPLAY_ID_DEFAULT, {50, 50}))
5150 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5151 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5152 mWindow->consumeDragEvent(false, 50, 50);
5153 mSecondWindow->assertNoEvents();
5154
5155 // Move to another window.
5156 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5157 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5158 ADISPLAY_ID_DEFAULT, {150, 50}))
5159 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5160 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5161 mWindow->consumeDragEvent(true, 150, 50);
5162 mSecondWindow->consumeDragEvent(false, 50, 50);
5163
5164 // drop to another window.
5165 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5166 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5167 {150, 50}))
5168 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5169 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5170 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5171 mWindow->assertNoEvents();
5172 mSecondWindow->assertNoEvents();
5173}
5174
arthurhung6d4bed92021-03-17 11:59:33 +08005175TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5176 performStylusDrag();
5177
5178 // Move on window and keep button pressed.
5179 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5180 injectMotionEvent(mDispatcher,
5181 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5182 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5183 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5184 .x(50)
5185 .y(50))
5186 .build()))
5187 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5188 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5189 mWindow->consumeDragEvent(false, 50, 50);
5190 mSecondWindow->assertNoEvents();
5191
5192 // Move to another window and release button, expect to drop item.
5193 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5194 injectMotionEvent(mDispatcher,
5195 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5196 .buttonState(0)
5197 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5198 .x(150)
5199 .y(50))
5200 .build()))
5201 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5202 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5203 mWindow->assertNoEvents();
5204 mSecondWindow->assertNoEvents();
5205 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5206
5207 // nothing to the window.
5208 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5209 injectMotionEvent(mDispatcher,
5210 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5211 .buttonState(0)
5212 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5213 .x(150)
5214 .y(50))
5215 .build()))
5216 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5217 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5218 mWindow->assertNoEvents();
5219 mSecondWindow->assertNoEvents();
5220}
5221
Arthur Hung6d0571e2021-04-09 20:18:16 +08005222TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5223 performDrag();
5224
5225 // Set second window invisible.
5226 mSecondWindow->setVisible(false);
5227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5228
5229 // Move on window.
5230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5231 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5232 ADISPLAY_ID_DEFAULT, {50, 50}))
5233 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5234 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5235 mWindow->consumeDragEvent(false, 50, 50);
5236 mSecondWindow->assertNoEvents();
5237
5238 // Move to another window.
5239 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5240 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5241 ADISPLAY_ID_DEFAULT, {150, 50}))
5242 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5243 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5244 mWindow->consumeDragEvent(true, 150, 50);
5245 mSecondWindow->assertNoEvents();
5246
5247 // drop to another window.
5248 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5249 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5250 {150, 50}))
5251 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5252 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5253 mFakePolicy->assertDropTargetEquals(nullptr);
5254 mWindow->assertNoEvents();
5255 mSecondWindow->assertNoEvents();
5256}
5257
Garfield Tane84e6f92019-08-29 17:28:41 -07005258} // namespace android::inputdispatcher