blob: b3fea742191a1180db1b7af0f4b037756d78ed6c [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
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -070019#include <android-base/properties.h>
Prabir Pradhana3ab87a2022-01-27 10:00:21 -080020#include <android-base/silent_death_test.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080021#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070022#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070023#include <binder/Binder.h>
Michael Wright8e9a8562022-02-09 13:44:29 +000024#include <fcntl.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100026#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080027#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080028#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100029
Garfield Tan1c7bc862020-01-28 13:24:04 -080030#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070031#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080032#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080033#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080034
Garfield Tan1c7bc862020-01-28 13:24:04 -080035using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050036using android::gui::FocusRequest;
37using android::gui::TouchOcclusionMode;
38using android::gui::WindowInfo;
39using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080040using android::os::InputEventInjectionResult;
41using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010042using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080043
Garfield Tane84e6f92019-08-29 17:28:41 -070044namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080045
46// An arbitrary time value.
47static const nsecs_t ARBITRARY_TIME = 1234;
48
49// An arbitrary device id.
50static const int32_t DEVICE_ID = 1;
51
Jeff Brownf086ddb2014-02-11 14:28:48 -080052// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000053static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
54static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080055
Michael Wrightd02c5b62014-02-10 15:10:22 -080056// An arbitrary injector pid / uid pair that has permission to inject events.
57static const int32_t INJECTOR_PID = 999;
58static const int32_t INJECTOR_UID = 1001;
59
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000060// An arbitrary pid of the gesture monitor window
61static constexpr int32_t MONITOR_PID = 2001;
62
chaviwd1c23182019-12-20 18:44:56 -080063struct PointF {
64 float x;
65 float y;
66};
Michael Wrightd02c5b62014-02-10 15:10:22 -080067
Gang Wang342c9272020-01-13 13:15:04 -050068/**
69 * Return a DOWN key event with KEYCODE_A.
70 */
71static KeyEvent getTestKeyEvent() {
72 KeyEvent event;
73
Garfield Tanfbe732e2020-01-24 11:26:14 -080074 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
75 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
76 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050077 return event;
78}
79
Siarhei Vishniakouca205502021-07-16 21:31:58 +000080static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
81 ASSERT_EQ(expectedAction, receivedAction)
82 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
83 << MotionEvent::actionToString(receivedAction);
84}
85
Michael Wrightd02c5b62014-02-10 15:10:22 -080086// --- FakeInputDispatcherPolicy ---
87
88class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
89 InputDispatcherConfiguration mConfig;
90
Prabir Pradhanedd96402022-02-15 01:46:16 -080091 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
92
Michael Wrightd02c5b62014-02-10 15:10:22 -080093protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100094 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080095
96public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100097 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080098
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080099 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700100 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
101 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
102 EXPECT_EQ(event.getDisplayId(), args.displayId);
103
104 const auto& keyEvent = static_cast<const KeyEvent&>(event);
105 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
106 EXPECT_EQ(keyEvent.getAction(), args.action);
107 });
Jackal Guof9696682018-10-05 12:23:23 +0800108 }
109
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700110 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
111 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
112 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
113 EXPECT_EQ(event.getDisplayId(), args.displayId);
114
115 const auto& motionEvent = static_cast<const MotionEvent&>(event);
116 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
117 EXPECT_EQ(motionEvent.getAction(), args.action);
118 EXPECT_EQ(motionEvent.getX(0), point.x);
119 EXPECT_EQ(motionEvent.getY(0), point.y);
120 EXPECT_EQ(motionEvent.getRawX(0), point.x);
121 EXPECT_EQ(motionEvent.getRawY(0), point.y);
122 });
Jackal Guof9696682018-10-05 12:23:23 +0800123 }
124
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700125 void assertFilterInputEventWasNotCalled() {
126 std::scoped_lock lock(mLock);
127 ASSERT_EQ(nullptr, mFilteredEvent);
128 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800130 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700131 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800132 ASSERT_TRUE(mConfigurationChangedTime)
133 << "Timed out waiting for configuration changed call";
134 ASSERT_EQ(*mConfigurationChangedTime, when);
135 mConfigurationChangedTime = std::nullopt;
136 }
137
138 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700139 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800140 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800141 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800142 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
143 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
144 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
145 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
146 mLastNotifySwitch = std::nullopt;
147 }
148
chaviwfd6d3512019-03-25 13:23:49 -0700149 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700150 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800151 ASSERT_EQ(touchedToken, mOnPointerDownToken);
152 mOnPointerDownToken.clear();
153 }
154
155 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700156 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800157 ASSERT_TRUE(mOnPointerDownToken == nullptr)
158 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700159 }
160
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700161 // This function must be called soon after the expected ANR timer starts,
162 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500163 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700164 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500165 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800166 std::unique_lock lock(mLock);
167 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500168 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800169 ASSERT_NO_FATAL_FAILURE(
170 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500171 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700172 }
173
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000174 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800175 const sp<WindowInfoHandle>& window) {
176 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
177 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
178 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500179 }
180
Prabir Pradhanedd96402022-02-15 01:46:16 -0800181 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
182 const sp<IBinder>& expectedToken,
183 int32_t expectedPid) {
184 std::unique_lock lock(mLock);
185 android::base::ScopedLockAssertion assumeLocked(mLock);
186 AnrResult result;
187 ASSERT_NO_FATAL_FAILURE(result =
188 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
189 const auto& [token, pid] = result;
190 ASSERT_EQ(expectedToken, token);
191 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500192 }
193
Prabir Pradhanedd96402022-02-15 01:46:16 -0800194 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000195 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500196 std::unique_lock lock(mLock);
197 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800198 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
199 const auto& [token, _] = result;
200 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000201 }
202
Prabir Pradhanedd96402022-02-15 01:46:16 -0800203 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
204 int32_t expectedPid) {
205 std::unique_lock lock(mLock);
206 android::base::ScopedLockAssertion assumeLocked(mLock);
207 AnrResult result;
208 ASSERT_NO_FATAL_FAILURE(
209 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
210 const auto& [token, pid] = result;
211 ASSERT_EQ(expectedToken, token);
212 ASSERT_EQ(expectedPid, pid);
213 }
214
215 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000216 sp<IBinder> getResponsiveWindowToken() {
217 std::unique_lock lock(mLock);
218 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800219 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
220 const auto& [token, _] = result;
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());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800227 ASSERT_TRUE(mAnrWindows.empty());
228 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500229 << "ANR was not called, but please also consume the 'connection is responsive' "
230 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700231 }
232
Garfield Tan1c7bc862020-01-28 13:24:04 -0800233 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
234 mConfig.keyRepeatTimeout = timeout;
235 mConfig.keyRepeatDelay = delay;
236 }
237
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000238 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800239 std::unique_lock lock(mLock);
240 base::ScopedLockAssertion assumeLocked(mLock);
241
242 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
243 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000244 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800245 enabled;
246 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000247 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
248 << ") to be called.";
249 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800250 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000251 auto request = *mPointerCaptureRequest;
252 mPointerCaptureRequest.reset();
253 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800254 }
255
256 void assertSetPointerCaptureNotCalled() {
257 std::unique_lock lock(mLock);
258 base::ScopedLockAssertion assumeLocked(mLock);
259
260 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000261 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800262 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000263 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800264 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000265 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800266 }
267
arthurhungf452d0b2021-01-06 00:19:52 +0800268 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
269 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800270 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800271 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800272 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800273 }
274
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800275 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
276 std::unique_lock lock(mLock);
277 base::ScopedLockAssertion assumeLocked(mLock);
278 std::optional<sp<IBinder>> receivedToken =
279 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
280 mNotifyInputChannelBroken);
281 ASSERT_TRUE(receivedToken.has_value());
282 ASSERT_EQ(token, *receivedToken);
283 }
284
Michael Wrightd02c5b62014-02-10 15:10:22 -0800285private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700286 std::mutex mLock;
287 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
288 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
289 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
290 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800291
Prabir Pradhan99987712020-11-10 18:43:05 -0800292 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000293
294 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800295
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700296 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700297 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800298 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
299 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700300 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800301 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
302 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700303
arthurhungf452d0b2021-01-06 00:19:52 +0800304 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800305 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800306
Prabir Pradhanedd96402022-02-15 01:46:16 -0800307 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
308 // for a specific container to become non-empty. When the container is non-empty, return the
309 // first entry from the container and erase it.
310 template <class T>
311 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
312 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
313 // If there is an ANR, Dispatcher won't be idle because there are still events
314 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
315 // before checking if ANR was called.
316 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
317 // to provide it some time to act. 100ms seems reasonable.
318 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
319 const std::chrono::time_point start = std::chrono::steady_clock::now();
320 std::optional<T> token =
321 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
322 if (!token.has_value()) {
323 ADD_FAILURE() << "Did not receive the ANR callback";
324 return {};
325 }
326
327 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
328 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
329 // the dispatcher started counting before this function was called
330 if (std::chrono::abs(timeout - waited) > 100ms) {
331 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
332 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
333 << "ms, but waited "
334 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
335 << "ms instead";
336 }
337 return *token;
338 }
339
340 template <class T>
341 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
342 std::queue<T>& storage,
343 std::unique_lock<std::mutex>& lock,
344 std::condition_variable& condition)
345 REQUIRES(mLock) {
346 condition.wait_for(lock, timeout,
347 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
348 if (storage.empty()) {
349 ADD_FAILURE() << "Did not receive the expected callback";
350 return std::nullopt;
351 }
352 T item = storage.front();
353 storage.pop();
354 return std::make_optional(item);
355 }
356
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600357 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700358 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800359 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360 }
361
Prabir Pradhanedd96402022-02-15 01:46:16 -0800362 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
363 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700364 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800365 ASSERT_TRUE(pid.has_value());
366 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700367 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500368 }
369
Prabir Pradhanedd96402022-02-15 01:46:16 -0800370 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
371 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500372 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800373 ASSERT_TRUE(pid.has_value());
374 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500375 mNotifyAnr.notify_all();
376 }
377
378 void notifyNoFocusedWindowAnr(
379 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
380 std::scoped_lock lock(mLock);
381 mAnrApplications.push(applicationHandle);
382 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800383 }
384
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800385 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
386 std::scoped_lock lock(mLock);
387 mBrokenInputChannels.push(connectionToken);
388 mNotifyInputChannelBroken.notify_all();
389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600391 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700392
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600393 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700394 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
395 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
396 const std::vector<float>& values) override {}
397
398 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
399 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000400
Chris Yefb552902021-02-03 17:18:37 -0800401 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
402
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600403 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800404 *outConfig = mConfig;
405 }
406
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600407 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700408 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800409 switch (inputEvent->getType()) {
410 case AINPUT_EVENT_TYPE_KEY: {
411 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800412 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800413 break;
414 }
415
416 case AINPUT_EVENT_TYPE_MOTION: {
417 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800418 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800419 break;
420 }
421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422 return true;
423 }
424
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600425 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600427 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600429 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 return 0;
431 }
432
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600433 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 return false;
435 }
436
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600437 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
438 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700439 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800440 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
441 * essentially a passthrough for notifySwitch.
442 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800443 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 }
445
Sean Stoutb4e0a592021-02-23 07:34:53 -0800446 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800448 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
449 return pid == INJECTOR_PID && uid == INJECTOR_UID;
450 }
Jackal Guof9696682018-10-05 12:23:23 +0800451
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600452 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700453 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700454 mOnPointerDownToken = newToken;
455 }
456
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000457 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800458 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000459 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800460 mPointerCaptureChangedCondition.notify_all();
461 }
462
arthurhungf452d0b2021-01-06 00:19:52 +0800463 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
464 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800465 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800466 mDropTargetWindowToken = token;
467 }
468
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700469 void assertFilterInputEventWasCalledInternal(
470 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700471 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800472 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700473 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800474 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800476};
477
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478// --- InputDispatcherTest ---
479
480class InputDispatcherTest : public testing::Test {
481protected:
482 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700483 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000485 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700487 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800488 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000489 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700490 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800491 }
492
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000493 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700494 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800495 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700496 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700498
499 /**
500 * Used for debugging when writing the test
501 */
502 void dumpDispatcherState() {
503 std::string dump;
504 mDispatcher->dump(dump);
505 std::stringstream ss(dump);
506 std::string to;
507
508 while (std::getline(ss, to, '\n')) {
509 ALOGE("%s", to.c_str());
510 }
511 }
Vishnu Nair958da932020-08-21 17:12:37 -0700512
chaviw3277faf2021-05-19 16:45:23 -0500513 void setFocusedWindow(const sp<WindowInfoHandle>& window,
514 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700515 FocusRequest request;
516 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000517 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700518 if (focusedWindow) {
519 request.focusedToken = focusedWindow->getToken();
520 }
521 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
522 request.displayId = window->getInfo()->displayId;
523 mDispatcher->setFocusedWindow(request);
524 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525};
526
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
528 KeyEvent event;
529
530 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800531 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
532 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600533 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
534 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800535 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700536 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800537 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800538 << "Should reject key events with undefined action.";
539
540 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800541 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
542 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600543 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800544 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700545 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800546 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 << "Should reject key events with ACTION_MULTIPLE.";
548}
549
550TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
551 MotionEvent event;
552 PointerProperties pointerProperties[MAX_POINTERS + 1];
553 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800554 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800555 pointerProperties[i].clear();
556 pointerProperties[i].id = i;
557 pointerCoords[i].clear();
558 }
559
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800560 // Some constants commonly used below
561 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
562 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
563 constexpr int32_t metaState = AMETA_NONE;
564 constexpr MotionClassification classification = MotionClassification::NONE;
565
chaviw9eaa22c2020-07-01 16:21:27 -0700566 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800567 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800568 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700569 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
570 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700571 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
572 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700573 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800574 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700575 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800576 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 << "Should reject motion events with undefined action.";
578
579 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800580 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700581 AMOTION_EVENT_ACTION_POINTER_DOWN |
582 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700583 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
584 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700585 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500586 /*pointerCount*/ 1, pointerProperties, 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 down index too large.";
591
Garfield Tanfbe732e2020-01-24 11:26:14 -0800592 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700593 AMOTION_EVENT_ACTION_POINTER_DOWN |
594 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700595 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
596 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700597 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500598 /*pointerCount*/ 1, 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 pointer down index too small.";
603
604 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800605 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700606 AMOTION_EVENT_ACTION_POINTER_UP |
607 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700608 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
609 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700610 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500611 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800612 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700613 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800614 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800615 << "Should reject motion events with pointer up index too large.";
616
Garfield Tanfbe732e2020-01-24 11:26:14 -0800617 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700618 AMOTION_EVENT_ACTION_POINTER_UP |
619 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700620 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
621 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700622 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500623 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700625 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800626 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 << "Should reject motion events with pointer up index too small.";
628
629 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800630 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
631 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700632 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700633 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
634 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700635 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800636 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700637 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800638 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800639 << "Should reject motion events with 0 pointers.";
640
Garfield Tanfbe732e2020-01-24 11:26:14 -0800641 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
642 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700643 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700644 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
645 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700646 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800647 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700648 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800649 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 << "Should reject motion events with more than MAX_POINTERS pointers.";
651
652 // Rejects motion events with invalid pointer ids.
653 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800654 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
655 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700656 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700657 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
658 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700659 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800660 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700661 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800662 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 << "Should reject motion events with pointer ids less than 0.";
664
665 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800666 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
667 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700668 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700669 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
670 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700671 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800672 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700673 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800674 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800675 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
676
677 // Rejects motion events with duplicate pointer ids.
678 pointerProperties[0].id = 1;
679 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800680 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
681 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700682 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700683 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
684 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700685 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800686 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700687 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800688 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800689 << "Should reject motion events with duplicate pointer ids.";
690}
691
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800692/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
693
694TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
695 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800696 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800697 mDispatcher->notifyConfigurationChanged(&args);
698 ASSERT_TRUE(mDispatcher->waitForIdle());
699
700 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
701}
702
703TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800704 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
705 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800706 mDispatcher->notifySwitch(&args);
707
708 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
709 args.policyFlags |= POLICY_FLAG_TRUSTED;
710 mFakePolicy->assertNotifySwitchWasCalled(args);
711}
712
Arthur Hungb92218b2018-08-14 12:00:21 +0800713// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700714static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700715// Default input dispatching timeout if there is no focused application or paused window
716// from which to determine an appropriate dispatching timeout.
717static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
718 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
719 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800720
721class FakeApplicationHandle : public InputApplicationHandle {
722public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700723 FakeApplicationHandle() {
724 mInfo.name = "Fake Application";
725 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500726 mInfo.dispatchingTimeoutMillis =
727 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700728 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800729 virtual ~FakeApplicationHandle() {}
730
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000731 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700732
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500733 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
734 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700735 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800736};
737
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800738class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800739public:
Garfield Tan15601662020-09-22 15:32:38 -0700740 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800741 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700742 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800743 }
744
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800745 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700746 InputEvent* event;
747 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
748 if (!consumeSeq) {
749 return nullptr;
750 }
751 finishEvent(*consumeSeq);
752 return event;
753 }
754
755 /**
756 * Receive an event without acknowledging it.
757 * Return the sequence number that could later be used to send finished signal.
758 */
759 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800760 uint32_t consumeSeq;
761 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800762
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800763 std::chrono::time_point start = std::chrono::steady_clock::now();
764 status_t status = WOULD_BLOCK;
765 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800766 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800767 &event);
768 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
769 if (elapsed > 100ms) {
770 break;
771 }
772 }
773
774 if (status == WOULD_BLOCK) {
775 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700776 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800777 }
778
779 if (status != OK) {
780 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700781 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800782 }
783 if (event == nullptr) {
784 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700785 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800786 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700787 if (outEvent != nullptr) {
788 *outEvent = event;
789 }
790 return consumeSeq;
791 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800792
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700793 /**
794 * To be used together with "receiveEvent" to complete the consumption of an event.
795 */
796 void finishEvent(uint32_t consumeSeq) {
797 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
798 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800799 }
800
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000801 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
802 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
803 ASSERT_EQ(OK, status);
804 }
805
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000806 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
807 std::optional<int32_t> expectedDisplayId,
808 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800809 InputEvent* event = consume();
810
811 ASSERT_NE(nullptr, event) << mName.c_str()
812 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800813 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700814 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800815 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800816
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000817 if (expectedDisplayId.has_value()) {
818 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
819 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800820
Tiger Huang8664f8c2018-10-11 19:14:35 +0800821 switch (expectedEventType) {
822 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800823 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
824 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000825 if (expectedFlags.has_value()) {
826 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
827 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800828 break;
829 }
830 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800831 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000832 assertMotionAction(expectedAction, motionEvent.getAction());
833
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000834 if (expectedFlags.has_value()) {
835 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
836 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800837 break;
838 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100839 case AINPUT_EVENT_TYPE_FOCUS: {
840 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
841 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800842 case AINPUT_EVENT_TYPE_CAPTURE: {
843 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
844 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000845 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
846 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
847 }
arthurhungb89ccb02020-12-30 16:19:01 +0800848 case AINPUT_EVENT_TYPE_DRAG: {
849 FAIL() << "Use 'consumeDragEvent' for DRAG events";
850 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800851 default: {
852 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
853 }
854 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800855 }
856
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100857 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
858 InputEvent* event = consume();
859 ASSERT_NE(nullptr, event) << mName.c_str()
860 << ": consumer should have returned non-NULL event.";
861 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
862 << "Got " << inputEventTypeToString(event->getType())
863 << " event instead of FOCUS event";
864
865 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
866 << mName.c_str() << ": event displayId should always be NONE.";
867
868 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
869 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100870 }
871
Prabir Pradhan99987712020-11-10 18:43:05 -0800872 void consumeCaptureEvent(bool hasCapture) {
873 const InputEvent* event = consume();
874 ASSERT_NE(nullptr, event) << mName.c_str()
875 << ": consumer should have returned non-NULL event.";
876 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
877 << "Got " << inputEventTypeToString(event->getType())
878 << " event instead of CAPTURE event";
879
880 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
881 << mName.c_str() << ": event displayId should always be NONE.";
882
883 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
884 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
885 }
886
arthurhungb89ccb02020-12-30 16:19:01 +0800887 void consumeDragEvent(bool isExiting, float x, float y) {
888 const InputEvent* event = consume();
889 ASSERT_NE(nullptr, event) << mName.c_str()
890 << ": consumer should have returned non-NULL event.";
891 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
892 << "Got " << inputEventTypeToString(event->getType())
893 << " event instead of DRAG event";
894
895 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
896 << mName.c_str() << ": event displayId should always be NONE.";
897
898 const auto& dragEvent = static_cast<const DragEvent&>(*event);
899 EXPECT_EQ(isExiting, dragEvent.isExiting());
900 EXPECT_EQ(x, dragEvent.getX());
901 EXPECT_EQ(y, dragEvent.getY());
902 }
903
Antonio Kantekf16f2832021-09-28 04:39:20 +0000904 void consumeTouchModeEvent(bool inTouchMode) {
905 const InputEvent* event = consume();
906 ASSERT_NE(nullptr, event) << mName.c_str()
907 << ": consumer should have returned non-NULL event.";
908 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
909 << "Got " << inputEventTypeToString(event->getType())
910 << " event instead of TOUCH_MODE event";
911
912 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
913 << mName.c_str() << ": event displayId should always be NONE.";
914 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
915 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
916 }
917
chaviwd1c23182019-12-20 18:44:56 -0800918 void assertNoEvents() {
919 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700920 if (event == nullptr) {
921 return;
922 }
923 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
924 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
925 ADD_FAILURE() << "Received key event "
926 << KeyEvent::actionToString(keyEvent.getAction());
927 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
928 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
929 ADD_FAILURE() << "Received motion event "
930 << MotionEvent::actionToString(motionEvent.getAction());
931 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
932 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
933 ADD_FAILURE() << "Received focus event, hasFocus = "
934 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800935 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
936 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
937 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
938 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000939 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
940 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
941 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
942 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700943 }
944 FAIL() << mName.c_str()
945 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800946 }
947
948 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
949
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800950 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
951
chaviwd1c23182019-12-20 18:44:56 -0800952protected:
953 std::unique_ptr<InputConsumer> mConsumer;
954 PreallocatedInputEventFactory mEventFactory;
955
956 std::string mName;
957};
958
chaviw3277faf2021-05-19 16:45:23 -0500959class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800960public:
961 static const int32_t WIDTH = 600;
962 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800963
Chris Yea209fde2020-07-22 13:54:51 -0700964 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700965 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500966 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800967 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500968 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700969 base::Result<std::unique_ptr<InputChannel>> channel =
970 dispatcher->createInputChannel(name);
971 token = (*channel)->getConnectionToken();
972 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800973 }
974
975 inputApplicationHandle->updateInfo();
976 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
977
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500978 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700979 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800980 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500981 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000982 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800983 mInfo.frameLeft = 0;
984 mInfo.frameTop = 0;
985 mInfo.frameRight = WIDTH;
986 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700987 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800988 mInfo.globalScaleFactor = 1.0;
989 mInfo.touchableRegion.clear();
990 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
chaviwd1c23182019-12-20 18:44:56 -0800991 mInfo.ownerPid = INJECTOR_PID;
992 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800993 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -0800994 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -0800995 }
996
Arthur Hungabbb9d82021-09-01 14:52:30 +0000997 sp<FakeWindowHandle> clone(
998 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700999 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001000 sp<FakeWindowHandle> handle =
1001 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1002 displayId, mInfo.token);
1003 return handle;
1004 }
1005
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001006 void setTouchable(bool touchable) {
1007 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1008 }
chaviwd1c23182019-12-20 18:44:56 -08001009
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001010 void setFocusable(bool focusable) {
1011 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1012 }
1013
1014 void setVisible(bool visible) {
1015 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1016 }
Vishnu Nair958da932020-08-21 17:12:37 -07001017
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001018 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001019 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001020 }
1021
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001022 void setPaused(bool paused) {
1023 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1024 }
1025
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001026 void setPreventSplitting(bool preventSplitting) {
1027 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001028 }
1029
1030 void setSlippery(bool slippery) {
1031 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1032 }
1033
1034 void setWatchOutsideTouch(bool watchOutside) {
1035 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1036 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001037
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001038 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1039
1040 void setInterceptsStylus(bool interceptsStylus) {
1041 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1042 }
1043
1044 void setDropInput(bool dropInput) {
1045 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1046 }
1047
1048 void setDropInputIfObscured(bool dropInputIfObscured) {
1049 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1050 }
1051
1052 void setNoInputChannel(bool noInputChannel) {
1053 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1054 }
1055
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001056 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1057
chaviw3277faf2021-05-19 16:45:23 -05001058 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001059
Bernardo Rufino7393d172021-02-26 13:56:11 +00001060 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1061
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001062 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001063 mInfo.frameLeft = frame.left;
1064 mInfo.frameTop = frame.top;
1065 mInfo.frameRight = frame.right;
1066 mInfo.frameBottom = frame.bottom;
1067 mInfo.touchableRegion.clear();
1068 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001069
1070 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1071 ui::Transform translate;
1072 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1073 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001074 }
1075
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001076 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1077
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001078 void setIsWallpaper(bool isWallpaper) {
1079 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1080 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001081
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001082 void setDupTouchToWallpaper(bool hasWallpaper) {
1083 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1084 }
chaviwd1c23182019-12-20 18:44:56 -08001085
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001086 void setTrustedOverlay(bool trustedOverlay) {
1087 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1088 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001089
chaviw9eaa22c2020-07-01 16:21:27 -07001090 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1091 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1092 }
1093
1094 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001095
yunho.shinf4a80b82020-11-16 21:13:57 +09001096 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1097
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001098 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1099 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1100 expectedFlags);
1101 }
1102
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001103 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1104 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1105 }
1106
Svet Ganov5d3bc372020-01-26 23:11:07 -08001107 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001108 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001109 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1110 expectedFlags);
1111 }
1112
1113 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001114 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001115 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1116 expectedFlags);
1117 }
1118
1119 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001120 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001121 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1122 }
1123
1124 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1125 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001126 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1127 expectedFlags);
1128 }
1129
Svet Ganov5d3bc372020-01-26 23:11:07 -08001130 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001131 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1132 int32_t expectedFlags = 0) {
1133 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1134 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001135 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1136 }
1137
1138 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001139 int32_t expectedFlags = 0) {
1140 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1141 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001142 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1143 }
1144
1145 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001146 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001147 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1148 expectedFlags);
1149 }
1150
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001151 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1152 int32_t expectedFlags = 0) {
1153 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1154 expectedFlags);
1155 }
1156
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001157 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1158 int32_t expectedFlags = 0) {
1159 InputEvent* event = consume();
1160 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1161 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1162 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1163 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1164 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1165 }
1166
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001167 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1168 ASSERT_NE(mInputReceiver, nullptr)
1169 << "Cannot consume events from a window with no receiver";
1170 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1171 }
1172
Prabir Pradhan99987712020-11-10 18:43:05 -08001173 void consumeCaptureEvent(bool hasCapture) {
1174 ASSERT_NE(mInputReceiver, nullptr)
1175 << "Cannot consume events from a window with no receiver";
1176 mInputReceiver->consumeCaptureEvent(hasCapture);
1177 }
1178
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001179 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1180 std::optional<int32_t> expectedDisplayId,
1181 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001182 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1183 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1184 expectedFlags);
1185 }
1186
arthurhungb89ccb02020-12-30 16:19:01 +08001187 void consumeDragEvent(bool isExiting, float x, float y) {
1188 mInputReceiver->consumeDragEvent(isExiting, x, y);
1189 }
1190
Antonio Kantekf16f2832021-09-28 04:39:20 +00001191 void consumeTouchModeEvent(bool inTouchMode) {
1192 ASSERT_NE(mInputReceiver, nullptr)
1193 << "Cannot consume events from a window with no receiver";
1194 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1195 }
1196
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001197 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001198 if (mInputReceiver == nullptr) {
1199 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1200 return std::nullopt;
1201 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001202 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001203 }
1204
1205 void finishEvent(uint32_t sequenceNum) {
1206 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1207 mInputReceiver->finishEvent(sequenceNum);
1208 }
1209
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001210 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1211 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1212 mInputReceiver->sendTimeline(inputEventId, timeline);
1213 }
1214
chaviwaf87b3e2019-10-01 16:59:28 -07001215 InputEvent* consume() {
1216 if (mInputReceiver == nullptr) {
1217 return nullptr;
1218 }
1219 return mInputReceiver->consume();
1220 }
1221
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001222 MotionEvent* consumeMotion() {
1223 InputEvent* event = consume();
1224 if (event == nullptr) {
1225 ADD_FAILURE() << "Consume failed : no event";
1226 return nullptr;
1227 }
1228 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1229 ADD_FAILURE() << "Instead of motion event, got "
1230 << inputEventTypeToString(event->getType());
1231 return nullptr;
1232 }
1233 return static_cast<MotionEvent*>(event);
1234 }
1235
Arthur Hungb92218b2018-08-14 12:00:21 +08001236 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001237 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001238 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001239 return; // Can't receive events if the window does not have input channel
1240 }
1241 ASSERT_NE(nullptr, mInputReceiver)
1242 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001243 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001244 }
1245
chaviwaf87b3e2019-10-01 16:59:28 -07001246 sp<IBinder> getToken() { return mInfo.token; }
1247
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001248 const std::string& getName() { return mName; }
1249
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001250 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1251 mInfo.ownerPid = ownerPid;
1252 mInfo.ownerUid = ownerUid;
1253 }
1254
Prabir Pradhanedd96402022-02-15 01:46:16 -08001255 int32_t getPid() const { return mInfo.ownerPid; }
1256
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001257 void destroyReceiver() { mInputReceiver = nullptr; }
1258
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001259 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1260
chaviwd1c23182019-12-20 18:44:56 -08001261private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001262 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001263 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001264 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001265};
1266
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001267std::atomic<int32_t> FakeWindowHandle::sId{1};
1268
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001269static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001270 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001271 int32_t displayId = ADISPLAY_ID_NONE,
1272 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001273 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1274 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001275 KeyEvent event;
1276 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1277
1278 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001279 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001280 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1281 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001282
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001283 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1284 if (!allowKeyRepeat) {
1285 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1286 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001287 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001288 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001289 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001290}
1291
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001292static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001293 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001294 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1295}
1296
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001297// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1298// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1299// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001300static InputEventInjectionResult injectKeyDownNoRepeat(
1301 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001302 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1303 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1304 /* allowKeyRepeat */ false);
1305}
1306
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001307static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001308 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001309 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1310}
1311
Garfield Tandf26e862020-07-01 20:18:19 -07001312class PointerBuilder {
1313public:
1314 PointerBuilder(int32_t id, int32_t toolType) {
1315 mProperties.clear();
1316 mProperties.id = id;
1317 mProperties.toolType = toolType;
1318 mCoords.clear();
1319 }
1320
1321 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1322
1323 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1324
1325 PointerBuilder& axis(int32_t axis, float value) {
1326 mCoords.setAxisValue(axis, value);
1327 return *this;
1328 }
1329
1330 PointerProperties buildProperties() const { return mProperties; }
1331
1332 PointerCoords buildCoords() const { return mCoords; }
1333
1334private:
1335 PointerProperties mProperties;
1336 PointerCoords mCoords;
1337};
1338
1339class MotionEventBuilder {
1340public:
1341 MotionEventBuilder(int32_t action, int32_t source) {
1342 mAction = action;
1343 mSource = source;
1344 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1345 }
1346
1347 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1348 mEventTime = eventTime;
1349 return *this;
1350 }
1351
1352 MotionEventBuilder& displayId(int32_t displayId) {
1353 mDisplayId = displayId;
1354 return *this;
1355 }
1356
1357 MotionEventBuilder& actionButton(int32_t actionButton) {
1358 mActionButton = actionButton;
1359 return *this;
1360 }
1361
arthurhung6d4bed92021-03-17 11:59:33 +08001362 MotionEventBuilder& buttonState(int32_t buttonState) {
1363 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001364 return *this;
1365 }
1366
1367 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1368 mRawXCursorPosition = rawXCursorPosition;
1369 return *this;
1370 }
1371
1372 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1373 mRawYCursorPosition = rawYCursorPosition;
1374 return *this;
1375 }
1376
1377 MotionEventBuilder& pointer(PointerBuilder pointer) {
1378 mPointers.push_back(pointer);
1379 return *this;
1380 }
1381
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001382 MotionEventBuilder& addFlag(uint32_t flags) {
1383 mFlags |= flags;
1384 return *this;
1385 }
1386
Garfield Tandf26e862020-07-01 20:18:19 -07001387 MotionEvent build() {
1388 std::vector<PointerProperties> pointerProperties;
1389 std::vector<PointerCoords> pointerCoords;
1390 for (const PointerBuilder& pointer : mPointers) {
1391 pointerProperties.push_back(pointer.buildProperties());
1392 pointerCoords.push_back(pointer.buildCoords());
1393 }
1394
1395 // Set mouse cursor position for the most common cases to avoid boilerplate.
1396 if (mSource == AINPUT_SOURCE_MOUSE &&
1397 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1398 mPointers.size() == 1) {
1399 mRawXCursorPosition = pointerCoords[0].getX();
1400 mRawYCursorPosition = pointerCoords[0].getY();
1401 }
1402
1403 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001404 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001405 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001406 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001407 mButtonState, MotionClassification::NONE, identityTransform,
1408 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001409 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1410 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001411
1412 return event;
1413 }
1414
1415private:
1416 int32_t mAction;
1417 int32_t mSource;
1418 nsecs_t mEventTime;
1419 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1420 int32_t mActionButton{0};
1421 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001422 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001423 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1424 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1425
1426 std::vector<PointerBuilder> mPointers;
1427};
1428
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001429static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001430 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001431 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001432 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001433 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1434 injectionTimeout,
1435 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1436}
1437
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001438static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001439 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001440 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001441 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001442 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1443 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001444 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001445 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001446 MotionEvent event = MotionEventBuilder(action, source)
1447 .displayId(displayId)
1448 .eventTime(eventTime)
1449 .rawXCursorPosition(cursorPosition.x)
1450 .rawYCursorPosition(cursorPosition.y)
1451 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1452 .x(position.x)
1453 .y(position.y))
1454 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001455
1456 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001457 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001458}
1459
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001460static InputEventInjectionResult injectMotionDown(
1461 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1462 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001463 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001464}
1465
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001466static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467 int32_t source, int32_t displayId,
1468 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001469 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001470}
1471
Jackal Guof9696682018-10-05 12:23:23 +08001472static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1473 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1474 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001475 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1476 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1477 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001478
1479 return args;
1480}
1481
chaviwd1c23182019-12-20 18:44:56 -08001482static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1483 const std::vector<PointF>& points) {
1484 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001485 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1486 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1487 }
1488
chaviwd1c23182019-12-20 18:44:56 -08001489 PointerProperties pointerProperties[pointerCount];
1490 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001491
chaviwd1c23182019-12-20 18:44:56 -08001492 for (size_t i = 0; i < pointerCount; i++) {
1493 pointerProperties[i].clear();
1494 pointerProperties[i].id = i;
1495 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001496
chaviwd1c23182019-12-20 18:44:56 -08001497 pointerCoords[i].clear();
1498 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1499 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1500 }
Jackal Guof9696682018-10-05 12:23:23 +08001501
1502 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1503 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001504 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001505 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1506 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001507 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1508 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001509 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1510 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001511
1512 return args;
1513}
1514
chaviwd1c23182019-12-20 18:44:56 -08001515static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1516 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1517}
1518
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001519static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1520 const PointerCaptureRequest& request) {
1521 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001522}
1523
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001524/**
1525 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1526 * broken channel.
1527 */
1528TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1529 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1530 sp<FakeWindowHandle> window =
1531 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1532 ADISPLAY_ID_DEFAULT);
1533
1534 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1535
1536 // Window closes its channel, but the window remains.
1537 window->destroyReceiver();
1538 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1539}
1540
Arthur Hungb92218b2018-08-14 12:00:21 +08001541TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001542 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001543 sp<FakeWindowHandle> window =
1544 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001545
Arthur Hung72d8dc32020-03-28 00:48:39 +00001546 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1548 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1549 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001550
1551 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001552 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001553}
1554
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001555TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1556 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1557 sp<FakeWindowHandle> window =
1558 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1559
1560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1561 // Inject a MotionEvent to an unknown display.
1562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1563 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1564 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1565
1566 // Window should receive motion event.
1567 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1568}
1569
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001570/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001571 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001572 * This test serves as a sanity check for the next test, where setInputWindows is
1573 * called twice.
1574 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001575TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001576 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001577 sp<FakeWindowHandle> window =
1578 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1579 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001580
1581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1584 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001586
1587 // Window should receive motion event.
1588 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1589}
1590
1591/**
1592 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001593 */
1594TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001595 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001596 sp<FakeWindowHandle> window =
1597 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1598 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001599
1600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001602 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001603 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1604 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001605 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001606
1607 // Window should receive motion event.
1608 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1609}
1610
Arthur Hungb92218b2018-08-14 12:00:21 +08001611// The foreground window should receive the first touch down event.
1612TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001613 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001614 sp<FakeWindowHandle> windowTop =
1615 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1616 sp<FakeWindowHandle> windowSecond =
1617 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001618
Arthur Hung72d8dc32020-03-28 00:48:39 +00001619 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001620 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1621 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1622 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001623
1624 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001625 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001626 windowSecond->assertNoEvents();
1627}
1628
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001629/**
1630 * Two windows: A top window, and a wallpaper behind the window.
1631 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1632 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001633 * 1. foregroundWindow <-- dup touch to wallpaper
1634 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001635 */
1636TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1637 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1638 sp<FakeWindowHandle> foregroundWindow =
1639 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001640 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001641 sp<FakeWindowHandle> wallpaperWindow =
1642 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001643 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001644 constexpr int expectedWallpaperFlags =
1645 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1646
1647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1649 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1650 {100, 200}))
1651 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1652
1653 // Both foreground window and its wallpaper should receive the touch down
1654 foregroundWindow->consumeMotionDown();
1655 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1656
1657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1658 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1659 ADISPLAY_ID_DEFAULT, {110, 200}))
1660 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1661
1662 foregroundWindow->consumeMotionMove();
1663 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1664
1665 // Now the foreground window goes away, but the wallpaper stays
1666 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1667 foregroundWindow->consumeMotionCancel();
1668 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1669 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1670}
1671
1672/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001673 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1674 * with the following differences:
1675 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1676 * clean up the connection.
1677 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1678 * Ensure that there's no crash in the dispatcher.
1679 */
1680TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1681 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1682 sp<FakeWindowHandle> foregroundWindow =
1683 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001684 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001685 sp<FakeWindowHandle> wallpaperWindow =
1686 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001687 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001688 constexpr int expectedWallpaperFlags =
1689 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1690
1691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1693 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1694 {100, 200}))
1695 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1696
1697 // Both foreground window and its wallpaper should receive the touch down
1698 foregroundWindow->consumeMotionDown();
1699 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1700
1701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1702 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1703 ADISPLAY_ID_DEFAULT, {110, 200}))
1704 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1705
1706 foregroundWindow->consumeMotionMove();
1707 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1708
1709 // Wallpaper closes its channel, but the window remains.
1710 wallpaperWindow->destroyReceiver();
1711 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1712
1713 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1714 // is no longer valid.
1715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1716 foregroundWindow->consumeMotionCancel();
1717}
1718
1719/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001720 * A single window that receives touch (on top), and a wallpaper window underneath it.
1721 * The top window gets a multitouch gesture.
1722 * Ensure that wallpaper gets the same gesture.
1723 */
1724TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1725 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1726 sp<FakeWindowHandle> window =
1727 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001728 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001729
1730 sp<FakeWindowHandle> wallpaperWindow =
1731 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001732 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001733 constexpr int expectedWallpaperFlags =
1734 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1735
1736 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1737
1738 // Touch down on top window
1739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1740 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1741 {100, 100}))
1742 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1743
1744 // Both top window and its wallpaper should receive the touch down
1745 window->consumeMotionDown();
1746 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1747
1748 // Second finger down on the top window
1749 const MotionEvent secondFingerDownEvent =
1750 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1751 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1752 AINPUT_SOURCE_TOUCHSCREEN)
1753 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1754 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1755 .x(100)
1756 .y(100))
1757 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1758 .x(150)
1759 .y(150))
1760 .build();
1761 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1762 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1763 InputEventInjectionSync::WAIT_FOR_RESULT))
1764 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1765
1766 window->consumeMotionPointerDown(1 /* pointerIndex */);
1767 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1768 expectedWallpaperFlags);
1769 window->assertNoEvents();
1770 wallpaperWindow->assertNoEvents();
1771}
1772
1773/**
1774 * Two windows: a window on the left and window on the right.
1775 * A third window, wallpaper, is behind both windows, and spans both top windows.
1776 * The first touch down goes to the left window. A second pointer touches down on the right window.
1777 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1778 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1779 * ACTION_POINTER_DOWN(1).
1780 */
1781TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1782 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1783 sp<FakeWindowHandle> leftWindow =
1784 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1785 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001786 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001787
1788 sp<FakeWindowHandle> rightWindow =
1789 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1790 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001791 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001792
1793 sp<FakeWindowHandle> wallpaperWindow =
1794 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1795 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001796 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001797 constexpr int expectedWallpaperFlags =
1798 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1799
1800 mDispatcher->setInputWindows(
1801 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1802
1803 // Touch down on left window
1804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1805 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1806 {100, 100}))
1807 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1808
1809 // Both foreground window and its wallpaper should receive the touch down
1810 leftWindow->consumeMotionDown();
1811 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1812
1813 // Second finger down on the right window
1814 const MotionEvent secondFingerDownEvent =
1815 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1816 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1817 AINPUT_SOURCE_TOUCHSCREEN)
1818 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1819 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1820 .x(100)
1821 .y(100))
1822 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1823 .x(300)
1824 .y(100))
1825 .build();
1826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1827 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1828 InputEventInjectionSync::WAIT_FOR_RESULT))
1829 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1830
1831 leftWindow->consumeMotionMove();
1832 // Since the touch is split, right window gets ACTION_DOWN
1833 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1834 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1835 expectedWallpaperFlags);
1836
1837 // Now, leftWindow, which received the first finger, disappears.
1838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1839 leftWindow->consumeMotionCancel();
1840 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1841 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1842
1843 // The pointer that's still down on the right window moves, and goes to the right window only.
1844 // As far as the dispatcher's concerned though, both pointers are still present.
1845 const MotionEvent secondFingerMoveEvent =
1846 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1847 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1848 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1849 .x(100)
1850 .y(100))
1851 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1852 .x(310)
1853 .y(110))
1854 .build();
1855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1856 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1857 InputEventInjectionSync::WAIT_FOR_RESULT));
1858 rightWindow->consumeMotionMove();
1859
1860 leftWindow->assertNoEvents();
1861 rightWindow->assertNoEvents();
1862 wallpaperWindow->assertNoEvents();
1863}
1864
Garfield Tandf26e862020-07-01 20:18:19 -07001865TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001866 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001867 sp<FakeWindowHandle> windowLeft =
1868 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1869 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001870 sp<FakeWindowHandle> windowRight =
1871 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1872 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001873
1874 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1875
1876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1877
1878 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001880 injectMotionEvent(mDispatcher,
1881 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1882 AINPUT_SOURCE_MOUSE)
1883 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1884 .x(900)
1885 .y(400))
1886 .build()));
1887 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1888 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1889 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1890 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1891
1892 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001894 injectMotionEvent(mDispatcher,
1895 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1896 AINPUT_SOURCE_MOUSE)
1897 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1898 .x(300)
1899 .y(400))
1900 .build()));
1901 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1902 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1903 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1904 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1905 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1906 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1907
1908 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001910 injectMotionEvent(mDispatcher,
1911 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1912 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1913 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1914 .x(300)
1915 .y(400))
1916 .build()));
1917 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1918
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001919 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001920 injectMotionEvent(mDispatcher,
1921 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1922 AINPUT_SOURCE_MOUSE)
1923 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1924 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1925 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1926 .x(300)
1927 .y(400))
1928 .build()));
1929 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1930 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1931
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001933 injectMotionEvent(mDispatcher,
1934 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1935 AINPUT_SOURCE_MOUSE)
1936 .buttonState(0)
1937 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1938 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1939 .x(300)
1940 .y(400))
1941 .build()));
1942 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1943 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1944
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001946 injectMotionEvent(mDispatcher,
1947 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1948 .buttonState(0)
1949 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1950 .x(300)
1951 .y(400))
1952 .build()));
1953 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1954
1955 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001956 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001957 injectMotionEvent(mDispatcher,
1958 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1959 AINPUT_SOURCE_MOUSE)
1960 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1961 .x(900)
1962 .y(400))
1963 .build()));
1964 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1965 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1966 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1967 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1968 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1969 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1970}
1971
1972// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1973// directly in this test.
1974TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001975 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001976 sp<FakeWindowHandle> window =
1977 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1978 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001979
1980 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1981
1982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1983
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001984 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001985 injectMotionEvent(mDispatcher,
1986 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1987 AINPUT_SOURCE_MOUSE)
1988 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1989 .x(300)
1990 .y(400))
1991 .build()));
1992 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1993 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1994
1995 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001997 injectMotionEvent(mDispatcher,
1998 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1999 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2000 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2001 .x(300)
2002 .y(400))
2003 .build()));
2004 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2005
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002006 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002007 injectMotionEvent(mDispatcher,
2008 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2009 AINPUT_SOURCE_MOUSE)
2010 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2011 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2012 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2013 .x(300)
2014 .y(400))
2015 .build()));
2016 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2017 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2018
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002019 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002020 injectMotionEvent(mDispatcher,
2021 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2022 AINPUT_SOURCE_MOUSE)
2023 .buttonState(0)
2024 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2025 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2026 .x(300)
2027 .y(400))
2028 .build()));
2029 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2030 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2031
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002032 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002033 injectMotionEvent(mDispatcher,
2034 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2035 .buttonState(0)
2036 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2037 .x(300)
2038 .y(400))
2039 .build()));
2040 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2041
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002043 injectMotionEvent(mDispatcher,
2044 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2045 AINPUT_SOURCE_MOUSE)
2046 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2047 .x(300)
2048 .y(400))
2049 .build()));
2050 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2051 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2052}
2053
Garfield Tan00f511d2019-06-12 16:55:40 -07002054TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002055 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002056
2057 sp<FakeWindowHandle> windowLeft =
2058 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2059 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002060 sp<FakeWindowHandle> windowRight =
2061 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2062 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002063
2064 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2065
Arthur Hung72d8dc32020-03-28 00:48:39 +00002066 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002067
2068 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2069 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002071 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002072 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002073 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002074 windowRight->assertNoEvents();
2075}
2076
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002077TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002078 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002079 sp<FakeWindowHandle> window =
2080 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002081 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002082
Arthur Hung72d8dc32020-03-28 00:48:39 +00002083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002084 setFocusedWindow(window);
2085
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002086 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002087
2088 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2089 mDispatcher->notifyKey(&keyArgs);
2090
2091 // Window should receive key down event.
2092 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2093
2094 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2095 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002096 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002097 mDispatcher->notifyDeviceReset(&args);
2098 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2099 AKEY_EVENT_FLAG_CANCELED);
2100}
2101
2102TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002103 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002104 sp<FakeWindowHandle> window =
2105 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2106
Arthur Hung72d8dc32020-03-28 00:48:39 +00002107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002108
2109 NotifyMotionArgs motionArgs =
2110 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2111 ADISPLAY_ID_DEFAULT);
2112 mDispatcher->notifyMotion(&motionArgs);
2113
2114 // Window should receive motion down event.
2115 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2116
2117 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2118 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002119 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002120 mDispatcher->notifyDeviceReset(&args);
2121 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2122 0 /*expectedFlags*/);
2123}
2124
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002125/**
2126 * Ensure the correct coordinate spaces are used by InputDispatcher.
2127 *
2128 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2129 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2130 * space.
2131 */
2132class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2133public:
2134 void SetUp() override {
2135 InputDispatcherTest::SetUp();
2136 mDisplayInfos.clear();
2137 mWindowInfos.clear();
2138 }
2139
2140 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2141 gui::DisplayInfo info;
2142 info.displayId = displayId;
2143 info.transform = transform;
2144 mDisplayInfos.push_back(std::move(info));
2145 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2146 }
2147
2148 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2149 mWindowInfos.push_back(*windowHandle->getInfo());
2150 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2151 }
2152
2153 // Set up a test scenario where the display has a scaled projection and there are two windows
2154 // on the display.
2155 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2156 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2157 // respectively.
2158 ui::Transform displayTransform;
2159 displayTransform.set(2, 0, 0, 4);
2160 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2161
2162 std::shared_ptr<FakeApplicationHandle> application =
2163 std::make_shared<FakeApplicationHandle>();
2164
2165 // Add two windows to the display. Their frames are represented in the display space.
2166 sp<FakeWindowHandle> firstWindow =
2167 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002168 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2169 addWindow(firstWindow);
2170
2171 sp<FakeWindowHandle> secondWindow =
2172 new FakeWindowHandle(application, mDispatcher, "Second Window",
2173 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002174 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2175 addWindow(secondWindow);
2176 return {std::move(firstWindow), std::move(secondWindow)};
2177 }
2178
2179private:
2180 std::vector<gui::DisplayInfo> mDisplayInfos;
2181 std::vector<gui::WindowInfo> mWindowInfos;
2182};
2183
2184TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2185 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2186 // Send down to the first window. The point is represented in the display space. The point is
2187 // selected so that if the hit test was done with the transform applied to it, then it would
2188 // end up in the incorrect window.
2189 NotifyMotionArgs downMotionArgs =
2190 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2191 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2192 mDispatcher->notifyMotion(&downMotionArgs);
2193
2194 firstWindow->consumeMotionDown();
2195 secondWindow->assertNoEvents();
2196}
2197
2198// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2199// the event should be treated as being in the logical display space.
2200TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2201 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2202 // Send down to the first window. The point is represented in the logical display space. The
2203 // point is selected so that if the hit test was done in logical display space, then it would
2204 // end up in the incorrect window.
2205 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2206 PointF{75 * 2, 55 * 4});
2207
2208 firstWindow->consumeMotionDown();
2209 secondWindow->assertNoEvents();
2210}
2211
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002212// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2213// event should be treated as being in the logical display space.
2214TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2215 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2216
2217 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2218 ui::Transform injectedEventTransform;
2219 injectedEventTransform.set(matrix);
2220 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2221 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2222
2223 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2224 .displayId(ADISPLAY_ID_DEFAULT)
2225 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2226 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2227 .x(untransformedPoint.x)
2228 .y(untransformedPoint.y))
2229 .build();
2230 event.transform(matrix);
2231
2232 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2233 InputEventInjectionSync::WAIT_FOR_RESULT);
2234
2235 firstWindow->consumeMotionDown();
2236 secondWindow->assertNoEvents();
2237}
2238
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002239TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2240 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2241
2242 // Send down to the second window.
2243 NotifyMotionArgs downMotionArgs =
2244 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2245 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2246 mDispatcher->notifyMotion(&downMotionArgs);
2247
2248 firstWindow->assertNoEvents();
2249 const MotionEvent* event = secondWindow->consumeMotion();
2250 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2251
2252 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2253 EXPECT_EQ(300, event->getRawX(0));
2254 EXPECT_EQ(880, event->getRawY(0));
2255
2256 // Ensure that the x and y values are in the window's coordinate space.
2257 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2258 // the logical display space. This will be the origin of the window space.
2259 EXPECT_EQ(100, event->getX(0));
2260 EXPECT_EQ(80, event->getY(0));
2261}
2262
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002263using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2264 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002265
2266class TransferTouchFixture : public InputDispatcherTest,
2267 public ::testing::WithParamInterface<TransferFunction> {};
2268
2269TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002270 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002271
2272 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002273 sp<FakeWindowHandle> firstWindow =
2274 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2275 sp<FakeWindowHandle> secondWindow =
2276 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002277
2278 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002279 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002280
2281 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002282 NotifyMotionArgs downMotionArgs =
2283 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2284 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002285 mDispatcher->notifyMotion(&downMotionArgs);
2286 // Only the first window should get the down event
2287 firstWindow->consumeMotionDown();
2288 secondWindow->assertNoEvents();
2289
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002290 // Transfer touch to the second window
2291 TransferFunction f = GetParam();
2292 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2293 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002294 // The first window gets cancel and the second gets down
2295 firstWindow->consumeMotionCancel();
2296 secondWindow->consumeMotionDown();
2297
2298 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002299 NotifyMotionArgs upMotionArgs =
2300 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2301 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002302 mDispatcher->notifyMotion(&upMotionArgs);
2303 // The first window gets no events and the second gets up
2304 firstWindow->assertNoEvents();
2305 secondWindow->consumeMotionUp();
2306}
2307
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002308TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002309 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002310
2311 PointF touchPoint = {10, 10};
2312
2313 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002314 sp<FakeWindowHandle> firstWindow =
2315 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002316 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002317 sp<FakeWindowHandle> secondWindow =
2318 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002319 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002320
2321 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002323
2324 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002325 NotifyMotionArgs downMotionArgs =
2326 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2327 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002328 mDispatcher->notifyMotion(&downMotionArgs);
2329 // Only the first window should get the down event
2330 firstWindow->consumeMotionDown();
2331 secondWindow->assertNoEvents();
2332
2333 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002334 NotifyMotionArgs pointerDownMotionArgs =
2335 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2336 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2337 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2338 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002339 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2340 // Only the first window should get the pointer down event
2341 firstWindow->consumeMotionPointerDown(1);
2342 secondWindow->assertNoEvents();
2343
2344 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002345 TransferFunction f = GetParam();
2346 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2347 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002348 // The first window gets cancel and the second gets down and pointer down
2349 firstWindow->consumeMotionCancel();
2350 secondWindow->consumeMotionDown();
2351 secondWindow->consumeMotionPointerDown(1);
2352
2353 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002354 NotifyMotionArgs pointerUpMotionArgs =
2355 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2356 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2357 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2358 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002359 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2360 // The first window gets nothing and the second gets pointer up
2361 firstWindow->assertNoEvents();
2362 secondWindow->consumeMotionPointerUp(1);
2363
2364 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002365 NotifyMotionArgs upMotionArgs =
2366 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2367 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002368 mDispatcher->notifyMotion(&upMotionArgs);
2369 // The first window gets nothing and the second gets up
2370 firstWindow->assertNoEvents();
2371 secondWindow->consumeMotionUp();
2372}
2373
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002374// For the cases of single pointer touch and two pointers non-split touch, the api's
2375// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2376// for the case where there are multiple pointers split across several windows.
2377INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2378 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002379 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2380 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002381 return dispatcher->transferTouch(destChannelToken);
2382 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002383 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2384 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002385 return dispatcher->transferTouchFocus(from, to,
2386 false /*isDragAndDrop*/);
2387 }));
2388
Svet Ganov5d3bc372020-01-26 23:11:07 -08002389TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002390 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002391
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002392 sp<FakeWindowHandle> firstWindow =
2393 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002394 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002395
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002396 sp<FakeWindowHandle> secondWindow =
2397 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002398 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002399
2400 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002402
2403 PointF pointInFirst = {300, 200};
2404 PointF pointInSecond = {300, 600};
2405
2406 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002407 NotifyMotionArgs firstDownMotionArgs =
2408 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2409 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002410 mDispatcher->notifyMotion(&firstDownMotionArgs);
2411 // Only the first window should get the down event
2412 firstWindow->consumeMotionDown();
2413 secondWindow->assertNoEvents();
2414
2415 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002416 NotifyMotionArgs secondDownMotionArgs =
2417 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2418 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2419 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2420 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002421 mDispatcher->notifyMotion(&secondDownMotionArgs);
2422 // The first window gets a move and the second a down
2423 firstWindow->consumeMotionMove();
2424 secondWindow->consumeMotionDown();
2425
2426 // Transfer touch focus to the second window
2427 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2428 // The first window gets cancel and the new gets pointer down (it already saw down)
2429 firstWindow->consumeMotionCancel();
2430 secondWindow->consumeMotionPointerDown(1);
2431
2432 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002433 NotifyMotionArgs pointerUpMotionArgs =
2434 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2435 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2436 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2437 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002438 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2439 // The first window gets nothing and the second gets pointer up
2440 firstWindow->assertNoEvents();
2441 secondWindow->consumeMotionPointerUp(1);
2442
2443 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002444 NotifyMotionArgs upMotionArgs =
2445 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2446 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002447 mDispatcher->notifyMotion(&upMotionArgs);
2448 // The first window gets nothing and the second gets up
2449 firstWindow->assertNoEvents();
2450 secondWindow->consumeMotionUp();
2451}
2452
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002453// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2454// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2455// touch is not supported, so the touch should continue on those windows and the transferred-to
2456// window should get nothing.
2457TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2458 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2459
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002460 sp<FakeWindowHandle> firstWindow =
2461 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2462 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002463
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002464 sp<FakeWindowHandle> secondWindow =
2465 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2466 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002467
2468 // Add the windows to the dispatcher
2469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2470
2471 PointF pointInFirst = {300, 200};
2472 PointF pointInSecond = {300, 600};
2473
2474 // Send down to the first window
2475 NotifyMotionArgs firstDownMotionArgs =
2476 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2477 ADISPLAY_ID_DEFAULT, {pointInFirst});
2478 mDispatcher->notifyMotion(&firstDownMotionArgs);
2479 // Only the first window should get the down event
2480 firstWindow->consumeMotionDown();
2481 secondWindow->assertNoEvents();
2482
2483 // Send down to the second window
2484 NotifyMotionArgs secondDownMotionArgs =
2485 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2486 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2487 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2488 {pointInFirst, pointInSecond});
2489 mDispatcher->notifyMotion(&secondDownMotionArgs);
2490 // The first window gets a move and the second a down
2491 firstWindow->consumeMotionMove();
2492 secondWindow->consumeMotionDown();
2493
2494 // Transfer touch focus to the second window
2495 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2496 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2497 ASSERT_FALSE(transferred);
2498 firstWindow->assertNoEvents();
2499 secondWindow->assertNoEvents();
2500
2501 // The rest of the dispatch should proceed as normal
2502 // Send pointer up to the second window
2503 NotifyMotionArgs pointerUpMotionArgs =
2504 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2505 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2506 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2507 {pointInFirst, pointInSecond});
2508 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2509 // The first window gets MOVE and the second gets pointer up
2510 firstWindow->consumeMotionMove();
2511 secondWindow->consumeMotionUp();
2512
2513 // Send up event to the first window
2514 NotifyMotionArgs upMotionArgs =
2515 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2516 ADISPLAY_ID_DEFAULT);
2517 mDispatcher->notifyMotion(&upMotionArgs);
2518 // The first window gets nothing and the second gets up
2519 firstWindow->consumeMotionUp();
2520 secondWindow->assertNoEvents();
2521}
2522
Arthur Hungabbb9d82021-09-01 14:52:30 +00002523// This case will create two windows and one mirrored window on the default display and mirror
2524// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2525// the windows info of second display before default display.
2526TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2527 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2528 sp<FakeWindowHandle> firstWindowInPrimary =
2529 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2530 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002531 sp<FakeWindowHandle> secondWindowInPrimary =
2532 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2533 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002534
2535 sp<FakeWindowHandle> mirrorWindowInPrimary =
2536 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2537 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002538
2539 sp<FakeWindowHandle> firstWindowInSecondary =
2540 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2541 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002542
2543 sp<FakeWindowHandle> secondWindowInSecondary =
2544 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2545 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002546
2547 // Update window info, let it find window handle of second display first.
2548 mDispatcher->setInputWindows(
2549 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2550 {ADISPLAY_ID_DEFAULT,
2551 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2552
2553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2554 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2555 {50, 50}))
2556 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2557
2558 // Window should receive motion event.
2559 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2560
2561 // Transfer touch focus
2562 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2563 secondWindowInPrimary->getToken()));
2564 // The first window gets cancel.
2565 firstWindowInPrimary->consumeMotionCancel();
2566 secondWindowInPrimary->consumeMotionDown();
2567
2568 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2569 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2570 ADISPLAY_ID_DEFAULT, {150, 50}))
2571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2572 firstWindowInPrimary->assertNoEvents();
2573 secondWindowInPrimary->consumeMotionMove();
2574
2575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2576 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2577 {150, 50}))
2578 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2579 firstWindowInPrimary->assertNoEvents();
2580 secondWindowInPrimary->consumeMotionUp();
2581}
2582
2583// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2584// 'transferTouch' api.
2585TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2586 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2587 sp<FakeWindowHandle> firstWindowInPrimary =
2588 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2589 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002590 sp<FakeWindowHandle> secondWindowInPrimary =
2591 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2592 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002593
2594 sp<FakeWindowHandle> mirrorWindowInPrimary =
2595 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2596 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002597
2598 sp<FakeWindowHandle> firstWindowInSecondary =
2599 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2600 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002601
2602 sp<FakeWindowHandle> secondWindowInSecondary =
2603 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2604 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002605
2606 // Update window info, let it find window handle of second display first.
2607 mDispatcher->setInputWindows(
2608 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2609 {ADISPLAY_ID_DEFAULT,
2610 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2611
2612 // Touch on second display.
2613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2614 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2615 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2616
2617 // Window should receive motion event.
2618 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2619
2620 // Transfer touch focus
2621 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2622
2623 // The first window gets cancel.
2624 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2625 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2626
2627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2628 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2629 SECOND_DISPLAY_ID, {150, 50}))
2630 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2631 firstWindowInPrimary->assertNoEvents();
2632 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2633
2634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2635 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2636 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2637 firstWindowInPrimary->assertNoEvents();
2638 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2639}
2640
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002641TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002642 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002643 sp<FakeWindowHandle> window =
2644 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2645
Vishnu Nair47074b82020-08-14 11:54:47 -07002646 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002648 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002649
2650 window->consumeFocusEvent(true);
2651
2652 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2653 mDispatcher->notifyKey(&keyArgs);
2654
2655 // Window should receive key down event.
2656 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2657}
2658
2659TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002660 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002661 sp<FakeWindowHandle> window =
2662 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2663
Arthur Hung72d8dc32020-03-28 00:48:39 +00002664 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002665
2666 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2667 mDispatcher->notifyKey(&keyArgs);
2668 mDispatcher->waitForIdle();
2669
2670 window->assertNoEvents();
2671}
2672
2673// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2674TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002675 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002676 sp<FakeWindowHandle> window =
2677 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2678
Arthur Hung72d8dc32020-03-28 00:48:39 +00002679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002680
2681 // Send key
2682 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2683 mDispatcher->notifyKey(&keyArgs);
2684 // Send motion
2685 NotifyMotionArgs motionArgs =
2686 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2687 ADISPLAY_ID_DEFAULT);
2688 mDispatcher->notifyMotion(&motionArgs);
2689
2690 // Window should receive only the motion event
2691 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2692 window->assertNoEvents(); // Key event or focus event will not be received
2693}
2694
arthurhungea3f4fc2020-12-21 23:18:53 +08002695TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2696 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2697
arthurhungea3f4fc2020-12-21 23:18:53 +08002698 sp<FakeWindowHandle> firstWindow =
2699 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2700 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002701
arthurhungea3f4fc2020-12-21 23:18:53 +08002702 sp<FakeWindowHandle> secondWindow =
2703 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2704 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002705
2706 // Add the windows to the dispatcher
2707 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2708
2709 PointF pointInFirst = {300, 200};
2710 PointF pointInSecond = {300, 600};
2711
2712 // Send down to the first window
2713 NotifyMotionArgs firstDownMotionArgs =
2714 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2715 ADISPLAY_ID_DEFAULT, {pointInFirst});
2716 mDispatcher->notifyMotion(&firstDownMotionArgs);
2717 // Only the first window should get the down event
2718 firstWindow->consumeMotionDown();
2719 secondWindow->assertNoEvents();
2720
2721 // Send down to the second window
2722 NotifyMotionArgs secondDownMotionArgs =
2723 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2724 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2725 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2726 {pointInFirst, pointInSecond});
2727 mDispatcher->notifyMotion(&secondDownMotionArgs);
2728 // The first window gets a move and the second a down
2729 firstWindow->consumeMotionMove();
2730 secondWindow->consumeMotionDown();
2731
2732 // Send pointer cancel to the second window
2733 NotifyMotionArgs pointerUpMotionArgs =
2734 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2735 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2736 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2737 {pointInFirst, pointInSecond});
2738 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2739 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2740 // The first window gets move and the second gets cancel.
2741 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2742 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2743
2744 // Send up event.
2745 NotifyMotionArgs upMotionArgs =
2746 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2747 ADISPLAY_ID_DEFAULT);
2748 mDispatcher->notifyMotion(&upMotionArgs);
2749 // The first window gets up and the second gets nothing.
2750 firstWindow->consumeMotionUp();
2751 secondWindow->assertNoEvents();
2752}
2753
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002754TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2755 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2756
2757 sp<FakeWindowHandle> window =
2758 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2760 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2761 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2762 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2763
2764 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2765 window->assertNoEvents();
2766 mDispatcher->waitForIdle();
2767}
2768
chaviwd1c23182019-12-20 18:44:56 -08002769class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002770public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002771 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002772 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002773 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002774 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002775 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002776 }
2777
chaviwd1c23182019-12-20 18:44:56 -08002778 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2779
2780 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2781 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2782 expectedDisplayId, expectedFlags);
2783 }
2784
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002785 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2786
2787 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2788
chaviwd1c23182019-12-20 18:44:56 -08002789 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2790 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2791 expectedDisplayId, expectedFlags);
2792 }
2793
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002794 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2795 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2796 expectedDisplayId, expectedFlags);
2797 }
2798
chaviwd1c23182019-12-20 18:44:56 -08002799 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2800 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2801 expectedDisplayId, expectedFlags);
2802 }
2803
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002804 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2805 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2806 expectedDisplayId, expectedFlags);
2807 }
2808
Arthur Hungfbfa5722021-11-16 02:45:54 +00002809 void consumeMotionPointerDown(int32_t pointerIdx) {
2810 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2811 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2812 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2813 0 /*expectedFlags*/);
2814 }
2815
Evan Rosky84f07f02021-04-16 10:42:42 -07002816 MotionEvent* consumeMotion() {
2817 InputEvent* event = mInputReceiver->consume();
2818 if (!event) {
2819 ADD_FAILURE() << "No event was produced";
2820 return nullptr;
2821 }
2822 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2823 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2824 return nullptr;
2825 }
2826 return static_cast<MotionEvent*>(event);
2827 }
2828
chaviwd1c23182019-12-20 18:44:56 -08002829 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2830
2831private:
2832 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002833};
2834
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002835using InputDispatcherMonitorTest = InputDispatcherTest;
2836
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002837/**
2838 * Two entities that receive touch: A window, and a global monitor.
2839 * The touch goes to the window, and then the window disappears.
2840 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2841 * for the monitor, as well.
2842 * 1. foregroundWindow
2843 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2844 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002845TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002846 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2847 sp<FakeWindowHandle> window =
2848 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2849
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002850 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002851
2852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2853 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2854 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2855 {100, 200}))
2856 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2857
2858 // Both the foreground window and the global monitor should receive the touch down
2859 window->consumeMotionDown();
2860 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2861
2862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2863 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2864 ADISPLAY_ID_DEFAULT, {110, 200}))
2865 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2866
2867 window->consumeMotionMove();
2868 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2869
2870 // Now the foreground window goes away
2871 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2872 window->consumeMotionCancel();
2873 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2874
2875 // If more events come in, there will be no more foreground window to send them to. This will
2876 // cause a cancel for the monitor, as well.
2877 ASSERT_EQ(InputEventInjectionResult::FAILED,
2878 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2879 ADISPLAY_ID_DEFAULT, {120, 200}))
2880 << "Injection should fail because the window was removed";
2881 window->assertNoEvents();
2882 // Global monitor now gets the cancel
2883 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2884}
2885
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002886TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002887 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002888 sp<FakeWindowHandle> window =
2889 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002890 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002891
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002892 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002893
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002895 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002896 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002897 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002898 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002899}
2900
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002901TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2902 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002903
Chris Yea209fde2020-07-22 13:54:51 -07002904 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002905 sp<FakeWindowHandle> window =
2906 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002908
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002910 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002911 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002912 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002913 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002914
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002915 // Pilfer pointers from the monitor.
2916 // This should not do anything and the window should continue to receive events.
2917 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002918
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002919 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002920 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2921 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002922 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002923
2924 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2925 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002926}
2927
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002928TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002929 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2930 sp<FakeWindowHandle> window =
2931 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2933 window->setWindowOffset(20, 40);
2934 window->setWindowTransform(0, 1, -1, 0);
2935
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002936 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002937
2938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2939 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2940 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2941 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2942 MotionEvent* event = monitor.consumeMotion();
2943 // Even though window has transform, gesture monitor must not.
2944 ASSERT_EQ(ui::Transform(), event->getTransform());
2945}
2946
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002947TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002948 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002949 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002950
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002951 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002952 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002953 << "Injection should fail if there is a monitor, but no touchable window";
2954 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002955}
2956
chaviw81e2bb92019-12-18 15:03:51 -08002957TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002958 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002959 sp<FakeWindowHandle> window =
2960 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2961
Arthur Hung72d8dc32020-03-28 00:48:39 +00002962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002963
2964 NotifyMotionArgs motionArgs =
2965 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2966 ADISPLAY_ID_DEFAULT);
2967
2968 mDispatcher->notifyMotion(&motionArgs);
2969 // Window should receive motion down event.
2970 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2971
2972 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002973 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002974 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2975 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2976 motionArgs.pointerCoords[0].getX() - 10);
2977
2978 mDispatcher->notifyMotion(&motionArgs);
2979 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2980 0 /*expectedFlags*/);
2981}
2982
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002983/**
2984 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2985 * the device default right away. In the test scenario, we check both the default value,
2986 * and the action of enabling / disabling.
2987 */
2988TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002989 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002990 sp<FakeWindowHandle> window =
2991 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08002992 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002993
2994 // Set focused application.
2995 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002996 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002997
2998 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002999 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003000 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003001 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3002
3003 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003004 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003006 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3007
3008 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003009 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3010 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003011 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003012 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003013 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003014 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003015 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3016
3017 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003018 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003020 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3021
3022 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003023 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3024 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003025 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003026 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003027 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003028 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003029 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3030
3031 window->assertNoEvents();
3032}
3033
Gang Wange9087892020-01-07 12:17:14 -05003034TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003035 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003036 sp<FakeWindowHandle> window =
3037 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3038
3039 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003040 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003041
Arthur Hung72d8dc32020-03-28 00:48:39 +00003042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003043 setFocusedWindow(window);
3044
Gang Wange9087892020-01-07 12:17:14 -05003045 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3046
3047 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3048 mDispatcher->notifyKey(&keyArgs);
3049
3050 InputEvent* event = window->consume();
3051 ASSERT_NE(event, nullptr);
3052
3053 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3054 ASSERT_NE(verified, nullptr);
3055 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3056
3057 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3058 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3059 ASSERT_EQ(keyArgs.source, verified->source);
3060 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3061
3062 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3063
3064 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003065 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003066 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003067 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3068 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3069 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3070 ASSERT_EQ(0, verifiedKey.repeatCount);
3071}
3072
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003073TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003074 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003075 sp<FakeWindowHandle> window =
3076 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3077
3078 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3079
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003080 ui::Transform transform;
3081 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3082
3083 gui::DisplayInfo displayInfo;
3084 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3085 displayInfo.transform = transform;
3086
3087 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003088
3089 NotifyMotionArgs motionArgs =
3090 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3091 ADISPLAY_ID_DEFAULT);
3092 mDispatcher->notifyMotion(&motionArgs);
3093
3094 InputEvent* event = window->consume();
3095 ASSERT_NE(event, nullptr);
3096
3097 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3098 ASSERT_NE(verified, nullptr);
3099 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3100
3101 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3102 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3103 EXPECT_EQ(motionArgs.source, verified->source);
3104 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3105
3106 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3107
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003108 const vec2 rawXY =
3109 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3110 motionArgs.pointerCoords[0].getXYValue());
3111 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3112 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003113 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003114 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003115 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003116 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3117 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3118}
3119
chaviw09c8d2d2020-08-24 15:48:26 -07003120/**
3121 * Ensure that separate calls to sign the same data are generating the same key.
3122 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3123 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3124 * tests.
3125 */
3126TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3127 KeyEvent event = getTestKeyEvent();
3128 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3129
3130 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3131 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3132 ASSERT_EQ(hmac1, hmac2);
3133}
3134
3135/**
3136 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3137 */
3138TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3139 KeyEvent event = getTestKeyEvent();
3140 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3141 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3142
3143 verifiedEvent.deviceId += 1;
3144 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3145
3146 verifiedEvent.source += 1;
3147 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3148
3149 verifiedEvent.eventTimeNanos += 1;
3150 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3151
3152 verifiedEvent.displayId += 1;
3153 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3154
3155 verifiedEvent.action += 1;
3156 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3157
3158 verifiedEvent.downTimeNanos += 1;
3159 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3160
3161 verifiedEvent.flags += 1;
3162 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3163
3164 verifiedEvent.keyCode += 1;
3165 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3166
3167 verifiedEvent.scanCode += 1;
3168 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3169
3170 verifiedEvent.metaState += 1;
3171 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3172
3173 verifiedEvent.repeatCount += 1;
3174 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3175}
3176
Vishnu Nair958da932020-08-21 17:12:37 -07003177TEST_F(InputDispatcherTest, SetFocusedWindow) {
3178 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3179 sp<FakeWindowHandle> windowTop =
3180 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3181 sp<FakeWindowHandle> windowSecond =
3182 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3183 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3184
3185 // Top window is also focusable but is not granted focus.
3186 windowTop->setFocusable(true);
3187 windowSecond->setFocusable(true);
3188 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3189 setFocusedWindow(windowSecond);
3190
3191 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003192 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3193 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003194
3195 // Focused window should receive event.
3196 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3197 windowTop->assertNoEvents();
3198}
3199
3200TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3201 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3202 sp<FakeWindowHandle> window =
3203 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3204 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3205
3206 window->setFocusable(true);
3207 // Release channel for window is no longer valid.
3208 window->releaseChannel();
3209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3210 setFocusedWindow(window);
3211
3212 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003213 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3214 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003215
3216 // window channel is invalid, so it should not receive any input event.
3217 window->assertNoEvents();
3218}
3219
3220TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3221 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3222 sp<FakeWindowHandle> window =
3223 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003224 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003225 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3226
Vishnu Nair958da932020-08-21 17:12:37 -07003227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3228 setFocusedWindow(window);
3229
3230 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003231 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3232 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003233
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003234 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003235 window->assertNoEvents();
3236}
3237
3238TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3239 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3240 sp<FakeWindowHandle> windowTop =
3241 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3242 sp<FakeWindowHandle> windowSecond =
3243 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3244 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3245
3246 windowTop->setFocusable(true);
3247 windowSecond->setFocusable(true);
3248 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3249 setFocusedWindow(windowTop);
3250 windowTop->consumeFocusEvent(true);
3251
3252 setFocusedWindow(windowSecond, windowTop);
3253 windowSecond->consumeFocusEvent(true);
3254 windowTop->consumeFocusEvent(false);
3255
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003256 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3257 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003258
3259 // Focused window should receive event.
3260 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3261}
3262
3263TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3264 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3265 sp<FakeWindowHandle> windowTop =
3266 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3267 sp<FakeWindowHandle> windowSecond =
3268 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3269 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3270
3271 windowTop->setFocusable(true);
3272 windowSecond->setFocusable(true);
3273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3274 setFocusedWindow(windowSecond, windowTop);
3275
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003276 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3277 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003278
3279 // Event should be dropped.
3280 windowTop->assertNoEvents();
3281 windowSecond->assertNoEvents();
3282}
3283
3284TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3285 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3286 sp<FakeWindowHandle> window =
3287 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3288 sp<FakeWindowHandle> previousFocusedWindow =
3289 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3290 ADISPLAY_ID_DEFAULT);
3291 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3292
3293 window->setFocusable(true);
3294 previousFocusedWindow->setFocusable(true);
3295 window->setVisible(false);
3296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3297 setFocusedWindow(previousFocusedWindow);
3298 previousFocusedWindow->consumeFocusEvent(true);
3299
3300 // Requesting focus on invisible window takes focus from currently focused window.
3301 setFocusedWindow(window);
3302 previousFocusedWindow->consumeFocusEvent(false);
3303
3304 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003305 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003306 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003307 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003308
3309 // Window does not get focus event or key down.
3310 window->assertNoEvents();
3311
3312 // Window becomes visible.
3313 window->setVisible(true);
3314 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3315
3316 // Window receives focus event.
3317 window->consumeFocusEvent(true);
3318 // Focused window receives key down.
3319 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3320}
3321
Vishnu Nair599f1412021-06-21 10:39:58 -07003322TEST_F(InputDispatcherTest, DisplayRemoved) {
3323 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3324 sp<FakeWindowHandle> window =
3325 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3326 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3327
3328 // window is granted focus.
3329 window->setFocusable(true);
3330 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3331 setFocusedWindow(window);
3332 window->consumeFocusEvent(true);
3333
3334 // When a display is removed window loses focus.
3335 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3336 window->consumeFocusEvent(false);
3337}
3338
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003339/**
3340 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3341 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3342 * of the 'slipperyEnterWindow'.
3343 *
3344 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3345 * a way so that the touched location is no longer covered by the top window.
3346 *
3347 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3348 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3349 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3350 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3351 * with ACTION_DOWN).
3352 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3353 * window moved itself away from the touched location and had Flag::SLIPPERY.
3354 *
3355 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3356 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3357 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3358 *
3359 * In this test, we ensure that the event received by the bottom window has
3360 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3361 */
3362TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3363 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3364 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3365
3366 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3367 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3368
3369 sp<FakeWindowHandle> slipperyExitWindow =
3370 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003371 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003372 // Make sure this one overlaps the bottom window
3373 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3374 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3375 // one. Windows with the same owner are not considered to be occluding each other.
3376 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3377
3378 sp<FakeWindowHandle> slipperyEnterWindow =
3379 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3380 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3381
3382 mDispatcher->setInputWindows(
3383 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3384
3385 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3386 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3387 ADISPLAY_ID_DEFAULT, {{50, 50}});
3388 mDispatcher->notifyMotion(&args);
3389 slipperyExitWindow->consumeMotionDown();
3390 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3391 mDispatcher->setInputWindows(
3392 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3393
3394 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3395 ADISPLAY_ID_DEFAULT, {{51, 51}});
3396 mDispatcher->notifyMotion(&args);
3397
3398 slipperyExitWindow->consumeMotionCancel();
3399
3400 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3401 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3402}
3403
Garfield Tan1c7bc862020-01-28 13:24:04 -08003404class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3405protected:
3406 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3407 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3408
Chris Yea209fde2020-07-22 13:54:51 -07003409 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003410 sp<FakeWindowHandle> mWindow;
3411
3412 virtual void SetUp() override {
3413 mFakePolicy = new FakeInputDispatcherPolicy();
3414 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003415 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003416 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3417 ASSERT_EQ(OK, mDispatcher->start());
3418
3419 setUpWindow();
3420 }
3421
3422 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003423 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003424 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3425
Vishnu Nair47074b82020-08-14 11:54:47 -07003426 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003427 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003428 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003429 mWindow->consumeFocusEvent(true);
3430 }
3431
Chris Ye2ad95392020-09-01 13:44:44 -07003432 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003433 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003434 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003435 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3436 mDispatcher->notifyKey(&keyArgs);
3437
3438 // Window should receive key down event.
3439 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3440 }
3441
3442 void expectKeyRepeatOnce(int32_t repeatCount) {
3443 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3444 InputEvent* repeatEvent = mWindow->consume();
3445 ASSERT_NE(nullptr, repeatEvent);
3446
3447 uint32_t eventType = repeatEvent->getType();
3448 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3449
3450 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3451 uint32_t eventAction = repeatKeyEvent->getAction();
3452 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3453 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3454 }
3455
Chris Ye2ad95392020-09-01 13:44:44 -07003456 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003457 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003458 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003459 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3460 mDispatcher->notifyKey(&keyArgs);
3461
3462 // Window should receive key down event.
3463 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3464 0 /*expectedFlags*/);
3465 }
3466};
3467
3468TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003469 sendAndConsumeKeyDown(1 /* deviceId */);
3470 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3471 expectKeyRepeatOnce(repeatCount);
3472 }
3473}
3474
3475TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3476 sendAndConsumeKeyDown(1 /* deviceId */);
3477 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3478 expectKeyRepeatOnce(repeatCount);
3479 }
3480 sendAndConsumeKeyDown(2 /* deviceId */);
3481 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003482 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3483 expectKeyRepeatOnce(repeatCount);
3484 }
3485}
3486
3487TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003488 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003489 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003490 sendAndConsumeKeyUp(1 /* deviceId */);
3491 mWindow->assertNoEvents();
3492}
3493
3494TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3495 sendAndConsumeKeyDown(1 /* deviceId */);
3496 expectKeyRepeatOnce(1 /*repeatCount*/);
3497 sendAndConsumeKeyDown(2 /* deviceId */);
3498 expectKeyRepeatOnce(1 /*repeatCount*/);
3499 // Stale key up from device 1.
3500 sendAndConsumeKeyUp(1 /* deviceId */);
3501 // Device 2 is still down, keep repeating
3502 expectKeyRepeatOnce(2 /*repeatCount*/);
3503 expectKeyRepeatOnce(3 /*repeatCount*/);
3504 // Device 2 key up
3505 sendAndConsumeKeyUp(2 /* deviceId */);
3506 mWindow->assertNoEvents();
3507}
3508
3509TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3510 sendAndConsumeKeyDown(1 /* deviceId */);
3511 expectKeyRepeatOnce(1 /*repeatCount*/);
3512 sendAndConsumeKeyDown(2 /* deviceId */);
3513 expectKeyRepeatOnce(1 /*repeatCount*/);
3514 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3515 sendAndConsumeKeyUp(2 /* deviceId */);
3516 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003517 mWindow->assertNoEvents();
3518}
3519
liushenxiang42232912021-05-21 20:24:09 +08003520TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3521 sendAndConsumeKeyDown(DEVICE_ID);
3522 expectKeyRepeatOnce(1 /*repeatCount*/);
3523 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3524 mDispatcher->notifyDeviceReset(&args);
3525 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3526 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3527 mWindow->assertNoEvents();
3528}
3529
Garfield Tan1c7bc862020-01-28 13:24:04 -08003530TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003531 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003532 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3533 InputEvent* repeatEvent = mWindow->consume();
3534 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3535 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3536 IdGenerator::getSource(repeatEvent->getId()));
3537 }
3538}
3539
3540TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003541 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003542
3543 std::unordered_set<int32_t> idSet;
3544 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3545 InputEvent* repeatEvent = mWindow->consume();
3546 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3547 int32_t id = repeatEvent->getId();
3548 EXPECT_EQ(idSet.end(), idSet.find(id));
3549 idSet.insert(id);
3550 }
3551}
3552
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003553/* Test InputDispatcher for MultiDisplay */
3554class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3555public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003556 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003557 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003558
Chris Yea209fde2020-07-22 13:54:51 -07003559 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003560 windowInPrimary =
3561 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003562
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003563 // Set focus window for primary display, but focused display would be second one.
3564 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003565 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003566 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003567 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003568 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003569
Chris Yea209fde2020-07-22 13:54:51 -07003570 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003571 windowInSecondary =
3572 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003573 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003574 // Set focus display to second one.
3575 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3576 // Set focus window for second display.
3577 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003578 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003579 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003580 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003581 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003582 }
3583
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003584 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003585 InputDispatcherTest::TearDown();
3586
Chris Yea209fde2020-07-22 13:54:51 -07003587 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003588 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003589 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003590 windowInSecondary.clear();
3591 }
3592
3593protected:
Chris Yea209fde2020-07-22 13:54:51 -07003594 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003595 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003596 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003597 sp<FakeWindowHandle> windowInSecondary;
3598};
3599
3600TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3601 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003602 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3603 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3604 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003605 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003606 windowInSecondary->assertNoEvents();
3607
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003608 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3610 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3611 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003612 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003613 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003614}
3615
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003616TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003617 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3619 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003620 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003621 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003622 windowInSecondary->assertNoEvents();
3623
3624 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003626 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003627 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003628 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003629
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003630 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003631 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003632
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003633 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003634 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3635 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003636
3637 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003638 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003639 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003640 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003641 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003642 windowInSecondary->assertNoEvents();
3643}
3644
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003645// Test per-display input monitors for motion event.
3646TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003647 FakeMonitorReceiver monitorInPrimary =
3648 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3649 FakeMonitorReceiver monitorInSecondary =
3650 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003651
3652 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3654 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003656 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003657 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003658 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003659 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003660
3661 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3663 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3664 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003665 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003666 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003667 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003668 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003669
3670 // Test inject a non-pointer motion event.
3671 // If specific a display, it will dispatch to the focused window of particular display,
3672 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3674 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3675 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003676 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003677 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003678 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003679 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003680}
3681
3682// Test per-display input monitors for key event.
3683TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003684 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003685 FakeMonitorReceiver monitorInPrimary =
3686 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3687 FakeMonitorReceiver monitorInSecondary =
3688 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003689
3690 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003691 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3692 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003693 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003694 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003695 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003696 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003697}
3698
Vishnu Nair958da932020-08-21 17:12:37 -07003699TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3700 sp<FakeWindowHandle> secondWindowInPrimary =
3701 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3702 secondWindowInPrimary->setFocusable(true);
3703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3704 setFocusedWindow(secondWindowInPrimary);
3705 windowInPrimary->consumeFocusEvent(false);
3706 secondWindowInPrimary->consumeFocusEvent(true);
3707
3708 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3710 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003711 windowInPrimary->assertNoEvents();
3712 windowInSecondary->assertNoEvents();
3713 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3714}
3715
Arthur Hungdfd528e2021-12-08 13:23:04 +00003716TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3717 FakeMonitorReceiver monitorInPrimary =
3718 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3719 FakeMonitorReceiver monitorInSecondary =
3720 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3721
3722 // Test touch down on primary display.
3723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3724 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3725 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3726 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3727 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3728
3729 // Test touch down on second display.
3730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3731 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3732 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3733 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3734 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3735
3736 // Trigger cancel touch.
3737 mDispatcher->cancelCurrentTouch();
3738 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3739 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3740 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3741 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3742
3743 // Test inject a move motion event, no window/monitor should receive the event.
3744 ASSERT_EQ(InputEventInjectionResult::FAILED,
3745 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3746 ADISPLAY_ID_DEFAULT, {110, 200}))
3747 << "Inject motion event should return InputEventInjectionResult::FAILED";
3748 windowInPrimary->assertNoEvents();
3749 monitorInPrimary.assertNoEvents();
3750
3751 ASSERT_EQ(InputEventInjectionResult::FAILED,
3752 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3753 SECOND_DISPLAY_ID, {110, 200}))
3754 << "Inject motion event should return InputEventInjectionResult::FAILED";
3755 windowInSecondary->assertNoEvents();
3756 monitorInSecondary.assertNoEvents();
3757}
3758
Jackal Guof9696682018-10-05 12:23:23 +08003759class InputFilterTest : public InputDispatcherTest {
3760protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003761 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3762 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003763 NotifyMotionArgs motionArgs;
3764
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003765 motionArgs =
3766 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003767 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003768 motionArgs =
3769 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003770 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003771 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003772 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003773 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3774 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003775 } else {
3776 mFakePolicy->assertFilterInputEventWasNotCalled();
3777 }
3778 }
3779
3780 void testNotifyKey(bool expectToBeFiltered) {
3781 NotifyKeyArgs keyArgs;
3782
3783 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3784 mDispatcher->notifyKey(&keyArgs);
3785 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3786 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003787 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003788
3789 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003790 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003791 } else {
3792 mFakePolicy->assertFilterInputEventWasNotCalled();
3793 }
3794 }
3795};
3796
3797// Test InputFilter for MotionEvent
3798TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3799 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3800 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3801 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3802
3803 // Enable InputFilter
3804 mDispatcher->setInputFilterEnabled(true);
3805 // Test touch on both primary and second display, and check if both events are filtered.
3806 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3807 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3808
3809 // Disable InputFilter
3810 mDispatcher->setInputFilterEnabled(false);
3811 // Test touch on both primary and second display, and check if both events aren't filtered.
3812 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3813 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3814}
3815
3816// Test InputFilter for KeyEvent
3817TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3818 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3819 testNotifyKey(/*expectToBeFiltered*/ false);
3820
3821 // Enable InputFilter
3822 mDispatcher->setInputFilterEnabled(true);
3823 // Send a key event, and check if it is filtered.
3824 testNotifyKey(/*expectToBeFiltered*/ true);
3825
3826 // Disable InputFilter
3827 mDispatcher->setInputFilterEnabled(false);
3828 // Send a key event, and check if it isn't filtered.
3829 testNotifyKey(/*expectToBeFiltered*/ false);
3830}
3831
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003832// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3833// logical display coordinate space.
3834TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3835 ui::Transform firstDisplayTransform;
3836 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3837 ui::Transform secondDisplayTransform;
3838 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3839
3840 std::vector<gui::DisplayInfo> displayInfos(2);
3841 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3842 displayInfos[0].transform = firstDisplayTransform;
3843 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3844 displayInfos[1].transform = secondDisplayTransform;
3845
3846 mDispatcher->onWindowInfosChanged({}, displayInfos);
3847
3848 // Enable InputFilter
3849 mDispatcher->setInputFilterEnabled(true);
3850
3851 // Ensure the correct transforms are used for the displays.
3852 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3853 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3854}
3855
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003856class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3857protected:
3858 virtual void SetUp() override {
3859 InputDispatcherTest::SetUp();
3860
3861 /**
3862 * We don't need to enable input filter to test the injected event policy, but we enabled it
3863 * here to make the tests more realistic, since this policy only matters when inputfilter is
3864 * on.
3865 */
3866 mDispatcher->setInputFilterEnabled(true);
3867
3868 std::shared_ptr<InputApplicationHandle> application =
3869 std::make_shared<FakeApplicationHandle>();
3870 mWindow =
3871 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3872
3873 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3874 mWindow->setFocusable(true);
3875 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3876 setFocusedWindow(mWindow);
3877 mWindow->consumeFocusEvent(true);
3878 }
3879
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003880 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3881 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003882 KeyEvent event;
3883
3884 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3885 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3886 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3887 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3888 const int32_t additionalPolicyFlags =
3889 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3890 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3891 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3892 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3893 policyFlags | additionalPolicyFlags));
3894
3895 InputEvent* received = mWindow->consume();
3896 ASSERT_NE(nullptr, received);
3897 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003898 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3899 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3900 ASSERT_EQ(flags, keyEvent.getFlags());
3901 }
3902
3903 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3904 int32_t flags) {
3905 MotionEvent event;
3906 PointerProperties pointerProperties[1];
3907 PointerCoords pointerCoords[1];
3908 pointerProperties[0].clear();
3909 pointerProperties[0].id = 0;
3910 pointerCoords[0].clear();
3911 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3912 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3913
3914 ui::Transform identityTransform;
3915 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3916 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3917 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3918 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3919 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003920 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003921 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003922 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3923
3924 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3926 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3927 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3928 policyFlags | additionalPolicyFlags));
3929
3930 InputEvent* received = mWindow->consume();
3931 ASSERT_NE(nullptr, received);
3932 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3933 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3934 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3935 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003936 }
3937
3938private:
3939 sp<FakeWindowHandle> mWindow;
3940};
3941
3942TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003943 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3944 // filter. Without it, the event will no different from a regularly injected event, and the
3945 // injected device id will be overwritten.
3946 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3947 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003948}
3949
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003950TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003951 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003952 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3953 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3954}
3955
3956TEST_F(InputFilterInjectionPolicyTest,
3957 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3958 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3959 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3960 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003961}
3962
3963TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3964 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003965 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003966}
3967
chaviwfd6d3512019-03-25 13:23:49 -07003968class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003969 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003970 InputDispatcherTest::SetUp();
3971
Chris Yea209fde2020-07-22 13:54:51 -07003972 std::shared_ptr<FakeApplicationHandle> application =
3973 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003974 mUnfocusedWindow =
3975 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003976 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07003977
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003978 mFocusedWindow =
3979 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3980 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07003981
3982 // Set focused application.
3983 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003984 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003985
3986 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003988 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003989 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003990 }
3991
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003992 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003993 InputDispatcherTest::TearDown();
3994
3995 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003996 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003997 }
3998
3999protected:
4000 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004001 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004002 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004003};
4004
4005// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4006// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4007// the onPointerDownOutsideFocus callback.
4008TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004010 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4011 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004012 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004013 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004014
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004015 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004016 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4017}
4018
4019// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4020// DOWN on the window that doesn't have focus. Ensure no window received the
4021// onPointerDownOutsideFocus callback.
4022TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004024 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004025 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004026 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004027
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004028 ASSERT_TRUE(mDispatcher->waitForIdle());
4029 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004030}
4031
4032// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4033// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4034TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4036 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004037 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004038 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004039
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004040 ASSERT_TRUE(mDispatcher->waitForIdle());
4041 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004042}
4043
4044// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4045// DOWN on the window that already has focus. Ensure no window received the
4046// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004047TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004049 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004050 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004051 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004052 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004053
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004054 ASSERT_TRUE(mDispatcher->waitForIdle());
4055 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004056}
4057
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004058// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4059// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4060TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4061 const MotionEvent event =
4062 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4063 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4064 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4065 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4066 .build();
4067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4068 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4069 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4070
4071 ASSERT_TRUE(mDispatcher->waitForIdle());
4072 mFakePolicy->assertOnPointerDownWasNotCalled();
4073 // Ensure that the unfocused window did not receive any FOCUS events.
4074 mUnfocusedWindow->assertNoEvents();
4075}
4076
chaviwaf87b3e2019-10-01 16:59:28 -07004077// These tests ensures we can send touch events to a single client when there are multiple input
4078// windows that point to the same client token.
4079class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4080 virtual void SetUp() override {
4081 InputDispatcherTest::SetUp();
4082
Chris Yea209fde2020-07-22 13:54:51 -07004083 std::shared_ptr<FakeApplicationHandle> application =
4084 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004085 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4086 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004087 mWindow1->setFrame(Rect(0, 0, 100, 100));
4088
4089 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4090 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004091 mWindow2->setFrame(Rect(100, 100, 200, 200));
4092
Arthur Hung72d8dc32020-03-28 00:48:39 +00004093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004094 }
4095
4096protected:
4097 sp<FakeWindowHandle> mWindow1;
4098 sp<FakeWindowHandle> mWindow2;
4099
4100 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004101 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004102 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4103 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004104 }
4105
4106 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4107 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004108 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004109 InputEvent* event = window->consume();
4110
4111 ASSERT_NE(nullptr, event) << name.c_str()
4112 << ": consumer should have returned non-NULL event.";
4113
4114 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4115 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4116 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4117
4118 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004119 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004120
4121 for (size_t i = 0; i < points.size(); i++) {
4122 float expectedX = points[i].x;
4123 float expectedY = points[i].y;
4124
4125 EXPECT_EQ(expectedX, motionEvent.getX(i))
4126 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4127 << ", got " << motionEvent.getX(i);
4128 EXPECT_EQ(expectedY, motionEvent.getY(i))
4129 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4130 << ", got " << motionEvent.getY(i);
4131 }
4132 }
chaviw9eaa22c2020-07-01 16:21:27 -07004133
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004134 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004135 std::vector<PointF> expectedPoints) {
4136 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4137 ADISPLAY_ID_DEFAULT, touchedPoints);
4138 mDispatcher->notifyMotion(&motionArgs);
4139
4140 // Always consume from window1 since it's the window that has the InputReceiver
4141 consumeMotionEvent(mWindow1, action, expectedPoints);
4142 }
chaviwaf87b3e2019-10-01 16:59:28 -07004143};
4144
4145TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4146 // Touch Window 1
4147 PointF touchedPoint = {10, 10};
4148 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004149 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004150
4151 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004152 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004153
4154 // Touch Window 2
4155 touchedPoint = {150, 150};
4156 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004157 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004158}
4159
chaviw9eaa22c2020-07-01 16:21:27 -07004160TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4161 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004162 mWindow2->setWindowScale(0.5f, 0.5f);
4163
4164 // Touch Window 1
4165 PointF touchedPoint = {10, 10};
4166 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004167 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004168 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004169 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004170
4171 // Touch Window 2
4172 touchedPoint = {150, 150};
4173 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004174 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4175 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004176
chaviw9eaa22c2020-07-01 16:21:27 -07004177 // Update the transform so rotation is set
4178 mWindow2->setWindowTransform(0, -1, 1, 0);
4179 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4180 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004181}
4182
chaviw9eaa22c2020-07-01 16:21:27 -07004183TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004184 mWindow2->setWindowScale(0.5f, 0.5f);
4185
4186 // Touch Window 1
4187 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4188 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004189 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004190
4191 // Touch Window 2
4192 int32_t actionPointerDown =
4193 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004194 touchedPoints.push_back(PointF{150, 150});
4195 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4196 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004197
chaviw9eaa22c2020-07-01 16:21:27 -07004198 // Release Window 2
4199 int32_t actionPointerUp =
4200 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4201 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4202 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004203
chaviw9eaa22c2020-07-01 16:21:27 -07004204 // Update the transform so rotation is set for Window 2
4205 mWindow2->setWindowTransform(0, -1, 1, 0);
4206 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4207 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004208}
4209
chaviw9eaa22c2020-07-01 16:21:27 -07004210TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004211 mWindow2->setWindowScale(0.5f, 0.5f);
4212
4213 // Touch Window 1
4214 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4215 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004216 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004217
4218 // Touch Window 2
4219 int32_t actionPointerDown =
4220 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004221 touchedPoints.push_back(PointF{150, 150});
4222 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004223
chaviw9eaa22c2020-07-01 16:21:27 -07004224 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004225
4226 // Move both windows
4227 touchedPoints = {{20, 20}, {175, 175}};
4228 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4229 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4230
chaviw9eaa22c2020-07-01 16:21:27 -07004231 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004232
chaviw9eaa22c2020-07-01 16:21:27 -07004233 // Release Window 2
4234 int32_t actionPointerUp =
4235 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4236 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4237 expectedPoints.pop_back();
4238
4239 // Touch Window 2
4240 mWindow2->setWindowTransform(0, -1, 1, 0);
4241 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4242 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4243
4244 // Move both windows
4245 touchedPoints = {{20, 20}, {175, 175}};
4246 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4247 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4248
4249 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004250}
4251
4252TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4253 mWindow1->setWindowScale(0.5f, 0.5f);
4254
4255 // Touch Window 1
4256 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4257 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004258 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004259
4260 // Touch Window 2
4261 int32_t actionPointerDown =
4262 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004263 touchedPoints.push_back(PointF{150, 150});
4264 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004265
chaviw9eaa22c2020-07-01 16:21:27 -07004266 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004267
4268 // Move both windows
4269 touchedPoints = {{20, 20}, {175, 175}};
4270 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4271 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4272
chaviw9eaa22c2020-07-01 16:21:27 -07004273 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004274}
4275
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004276class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4277 virtual void SetUp() override {
4278 InputDispatcherTest::SetUp();
4279
Chris Yea209fde2020-07-22 13:54:51 -07004280 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004281 mApplication->setDispatchingTimeout(20ms);
4282 mWindow =
4283 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4284 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004285 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004286 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004287
4288 // Set focused application.
4289 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4290
4291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004292 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004293 mWindow->consumeFocusEvent(true);
4294 }
4295
4296 virtual void TearDown() override {
4297 InputDispatcherTest::TearDown();
4298 mWindow.clear();
4299 }
4300
4301protected:
Chris Yea209fde2020-07-22 13:54:51 -07004302 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004303 sp<FakeWindowHandle> mWindow;
4304 static constexpr PointF WINDOW_LOCATION = {20, 20};
4305
4306 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004307 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004308 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4309 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004311 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4312 WINDOW_LOCATION));
4313 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004314
4315 sp<FakeWindowHandle> addSpyWindow() {
4316 sp<FakeWindowHandle> spy =
4317 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4318 spy->setTrustedOverlay(true);
4319 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004320 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004321 spy->setDispatchingTimeout(30ms);
4322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4323 return spy;
4324 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004325};
4326
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004327// Send a tap and respond, which should not cause an ANR.
4328TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4329 tapOnWindow();
4330 mWindow->consumeMotionDown();
4331 mWindow->consumeMotionUp();
4332 ASSERT_TRUE(mDispatcher->waitForIdle());
4333 mFakePolicy->assertNotifyAnrWasNotCalled();
4334}
4335
4336// Send a regular key and respond, which should not cause an ANR.
4337TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004338 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004339 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4340 ASSERT_TRUE(mDispatcher->waitForIdle());
4341 mFakePolicy->assertNotifyAnrWasNotCalled();
4342}
4343
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004344TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4345 mWindow->setFocusable(false);
4346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4347 mWindow->consumeFocusEvent(false);
4348
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004349 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004350 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004351 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4352 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004354 // Key will not go to window because we have no focused window.
4355 // The 'no focused window' ANR timer should start instead.
4356
4357 // Now, the focused application goes away.
4358 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4359 // The key should get dropped and there should be no ANR.
4360
4361 ASSERT_TRUE(mDispatcher->waitForIdle());
4362 mFakePolicy->assertNotifyAnrWasNotCalled();
4363}
4364
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004365// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004366// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4367// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004368TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004370 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4371 WINDOW_LOCATION));
4372
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004373 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4374 ASSERT_TRUE(sequenceNum);
4375 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004376 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004377
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004378 mWindow->finishEvent(*sequenceNum);
4379 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4380 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004381 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004382 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004383}
4384
4385// Send a key to the app and have the app not respond right away.
4386TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4387 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004388 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004389 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4390 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004391 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004392 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004393 ASSERT_TRUE(mDispatcher->waitForIdle());
4394}
4395
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004396// We have a focused application, but no focused window
4397TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004398 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004399 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4400 mWindow->consumeFocusEvent(false);
4401
4402 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004404 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4405 WINDOW_LOCATION));
4406 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4407 mDispatcher->waitForIdle();
4408 mFakePolicy->assertNotifyAnrWasNotCalled();
4409
4410 // Once a focused event arrives, we get an ANR for this application
4411 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4412 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004413 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004414 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004415 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004417 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004418 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004419 ASSERT_TRUE(mDispatcher->waitForIdle());
4420}
4421
4422// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004423// Make sure that we don't notify policy twice about the same ANR.
4424TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004425 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004426 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4427 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004428
4429 // Once a focused event arrives, we get an ANR for this application
4430 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4431 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004432 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004433 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004434 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004435 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004436 const std::chrono::duration appTimeout =
4437 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004438 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004439
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004440 std::this_thread::sleep_for(appTimeout);
4441 // ANR should not be raised again. It is up to policy to do that if it desires.
4442 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004443
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004444 // If we now get a focused window, the ANR should stop, but the policy handles that via
4445 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004446 ASSERT_TRUE(mDispatcher->waitForIdle());
4447}
4448
4449// We have a focused application, but no focused window
4450TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004451 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4453 mWindow->consumeFocusEvent(false);
4454
4455 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004456 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004457 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004458 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4459 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004460
4461 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004462 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004463
4464 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004465 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004466 ASSERT_TRUE(mDispatcher->waitForIdle());
4467 mWindow->assertNoEvents();
4468}
4469
4470/**
4471 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4472 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4473 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4474 * the ANR mechanism should still work.
4475 *
4476 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4477 * DOWN event, while not responding on the second one.
4478 */
4479TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4480 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4481 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4482 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4483 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4484 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004486
4487 // Now send ACTION_UP, with identical timestamp
4488 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4489 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4490 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4491 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004492 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004493
4494 // We have now sent down and up. Let's consume first event and then ANR on the second.
4495 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4496 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004497 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004498}
4499
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004500// A spy window can receive an ANR
4501TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4502 sp<FakeWindowHandle> spy = addSpyWindow();
4503
4504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4505 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4506 WINDOW_LOCATION));
4507 mWindow->consumeMotionDown();
4508
4509 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4510 ASSERT_TRUE(sequenceNum);
4511 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004512 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004513
4514 spy->finishEvent(*sequenceNum);
4515 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4516 0 /*flags*/);
4517 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004518 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004519}
4520
4521// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004522// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004523TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4524 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004525
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004526 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4527 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004528 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004530
4531 // Stuck on the ACTION_UP
4532 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004533 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004534
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004535 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004536 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004537 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4538 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004539
4540 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4541 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004542 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004543 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004544 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004545}
4546
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004547// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004548// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004549TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4550 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004551
4552 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004553 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4554 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004555
4556 mWindow->consumeMotionDown();
4557 // Stuck on the ACTION_UP
4558 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004559 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004560
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004561 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004562 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004563 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4564 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004565
4566 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4567 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004568 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004569 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004570 spy->assertNoEvents();
4571}
4572
4573TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4574 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4575
4576 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4577
4578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4579 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4580 WINDOW_LOCATION));
4581
4582 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4583 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4584 ASSERT_TRUE(consumeSeq);
4585
Prabir Pradhanedd96402022-02-15 01:46:16 -08004586 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004587
4588 monitor.finishEvent(*consumeSeq);
4589 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4590
4591 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004592 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004593}
4594
4595// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4596// process events, you don't get an anr. When the window later becomes unresponsive again, you
4597// get an ANR again.
4598// 1. tap -> block on ACTION_UP -> receive ANR
4599// 2. consume all pending events (= queue becomes healthy again)
4600// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4601TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4602 tapOnWindow();
4603
4604 mWindow->consumeMotionDown();
4605 // Block on ACTION_UP
4606 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004607 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004608 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4609 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004610 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004611 mWindow->assertNoEvents();
4612
4613 tapOnWindow();
4614 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004615 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004616 mWindow->consumeMotionUp();
4617
4618 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004619 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004620 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621 mWindow->assertNoEvents();
4622}
4623
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004624// If a connection remains unresponsive for a while, make sure policy is only notified once about
4625// it.
4626TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4629 WINDOW_LOCATION));
4630
4631 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004632 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004633 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004634 // 'notifyConnectionUnresponsive' should only be called once per connection
4635 mFakePolicy->assertNotifyAnrWasNotCalled();
4636 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004637 mWindow->consumeMotionDown();
4638 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4639 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4640 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004641 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004642 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004643 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004644}
4645
4646/**
4647 * If a window is processing a motion event, and then a key event comes in, the key event should
4648 * not to to the focused window until the motion is processed.
4649 *
4650 * Warning!!!
4651 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4652 * and the injection timeout that we specify when injecting the key.
4653 * We must have the injection timeout (10ms) be smaller than
4654 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4655 *
4656 * If that value changes, this test should also change.
4657 */
4658TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4659 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4660 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4661
4662 tapOnWindow();
4663 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4664 ASSERT_TRUE(downSequenceNum);
4665 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4666 ASSERT_TRUE(upSequenceNum);
4667 // Don't finish the events yet, and send a key
4668 // Injection will "succeed" because we will eventually give up and send the key to the focused
4669 // window even if motions are still being processed. But because the injection timeout is short,
4670 // we will receive INJECTION_TIMED_OUT as the result.
4671
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004672 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004673 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004674 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4675 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004676 // Key will not be sent to the window, yet, because the window is still processing events
4677 // and the key remains pending, waiting for the touch events to be processed
4678 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4679 ASSERT_FALSE(keySequenceNum);
4680
4681 std::this_thread::sleep_for(500ms);
4682 // if we wait long enough though, dispatcher will give up, and still send the key
4683 // to the focused window, even though we have not yet finished the motion event
4684 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4685 mWindow->finishEvent(*downSequenceNum);
4686 mWindow->finishEvent(*upSequenceNum);
4687}
4688
4689/**
4690 * If a window is processing a motion event, and then a key event comes in, the key event should
4691 * not go to the focused window until the motion is processed.
4692 * If then a new motion comes in, then the pending key event should be going to the currently
4693 * focused window right away.
4694 */
4695TEST_F(InputDispatcherSingleWindowAnr,
4696 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4697 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4699
4700 tapOnWindow();
4701 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4702 ASSERT_TRUE(downSequenceNum);
4703 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4704 ASSERT_TRUE(upSequenceNum);
4705 // Don't finish the events yet, and send a key
4706 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004708 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004709 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710 // At this point, key is still pending, and should not be sent to the application yet.
4711 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4712 ASSERT_FALSE(keySequenceNum);
4713
4714 // Now tap down again. It should cause the pending key to go to the focused window right away.
4715 tapOnWindow();
4716 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4717 // the other events yet. We can finish events in any order.
4718 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4719 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4720 mWindow->consumeMotionDown();
4721 mWindow->consumeMotionUp();
4722 mWindow->assertNoEvents();
4723}
4724
4725class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4726 virtual void SetUp() override {
4727 InputDispatcherTest::SetUp();
4728
Chris Yea209fde2020-07-22 13:54:51 -07004729 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004730 mApplication->setDispatchingTimeout(10ms);
4731 mUnfocusedWindow =
4732 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4733 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004734 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004735 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004736
4737 mFocusedWindow =
4738 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004739 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004740 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004741
4742 // Set focused application.
4743 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004744 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745
4746 // Expect one focus window exist in display.
4747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004748 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004749 mFocusedWindow->consumeFocusEvent(true);
4750 }
4751
4752 virtual void TearDown() override {
4753 InputDispatcherTest::TearDown();
4754
4755 mUnfocusedWindow.clear();
4756 mFocusedWindow.clear();
4757 }
4758
4759protected:
Chris Yea209fde2020-07-22 13:54:51 -07004760 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004761 sp<FakeWindowHandle> mUnfocusedWindow;
4762 sp<FakeWindowHandle> mFocusedWindow;
4763 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4764 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4765 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4766
4767 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4768
4769 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4770
4771private:
4772 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004773 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4775 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004777 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4778 location));
4779 }
4780};
4781
4782// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4783// should be ANR'd first.
4784TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004786 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4787 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004789 mFocusedWindow->consumeMotionDown();
4790 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4791 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4792 // We consumed all events, so no ANR
4793 ASSERT_TRUE(mDispatcher->waitForIdle());
4794 mFakePolicy->assertNotifyAnrWasNotCalled();
4795
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004797 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4798 FOCUSED_WINDOW_LOCATION));
4799 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4800 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004801
4802 const std::chrono::duration timeout =
4803 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004804 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004805 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4806 // sequence to make it consistent
4807 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004808 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004809 mFocusedWindow->consumeMotionDown();
4810 // This cancel is generated because the connection was unresponsive
4811 mFocusedWindow->consumeMotionCancel();
4812 mFocusedWindow->assertNoEvents();
4813 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004814 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004815 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4816 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004817 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004818}
4819
4820// If we have 2 windows with identical timeouts that are both unresponsive,
4821// it doesn't matter which order they should have ANR.
4822// But we should receive ANR for both.
4823TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4824 // Set the timeout for unfocused window to match the focused window
4825 mUnfocusedWindow->setDispatchingTimeout(10ms);
4826 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4827
4828 tapOnFocusedWindow();
4829 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08004830 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
4831 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
4832 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004833
4834 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004835 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4836 mFocusedWindow->getToken() == anrConnectionToken2);
4837 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4838 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004839
4840 ASSERT_TRUE(mDispatcher->waitForIdle());
4841 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004842
4843 mFocusedWindow->consumeMotionDown();
4844 mFocusedWindow->consumeMotionUp();
4845 mUnfocusedWindow->consumeMotionOutside();
4846
Prabir Pradhanedd96402022-02-15 01:46:16 -08004847 sp<IBinder> responsiveToken1, responsiveToken2;
4848 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
4849 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004850
4851 // Both applications should be marked as responsive, in any order
4852 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4853 mFocusedWindow->getToken() == responsiveToken2);
4854 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4855 mUnfocusedWindow->getToken() == responsiveToken2);
4856 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857}
4858
4859// If a window is already not responding, the second tap on the same window should be ignored.
4860// We should also log an error to account for the dropped event (not tested here).
4861// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4862TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4863 tapOnFocusedWindow();
4864 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4865 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4866 // Receive the events, but don't respond
4867 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4868 ASSERT_TRUE(downEventSequenceNum);
4869 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4870 ASSERT_TRUE(upEventSequenceNum);
4871 const std::chrono::duration timeout =
4872 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004873 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004874
4875 // Tap once again
4876 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004877 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4879 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004880 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004881 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4882 FOCUSED_WINDOW_LOCATION));
4883 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4884 // valid touch target
4885 mUnfocusedWindow->assertNoEvents();
4886
4887 // Consume the first tap
4888 mFocusedWindow->finishEvent(*downEventSequenceNum);
4889 mFocusedWindow->finishEvent(*upEventSequenceNum);
4890 ASSERT_TRUE(mDispatcher->waitForIdle());
4891 // The second tap did not go to the focused window
4892 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004893 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08004894 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4895 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896 mFakePolicy->assertNotifyAnrWasNotCalled();
4897}
4898
4899// If you tap outside of all windows, there will not be ANR
4900TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004901 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4903 LOCATION_OUTSIDE_ALL_WINDOWS));
4904 ASSERT_TRUE(mDispatcher->waitForIdle());
4905 mFakePolicy->assertNotifyAnrWasNotCalled();
4906}
4907
4908// Since the focused window is paused, tapping on it should not produce any events
4909TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4910 mFocusedWindow->setPaused(true);
4911 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4912
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004913 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004914 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4915 FOCUSED_WINDOW_LOCATION));
4916
4917 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4918 ASSERT_TRUE(mDispatcher->waitForIdle());
4919 // Should not ANR because the window is paused, and touches shouldn't go to it
4920 mFakePolicy->assertNotifyAnrWasNotCalled();
4921
4922 mFocusedWindow->assertNoEvents();
4923 mUnfocusedWindow->assertNoEvents();
4924}
4925
4926/**
4927 * If a window is processing a motion event, and then a key event comes in, the key event should
4928 * not to to the focused window until the motion is processed.
4929 * If a different window becomes focused at this time, the key should go to that window instead.
4930 *
4931 * Warning!!!
4932 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4933 * and the injection timeout that we specify when injecting the key.
4934 * We must have the injection timeout (10ms) be smaller than
4935 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4936 *
4937 * If that value changes, this test should also change.
4938 */
4939TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4940 // Set a long ANR timeout to prevent it from triggering
4941 mFocusedWindow->setDispatchingTimeout(2s);
4942 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4943
4944 tapOnUnfocusedWindow();
4945 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4946 ASSERT_TRUE(downSequenceNum);
4947 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4948 ASSERT_TRUE(upSequenceNum);
4949 // Don't finish the events yet, and send a key
4950 // Injection will succeed because we will eventually give up and send the key to the focused
4951 // window even if motions are still being processed.
4952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004953 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004954 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004955 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4956 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004957 // Key will not be sent to the window, yet, because the window is still processing events
4958 // and the key remains pending, waiting for the touch events to be processed
4959 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4960 ASSERT_FALSE(keySequenceNum);
4961
4962 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004963 mFocusedWindow->setFocusable(false);
4964 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004965 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004966 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004967
4968 // Focus events should precede the key events
4969 mUnfocusedWindow->consumeFocusEvent(true);
4970 mFocusedWindow->consumeFocusEvent(false);
4971
4972 // Finish the tap events, which should unblock dispatcher
4973 mUnfocusedWindow->finishEvent(*downSequenceNum);
4974 mUnfocusedWindow->finishEvent(*upSequenceNum);
4975
4976 // Now that all queues are cleared and no backlog in the connections, the key event
4977 // can finally go to the newly focused "mUnfocusedWindow".
4978 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4979 mFocusedWindow->assertNoEvents();
4980 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004981 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004982}
4983
4984// When the touch stream is split across 2 windows, and one of them does not respond,
4985// then ANR should be raised and the touch should be canceled for the unresponsive window.
4986// The other window should not be affected by that.
4987TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4988 // Touch Window 1
4989 NotifyMotionArgs motionArgs =
4990 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4991 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4992 mDispatcher->notifyMotion(&motionArgs);
4993 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4994 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4995
4996 // Touch Window 2
4997 int32_t actionPointerDown =
4998 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4999
5000 motionArgs =
5001 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5002 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5003 mDispatcher->notifyMotion(&motionArgs);
5004
5005 const std::chrono::duration timeout =
5006 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005007 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005008
5009 mUnfocusedWindow->consumeMotionDown();
5010 mFocusedWindow->consumeMotionDown();
5011 // Focused window may or may not receive ACTION_MOVE
5012 // But it should definitely receive ACTION_CANCEL due to the ANR
5013 InputEvent* event;
5014 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5015 ASSERT_TRUE(moveOrCancelSequenceNum);
5016 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5017 ASSERT_NE(nullptr, event);
5018 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5019 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5020 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5021 mFocusedWindow->consumeMotionCancel();
5022 } else {
5023 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5024 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005025 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005026 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5027 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005028
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005029 mUnfocusedWindow->assertNoEvents();
5030 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005031 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005032}
5033
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005034/**
5035 * If we have no focused window, and a key comes in, we start the ANR timer.
5036 * The focused application should add a focused window before the timer runs out to prevent ANR.
5037 *
5038 * If the user touches another application during this time, the key should be dropped.
5039 * Next, if a new focused window comes in, without toggling the focused application,
5040 * then no ANR should occur.
5041 *
5042 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5043 * but in some cases the policy may not update the focused application.
5044 */
5045TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5046 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5047 std::make_shared<FakeApplicationHandle>();
5048 focusedApplication->setDispatchingTimeout(60ms);
5049 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5050 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5051 mFocusedWindow->setFocusable(false);
5052
5053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5054 mFocusedWindow->consumeFocusEvent(false);
5055
5056 // Send a key. The ANR timer should start because there is no focused window.
5057 // 'focusedApplication' will get blamed if this timer completes.
5058 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005059 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005060 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005061 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5062 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005064
5065 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5066 // then the injected touches won't cause the focused event to get dropped.
5067 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5068 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5069 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5070 // For this test, it means that the key would get delivered to the window once it becomes
5071 // focused.
5072 std::this_thread::sleep_for(10ms);
5073
5074 // Touch unfocused window. This should force the pending key to get dropped.
5075 NotifyMotionArgs motionArgs =
5076 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5077 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5078 mDispatcher->notifyMotion(&motionArgs);
5079
5080 // We do not consume the motion right away, because that would require dispatcher to first
5081 // process (== drop) the key event, and by that time, ANR will be raised.
5082 // Set the focused window first.
5083 mFocusedWindow->setFocusable(true);
5084 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5085 setFocusedWindow(mFocusedWindow);
5086 mFocusedWindow->consumeFocusEvent(true);
5087 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5088 // to another application. This could be a bug / behaviour in the policy.
5089
5090 mUnfocusedWindow->consumeMotionDown();
5091
5092 ASSERT_TRUE(mDispatcher->waitForIdle());
5093 // Should not ANR because we actually have a focused window. It was just added too slowly.
5094 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5095}
5096
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005097// These tests ensure we cannot send touch events to a window that's positioned behind a window
5098// that has feature NO_INPUT_CHANNEL.
5099// Layout:
5100// Top (closest to user)
5101// mNoInputWindow (above all windows)
5102// mBottomWindow
5103// Bottom (furthest from user)
5104class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5105 virtual void SetUp() override {
5106 InputDispatcherTest::SetUp();
5107
5108 mApplication = std::make_shared<FakeApplicationHandle>();
5109 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5110 "Window without input channel", ADISPLAY_ID_DEFAULT,
5111 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5112
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005113 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005114 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5115 // It's perfectly valid for this window to not have an associated input channel
5116
5117 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5118 ADISPLAY_ID_DEFAULT);
5119 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5120
5121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5122 }
5123
5124protected:
5125 std::shared_ptr<FakeApplicationHandle> mApplication;
5126 sp<FakeWindowHandle> mNoInputWindow;
5127 sp<FakeWindowHandle> mBottomWindow;
5128};
5129
5130TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5131 PointF touchedPoint = {10, 10};
5132
5133 NotifyMotionArgs motionArgs =
5134 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5135 ADISPLAY_ID_DEFAULT, {touchedPoint});
5136 mDispatcher->notifyMotion(&motionArgs);
5137
5138 mNoInputWindow->assertNoEvents();
5139 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5140 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5141 // and therefore should prevent mBottomWindow from receiving touches
5142 mBottomWindow->assertNoEvents();
5143}
5144
5145/**
5146 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5147 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5148 */
5149TEST_F(InputDispatcherMultiWindowOcclusionTests,
5150 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5151 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5152 "Window with input channel and NO_INPUT_CHANNEL",
5153 ADISPLAY_ID_DEFAULT);
5154
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005155 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005156 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5158
5159 PointF touchedPoint = {10, 10};
5160
5161 NotifyMotionArgs motionArgs =
5162 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5163 ADISPLAY_ID_DEFAULT, {touchedPoint});
5164 mDispatcher->notifyMotion(&motionArgs);
5165
5166 mNoInputWindow->assertNoEvents();
5167 mBottomWindow->assertNoEvents();
5168}
5169
Vishnu Nair958da932020-08-21 17:12:37 -07005170class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5171protected:
5172 std::shared_ptr<FakeApplicationHandle> mApp;
5173 sp<FakeWindowHandle> mWindow;
5174 sp<FakeWindowHandle> mMirror;
5175
5176 virtual void SetUp() override {
5177 InputDispatcherTest::SetUp();
5178 mApp = std::make_shared<FakeApplicationHandle>();
5179 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5180 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5181 mWindow->getToken());
5182 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5183 mWindow->setFocusable(true);
5184 mMirror->setFocusable(true);
5185 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5186 }
5187};
5188
5189TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5190 // Request focus on a mirrored window
5191 setFocusedWindow(mMirror);
5192
5193 // window gets focused
5194 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5196 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005197 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5198}
5199
5200// A focused & mirrored window remains focused only if the window and its mirror are both
5201// focusable.
5202TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5203 setFocusedWindow(mMirror);
5204
5205 // window gets focused
5206 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005207 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5208 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005209 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005210 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5211 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005212 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5213
5214 mMirror->setFocusable(false);
5215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5216
5217 // window loses focus since one of the windows associated with the token in not focusable
5218 mWindow->consumeFocusEvent(false);
5219
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005220 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5221 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005222 mWindow->assertNoEvents();
5223}
5224
5225// A focused & mirrored window remains focused until the window and its mirror both become
5226// invisible.
5227TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5228 setFocusedWindow(mMirror);
5229
5230 // window gets focused
5231 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5233 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005234 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5236 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005237 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5238
5239 mMirror->setVisible(false);
5240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5241
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005242 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5243 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005244 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5246 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005247 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5248
5249 mWindow->setVisible(false);
5250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5251
5252 // window loses focus only after all windows associated with the token become invisible.
5253 mWindow->consumeFocusEvent(false);
5254
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005255 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5256 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005257 mWindow->assertNoEvents();
5258}
5259
5260// A focused & mirrored window remains focused until both windows are removed.
5261TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5262 setFocusedWindow(mMirror);
5263
5264 // window gets focused
5265 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005266 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5267 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005268 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5270 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005271 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5272
5273 // single window is removed but the window token remains focused
5274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5275
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5277 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005278 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005279 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5280 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005281 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5282
5283 // Both windows are removed
5284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5285 mWindow->consumeFocusEvent(false);
5286
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005287 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5288 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005289 mWindow->assertNoEvents();
5290}
5291
5292// Focus request can be pending until one window becomes visible.
5293TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5294 // Request focus on an invisible mirror.
5295 mWindow->setVisible(false);
5296 mMirror->setVisible(false);
5297 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5298 setFocusedWindow(mMirror);
5299
5300 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005301 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005302 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005303 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005304
5305 mMirror->setVisible(true);
5306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5307
5308 // window gets focused
5309 mWindow->consumeFocusEvent(true);
5310 // window gets the pending key event
5311 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5312}
Prabir Pradhan99987712020-11-10 18:43:05 -08005313
5314class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5315protected:
5316 std::shared_ptr<FakeApplicationHandle> mApp;
5317 sp<FakeWindowHandle> mWindow;
5318 sp<FakeWindowHandle> mSecondWindow;
5319
5320 void SetUp() override {
5321 InputDispatcherTest::SetUp();
5322 mApp = std::make_shared<FakeApplicationHandle>();
5323 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5324 mWindow->setFocusable(true);
5325 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5326 mSecondWindow->setFocusable(true);
5327
5328 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5330
5331 setFocusedWindow(mWindow);
5332 mWindow->consumeFocusEvent(true);
5333 }
5334
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005335 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5336 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005337 mDispatcher->notifyPointerCaptureChanged(&args);
5338 }
5339
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005340 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5341 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005342 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005343 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5344 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005345 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005346 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005347 }
5348};
5349
5350TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5351 // Ensure that capture cannot be obtained for unfocused windows.
5352 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5353 mFakePolicy->assertSetPointerCaptureNotCalled();
5354 mSecondWindow->assertNoEvents();
5355
5356 // Ensure that capture can be enabled from the focus window.
5357 requestAndVerifyPointerCapture(mWindow, true);
5358
5359 // Ensure that capture cannot be disabled from a window that does not have capture.
5360 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5361 mFakePolicy->assertSetPointerCaptureNotCalled();
5362
5363 // Ensure that capture can be disabled from the window with capture.
5364 requestAndVerifyPointerCapture(mWindow, false);
5365}
5366
5367TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005368 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005369
5370 setFocusedWindow(mSecondWindow);
5371
5372 // Ensure that the capture disabled event was sent first.
5373 mWindow->consumeCaptureEvent(false);
5374 mWindow->consumeFocusEvent(false);
5375 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005376 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005377
5378 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005379 notifyPointerCaptureChanged({});
5380 notifyPointerCaptureChanged(request);
5381 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005382 mWindow->assertNoEvents();
5383 mSecondWindow->assertNoEvents();
5384 mFakePolicy->assertSetPointerCaptureNotCalled();
5385}
5386
5387TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005388 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005389
5390 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005391 notifyPointerCaptureChanged({});
5392 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005393
5394 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005395 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005396 mWindow->consumeCaptureEvent(false);
5397 mWindow->assertNoEvents();
5398}
5399
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005400TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5401 requestAndVerifyPointerCapture(mWindow, true);
5402
5403 // The first window loses focus.
5404 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005405 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005406 mWindow->consumeCaptureEvent(false);
5407
5408 // Request Pointer Capture from the second window before the notification from InputReader
5409 // arrives.
5410 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005411 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005412
5413 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005414 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005415
5416 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005417 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005418
5419 mSecondWindow->consumeFocusEvent(true);
5420 mSecondWindow->consumeCaptureEvent(true);
5421}
5422
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005423TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5424 // App repeatedly enables and disables capture.
5425 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5426 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5427 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5428 mFakePolicy->assertSetPointerCaptureCalled(false);
5429 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5430 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5431
5432 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5433 // first request is now stale, this should do nothing.
5434 notifyPointerCaptureChanged(firstRequest);
5435 mWindow->assertNoEvents();
5436
5437 // InputReader notifies that the second request was enabled.
5438 notifyPointerCaptureChanged(secondRequest);
5439 mWindow->consumeCaptureEvent(true);
5440}
5441
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005442class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5443protected:
5444 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005445
5446 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5447 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5448
5449 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5450 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5451
5452 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5453 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5454 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5455 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5456 MAXIMUM_OBSCURING_OPACITY);
5457
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005458 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005459 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005460 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005461
5462 sp<FakeWindowHandle> mTouchWindow;
5463
5464 virtual void SetUp() override {
5465 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005466 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005467 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5468 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5469 }
5470
5471 virtual void TearDown() override {
5472 InputDispatcherTest::TearDown();
5473 mTouchWindow.clear();
5474 }
5475
chaviw3277faf2021-05-19 16:45:23 -05005476 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5477 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005478 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005479 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005480 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005481 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005482 return window;
5483 }
5484
5485 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5486 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5487 sp<FakeWindowHandle> window =
5488 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5489 // Generate an arbitrary PID based on the UID
5490 window->setOwnerInfo(1777 + (uid % 10000), uid);
5491 return window;
5492 }
5493
5494 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5495 NotifyMotionArgs args =
5496 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5497 ADISPLAY_ID_DEFAULT, points);
5498 mDispatcher->notifyMotion(&args);
5499 }
5500};
5501
5502TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005503 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005504 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005505 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005506
5507 touch();
5508
5509 mTouchWindow->assertNoEvents();
5510}
5511
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005512TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005513 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5514 const sp<FakeWindowHandle>& w =
5515 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5516 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5517
5518 touch();
5519
5520 mTouchWindow->assertNoEvents();
5521}
5522
5523TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005524 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5525 const sp<FakeWindowHandle>& w =
5526 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5527 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5528
5529 touch();
5530
5531 w->assertNoEvents();
5532}
5533
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005534TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005535 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5536 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005537
5538 touch();
5539
5540 mTouchWindow->consumeAnyMotionDown();
5541}
5542
5543TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005544 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005545 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005546 w->setFrame(Rect(0, 0, 50, 50));
5547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005548
5549 touch({PointF{100, 100}});
5550
5551 mTouchWindow->consumeAnyMotionDown();
5552}
5553
5554TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005555 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005556 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005557 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5558
5559 touch();
5560
5561 mTouchWindow->consumeAnyMotionDown();
5562}
5563
5564TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5565 const sp<FakeWindowHandle>& w =
5566 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005568
5569 touch();
5570
5571 mTouchWindow->consumeAnyMotionDown();
5572}
5573
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005574TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5575 const sp<FakeWindowHandle>& w =
5576 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5578
5579 touch();
5580
5581 w->assertNoEvents();
5582}
5583
5584/**
5585 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5586 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5587 * window, the occluding window will still receive ACTION_OUTSIDE event.
5588 */
5589TEST_F(InputDispatcherUntrustedTouchesTest,
5590 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5591 const sp<FakeWindowHandle>& w =
5592 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005593 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005594 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5595
5596 touch();
5597
5598 w->consumeMotionOutside();
5599}
5600
5601TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5602 const sp<FakeWindowHandle>& w =
5603 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005604 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5606
5607 touch();
5608
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005609 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005610}
5611
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005612TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005613 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005614 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5615 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5617
5618 touch();
5619
5620 mTouchWindow->consumeAnyMotionDown();
5621}
5622
5623TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5624 const sp<FakeWindowHandle>& w =
5625 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5626 MAXIMUM_OBSCURING_OPACITY);
5627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005628
5629 touch();
5630
5631 mTouchWindow->consumeAnyMotionDown();
5632}
5633
5634TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005635 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005636 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5637 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5639
5640 touch();
5641
5642 mTouchWindow->assertNoEvents();
5643}
5644
5645TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5646 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5647 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005648 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5649 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005650 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005651 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5652 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5654
5655 touch();
5656
5657 mTouchWindow->assertNoEvents();
5658}
5659
5660TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5661 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5662 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005663 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5664 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005665 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005666 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5667 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5669
5670 touch();
5671
5672 mTouchWindow->consumeAnyMotionDown();
5673}
5674
5675TEST_F(InputDispatcherUntrustedTouchesTest,
5676 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5677 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005678 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5679 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005680 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005681 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5682 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5684
5685 touch();
5686
5687 mTouchWindow->consumeAnyMotionDown();
5688}
5689
5690TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5691 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005692 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5693 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005694 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005695 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5696 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005698
5699 touch();
5700
5701 mTouchWindow->assertNoEvents();
5702}
5703
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005704TEST_F(InputDispatcherUntrustedTouchesTest,
5705 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5706 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005707 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5708 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005709 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005710 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5711 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5713
5714 touch();
5715
5716 mTouchWindow->assertNoEvents();
5717}
5718
5719TEST_F(InputDispatcherUntrustedTouchesTest,
5720 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5721 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005722 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5723 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005724 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005725 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5726 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5728
5729 touch();
5730
5731 mTouchWindow->consumeAnyMotionDown();
5732}
5733
5734TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5735 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005736 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5737 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005738 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5739
5740 touch();
5741
5742 mTouchWindow->consumeAnyMotionDown();
5743}
5744
5745TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5746 const sp<FakeWindowHandle>& w =
5747 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5749
5750 touch();
5751
5752 mTouchWindow->consumeAnyMotionDown();
5753}
5754
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005755TEST_F(InputDispatcherUntrustedTouchesTest,
5756 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5757 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5758 const sp<FakeWindowHandle>& w =
5759 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5761
5762 touch();
5763
5764 mTouchWindow->assertNoEvents();
5765}
5766
5767TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5768 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5769 const sp<FakeWindowHandle>& w =
5770 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5772
5773 touch();
5774
5775 mTouchWindow->consumeAnyMotionDown();
5776}
5777
5778TEST_F(InputDispatcherUntrustedTouchesTest,
5779 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5780 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5781 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005782 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5783 OPACITY_ABOVE_THRESHOLD);
5784 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5785
5786 touch();
5787
5788 mTouchWindow->consumeAnyMotionDown();
5789}
5790
5791TEST_F(InputDispatcherUntrustedTouchesTest,
5792 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5793 const sp<FakeWindowHandle>& w1 =
5794 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5795 OPACITY_BELOW_THRESHOLD);
5796 const sp<FakeWindowHandle>& w2 =
5797 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5798 OPACITY_BELOW_THRESHOLD);
5799 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5800
5801 touch();
5802
5803 mTouchWindow->assertNoEvents();
5804}
5805
5806/**
5807 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5808 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5809 * (which alone would result in allowing touches) does not affect the blocking behavior.
5810 */
5811TEST_F(InputDispatcherUntrustedTouchesTest,
5812 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5813 const sp<FakeWindowHandle>& wB =
5814 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5815 OPACITY_BELOW_THRESHOLD);
5816 const sp<FakeWindowHandle>& wC =
5817 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5818 OPACITY_BELOW_THRESHOLD);
5819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5820
5821 touch();
5822
5823 mTouchWindow->assertNoEvents();
5824}
5825
5826/**
5827 * This test is testing that a window from a different UID but with same application token doesn't
5828 * block the touch. Apps can share the application token for close UI collaboration for example.
5829 */
5830TEST_F(InputDispatcherUntrustedTouchesTest,
5831 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5832 const sp<FakeWindowHandle>& w =
5833 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5834 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5836
5837 touch();
5838
5839 mTouchWindow->consumeAnyMotionDown();
5840}
5841
arthurhungb89ccb02020-12-30 16:19:01 +08005842class InputDispatcherDragTests : public InputDispatcherTest {
5843protected:
5844 std::shared_ptr<FakeApplicationHandle> mApp;
5845 sp<FakeWindowHandle> mWindow;
5846 sp<FakeWindowHandle> mSecondWindow;
5847 sp<FakeWindowHandle> mDragWindow;
5848
5849 void SetUp() override {
5850 InputDispatcherTest::SetUp();
5851 mApp = std::make_shared<FakeApplicationHandle>();
5852 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5853 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005854
5855 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5856 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005857
5858 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5860 }
5861
5862 // Start performing drag, we will create a drag window and transfer touch to it.
5863 void performDrag() {
5864 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5865 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5866 {50, 50}))
5867 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5868
5869 // Window should receive motion event.
5870 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5871
5872 // The drag window covers the entire display
5873 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5874 mDispatcher->setInputWindows(
5875 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5876
5877 // Transfer touch focus to the drag window
5878 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5879 true /* isDragDrop */);
5880 mWindow->consumeMotionCancel();
5881 mDragWindow->consumeMotionDown();
5882 }
arthurhung6d4bed92021-03-17 11:59:33 +08005883
5884 // Start performing drag, we will create a drag window and transfer touch to it.
5885 void performStylusDrag() {
5886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5887 injectMotionEvent(mDispatcher,
5888 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5889 AINPUT_SOURCE_STYLUS)
5890 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5891 .pointer(PointerBuilder(0,
5892 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5893 .x(50)
5894 .y(50))
5895 .build()));
5896 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5897
5898 // The drag window covers the entire display
5899 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5900 mDispatcher->setInputWindows(
5901 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5902
5903 // Transfer touch focus to the drag window
5904 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5905 true /* isDragDrop */);
5906 mWindow->consumeMotionCancel();
5907 mDragWindow->consumeMotionDown();
5908 }
arthurhungb89ccb02020-12-30 16:19:01 +08005909};
5910
5911TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5912 performDrag();
5913
5914 // Move on window.
5915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5916 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5917 ADISPLAY_ID_DEFAULT, {50, 50}))
5918 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5919 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5920 mWindow->consumeDragEvent(false, 50, 50);
5921 mSecondWindow->assertNoEvents();
5922
5923 // Move to another window.
5924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5925 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5926 ADISPLAY_ID_DEFAULT, {150, 50}))
5927 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5928 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5929 mWindow->consumeDragEvent(true, 150, 50);
5930 mSecondWindow->consumeDragEvent(false, 50, 50);
5931
5932 // Move back to original window.
5933 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5934 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5935 ADISPLAY_ID_DEFAULT, {50, 50}))
5936 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5937 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5938 mWindow->consumeDragEvent(false, 50, 50);
5939 mSecondWindow->consumeDragEvent(true, -50, 50);
5940
5941 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5942 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5943 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5944 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5945 mWindow->assertNoEvents();
5946 mSecondWindow->assertNoEvents();
5947}
5948
arthurhungf452d0b2021-01-06 00:19:52 +08005949TEST_F(InputDispatcherDragTests, DragAndDrop) {
5950 performDrag();
5951
5952 // Move on window.
5953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5954 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5955 ADISPLAY_ID_DEFAULT, {50, 50}))
5956 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5957 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5958 mWindow->consumeDragEvent(false, 50, 50);
5959 mSecondWindow->assertNoEvents();
5960
5961 // Move to another window.
5962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5963 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5964 ADISPLAY_ID_DEFAULT, {150, 50}))
5965 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5966 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5967 mWindow->consumeDragEvent(true, 150, 50);
5968 mSecondWindow->consumeDragEvent(false, 50, 50);
5969
5970 // drop to another window.
5971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5972 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5973 {150, 50}))
5974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5975 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5976 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5977 mWindow->assertNoEvents();
5978 mSecondWindow->assertNoEvents();
5979}
5980
arthurhung6d4bed92021-03-17 11:59:33 +08005981TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5982 performStylusDrag();
5983
5984 // Move on window and keep button pressed.
5985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5986 injectMotionEvent(mDispatcher,
5987 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5988 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5989 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5990 .x(50)
5991 .y(50))
5992 .build()))
5993 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5994 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5995 mWindow->consumeDragEvent(false, 50, 50);
5996 mSecondWindow->assertNoEvents();
5997
5998 // Move to another window and release button, expect to drop item.
5999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6000 injectMotionEvent(mDispatcher,
6001 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6002 .buttonState(0)
6003 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6004 .x(150)
6005 .y(50))
6006 .build()))
6007 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6008 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6009 mWindow->assertNoEvents();
6010 mSecondWindow->assertNoEvents();
6011 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6012
6013 // nothing to the window.
6014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6015 injectMotionEvent(mDispatcher,
6016 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6017 .buttonState(0)
6018 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6019 .x(150)
6020 .y(50))
6021 .build()))
6022 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6023 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6024 mWindow->assertNoEvents();
6025 mSecondWindow->assertNoEvents();
6026}
6027
Arthur Hung6d0571e2021-04-09 20:18:16 +08006028TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6029 performDrag();
6030
6031 // Set second window invisible.
6032 mSecondWindow->setVisible(false);
6033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6034
6035 // Move on window.
6036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6037 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6038 ADISPLAY_ID_DEFAULT, {50, 50}))
6039 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6040 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6041 mWindow->consumeDragEvent(false, 50, 50);
6042 mSecondWindow->assertNoEvents();
6043
6044 // Move to another window.
6045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6046 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6047 ADISPLAY_ID_DEFAULT, {150, 50}))
6048 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6049 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6050 mWindow->consumeDragEvent(true, 150, 50);
6051 mSecondWindow->assertNoEvents();
6052
6053 // drop to another window.
6054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6055 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6056 {150, 50}))
6057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6058 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6059 mFakePolicy->assertDropTargetEquals(nullptr);
6060 mWindow->assertNoEvents();
6061 mSecondWindow->assertNoEvents();
6062}
6063
Vishnu Nair062a8672021-09-03 16:07:44 -07006064class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6065
6066TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6067 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6068 sp<FakeWindowHandle> window =
6069 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006070 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006071 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6072 window->setFocusable(true);
6073 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6074 setFocusedWindow(window);
6075 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6076
6077 // With the flag set, window should not get any input
6078 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6079 mDispatcher->notifyKey(&keyArgs);
6080 window->assertNoEvents();
6081
6082 NotifyMotionArgs motionArgs =
6083 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6084 ADISPLAY_ID_DEFAULT);
6085 mDispatcher->notifyMotion(&motionArgs);
6086 window->assertNoEvents();
6087
6088 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006089 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6091
6092 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6093 mDispatcher->notifyKey(&keyArgs);
6094 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6095
6096 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6097 ADISPLAY_ID_DEFAULT);
6098 mDispatcher->notifyMotion(&motionArgs);
6099 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6100 window->assertNoEvents();
6101}
6102
6103TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6104 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6105 std::make_shared<FakeApplicationHandle>();
6106 sp<FakeWindowHandle> obscuringWindow =
6107 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6108 ADISPLAY_ID_DEFAULT);
6109 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6110 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006111 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006112 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6113 sp<FakeWindowHandle> window =
6114 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006115 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006116 window->setOwnerInfo(222, 222);
6117 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6118 window->setFocusable(true);
6119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6120 setFocusedWindow(window);
6121 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6122
6123 // With the flag set, window should not get any input
6124 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6125 mDispatcher->notifyKey(&keyArgs);
6126 window->assertNoEvents();
6127
6128 NotifyMotionArgs motionArgs =
6129 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6130 ADISPLAY_ID_DEFAULT);
6131 mDispatcher->notifyMotion(&motionArgs);
6132 window->assertNoEvents();
6133
6134 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006135 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6137
6138 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6139 mDispatcher->notifyKey(&keyArgs);
6140 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6141
6142 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6143 ADISPLAY_ID_DEFAULT);
6144 mDispatcher->notifyMotion(&motionArgs);
6145 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6146 window->assertNoEvents();
6147}
6148
6149TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6150 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6151 std::make_shared<FakeApplicationHandle>();
6152 sp<FakeWindowHandle> obscuringWindow =
6153 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6154 ADISPLAY_ID_DEFAULT);
6155 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6156 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006157 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006158 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6159 sp<FakeWindowHandle> window =
6160 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006161 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006162 window->setOwnerInfo(222, 222);
6163 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6164 window->setFocusable(true);
6165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6166 setFocusedWindow(window);
6167 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6168
6169 // With the flag set, window should not get any input
6170 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6171 mDispatcher->notifyKey(&keyArgs);
6172 window->assertNoEvents();
6173
6174 NotifyMotionArgs motionArgs =
6175 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6176 ADISPLAY_ID_DEFAULT);
6177 mDispatcher->notifyMotion(&motionArgs);
6178 window->assertNoEvents();
6179
6180 // When the window is no longer obscured because it went on top, it should get input
6181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6182
6183 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6184 mDispatcher->notifyKey(&keyArgs);
6185 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6186
6187 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6188 ADISPLAY_ID_DEFAULT);
6189 mDispatcher->notifyMotion(&motionArgs);
6190 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6191 window->assertNoEvents();
6192}
6193
Antonio Kantekf16f2832021-09-28 04:39:20 +00006194class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6195protected:
6196 std::shared_ptr<FakeApplicationHandle> mApp;
6197 sp<FakeWindowHandle> mWindow;
6198 sp<FakeWindowHandle> mSecondWindow;
6199
6200 void SetUp() override {
6201 InputDispatcherTest::SetUp();
6202
6203 mApp = std::make_shared<FakeApplicationHandle>();
6204 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6205 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006206 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006207 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6208 mSecondWindow->setFocusable(true);
6209
6210 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6211 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006212 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006213
6214 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6215 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6216 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006217 }
6218
Antonio Kantekea47acb2021-12-23 12:41:25 -08006219 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006220 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006221 mWindow->consumeTouchModeEvent(inTouchMode);
6222 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6223 }
6224};
6225
Antonio Kantek26defcf2022-02-08 01:12:27 +00006226TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006227 const WindowInfo& windowInfo = *mWindow->getInfo();
6228 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6229 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006230}
6231
Antonio Kantek26defcf2022-02-08 01:12:27 +00006232TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6233 const WindowInfo& windowInfo = *mWindow->getInfo();
6234 int32_t ownerPid = windowInfo.ownerPid;
6235 int32_t ownerUid = windowInfo.ownerUid;
6236 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6237 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6238 ownerUid, /* hasPermission */ false));
6239 mWindow->assertNoEvents();
6240 mSecondWindow->assertNoEvents();
6241}
6242
6243TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6244 const WindowInfo& windowInfo = *mWindow->getInfo();
6245 int32_t ownerPid = windowInfo.ownerPid;
6246 int32_t ownerUid = windowInfo.ownerUid;
6247 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6248 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6249 /* hasPermission */ true);
6250}
6251
Antonio Kantekf16f2832021-09-28 04:39:20 +00006252TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006253 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006254 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6255 windowInfo.ownerPid, windowInfo.ownerUid,
6256 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006257 mWindow->assertNoEvents();
6258 mSecondWindow->assertNoEvents();
6259}
6260
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006261class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6262public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006263 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006264 std::shared_ptr<FakeApplicationHandle> application =
6265 std::make_shared<FakeApplicationHandle>();
6266 std::string name = "Fake Spy ";
6267 name += std::to_string(mSpyCount++);
6268 sp<FakeWindowHandle> spy =
6269 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006270 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006271 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006272 return spy;
6273 }
6274
6275 sp<FakeWindowHandle> createForeground() {
6276 std::shared_ptr<FakeApplicationHandle> application =
6277 std::make_shared<FakeApplicationHandle>();
6278 sp<FakeWindowHandle> window =
6279 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006280 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006281 return window;
6282 }
6283
6284private:
6285 int mSpyCount{0};
6286};
6287
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006288using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006289/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006290 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6291 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006292TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6293 ScopedSilentDeath _silentDeath;
6294
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006295 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006296 spy->setTrustedOverlay(false);
6297 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6298 ".* not a trusted overlay");
6299}
6300
6301/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006302 * Input injection into a display with a spy window but no foreground windows should succeed.
6303 */
6304TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006305 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6307
6308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6309 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6310 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6311 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6312}
6313
6314/**
6315 * Verify the order in which different input windows receive events. The touched foreground window
6316 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6317 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6318 * receive events before ones belows it.
6319 *
6320 * Here, we set up a scenario with four windows in the following Z order from the top:
6321 * spy1, spy2, window, spy3.
6322 * We then inject an event and verify that the foreground "window" receives it first, followed by
6323 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6324 * window.
6325 */
6326TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6327 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006328 auto spy1 = createSpy();
6329 auto spy2 = createSpy();
6330 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6332 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6333 const size_t numChannels = channels.size();
6334
Michael Wright8e9a8562022-02-09 13:44:29 +00006335 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006336 if (!epollFd.ok()) {
6337 FAIL() << "Failed to create epoll fd";
6338 }
6339
6340 for (size_t i = 0; i < numChannels; i++) {
6341 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6342 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6343 FAIL() << "Failed to add fd to epoll";
6344 }
6345 }
6346
6347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6348 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6349 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6350
6351 std::vector<size_t> eventOrder;
6352 std::vector<struct epoll_event> events(numChannels);
6353 for (;;) {
6354 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6355 (100ms).count());
6356 if (nFds < 0) {
6357 FAIL() << "Failed to call epoll_wait";
6358 }
6359 if (nFds == 0) {
6360 break; // epoll_wait timed out
6361 }
6362 for (int i = 0; i < nFds; i++) {
6363 ASSERT_EQ(EPOLLIN, events[i].events);
6364 eventOrder.push_back(events[i].data.u64);
6365 channels[i]->consumeMotionDown();
6366 }
6367 }
6368
6369 // Verify the order in which the events were received.
6370 EXPECT_EQ(3u, eventOrder.size());
6371 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6372 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6373 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6374}
6375
6376/**
6377 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6378 */
6379TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6380 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006381 auto spy = createSpy();
6382 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6384
6385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6386 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6387 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6388 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6389 spy->assertNoEvents();
6390}
6391
6392/**
6393 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6394 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6395 * to the window.
6396 */
6397TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6398 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006399 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006400 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6402
6403 // Inject an event outside the spy window's touchable region.
6404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6405 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6407 window->consumeMotionDown();
6408 spy->assertNoEvents();
6409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6410 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6411 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6412 window->consumeMotionUp();
6413 spy->assertNoEvents();
6414
6415 // Inject an event inside the spy window's touchable region.
6416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6417 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6418 {5, 10}))
6419 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6420 window->consumeMotionDown();
6421 spy->consumeMotionDown();
6422}
6423
6424/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006425 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006426 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006427 */
6428TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6429 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006430 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006431 auto spy = createSpy();
6432 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006433 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006434 spy->setFrame(Rect{0, 0, 20, 20});
6435 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6436
6437 // Inject an event outside the spy window's frame and touchable region.
6438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006439 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6440 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006441 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6442 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006443 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006444}
6445
6446/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006447 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6448 * any other windows - including other spy windows - will also be cancelled.
6449 */
6450TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6451 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006452 auto spy1 = createSpy();
6453 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6455
6456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6457 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6458 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6459 window->consumeMotionDown();
6460 spy1->consumeMotionDown();
6461 spy2->consumeMotionDown();
6462
6463 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006464 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006465 spy2->assertNoEvents();
6466 spy1->consumeMotionCancel();
6467 window->consumeMotionCancel();
6468
6469 // The rest of the gesture should only be sent to the second spy window.
6470 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6471 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6472 ADISPLAY_ID_DEFAULT))
6473 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6474 spy2->consumeMotionMove();
6475 spy1->assertNoEvents();
6476 window->assertNoEvents();
6477}
6478
6479/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006480 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6481 * in the middle of the gesture.
6482 */
6483TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6484 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006485 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6487
6488 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6489 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6491 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6492 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6493
6494 window->releaseChannel();
6495
6496 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6497
6498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6499 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6500 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6501 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6502}
6503
6504/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006505 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6506 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006507 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006508TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006509 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006510 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006511
6512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6513
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006514 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6516 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6517 {100, 200}))
6518 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006519 spy->consumeMotionDown();
6520 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006521
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006522 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006523 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006524 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006525
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006526 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006527 const MotionEvent secondFingerDownEvent =
6528 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6529 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6530 AINPUT_SOURCE_TOUCHSCREEN)
6531 .displayId(ADISPLAY_ID_DEFAULT)
6532 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6533 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6534 .x(100)
6535 .y(200))
6536 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6537 .build();
6538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6539 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6540 InputEventInjectionSync::WAIT_FOR_RESULT))
6541 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6542
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006543 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6544
6545 // Third finger goes down outside all windows, so injection should fail.
6546 const MotionEvent thirdFingerDownEvent =
6547 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6548 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6549 AINPUT_SOURCE_TOUCHSCREEN)
6550 .displayId(ADISPLAY_ID_DEFAULT)
6551 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6552 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6553 .x(100)
6554 .y(200))
6555 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6556 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6557 .build();
6558 ASSERT_EQ(InputEventInjectionResult::FAILED,
6559 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6560 InputEventInjectionSync::WAIT_FOR_RESULT))
6561 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6562
6563 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006564 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006565}
6566
6567/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006568 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6569 * pointers that are down within its bounds.
6570 */
6571TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6572 auto windowLeft = createForeground();
6573 windowLeft->setFrame({0, 0, 100, 200});
6574 auto windowRight = createForeground();
6575 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006576 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006577 spy->setFrame({0, 0, 200, 200});
6578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6579
6580 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6581 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6582 {50, 50}))
6583 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6584 windowLeft->consumeMotionDown();
6585 spy->consumeMotionDown();
6586
6587 const MotionEvent secondFingerDownEvent =
6588 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6589 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6590 AINPUT_SOURCE_TOUCHSCREEN)
6591 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6592 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6593 .pointer(
6594 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6595 .build();
6596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6597 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6598 InputEventInjectionSync::WAIT_FOR_RESULT))
6599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6600 windowRight->consumeMotionDown();
6601 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6602}
6603
6604/**
6605 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6606 * the spy should receive the second pointer with ACTION_DOWN.
6607 */
6608TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6609 auto window = createForeground();
6610 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006611 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006612 spyRight->setFrame({100, 0, 200, 200});
6613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6614
6615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6616 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6617 {50, 50}))
6618 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6619 window->consumeMotionDown();
6620 spyRight->assertNoEvents();
6621
6622 const MotionEvent secondFingerDownEvent =
6623 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6624 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6625 AINPUT_SOURCE_TOUCHSCREEN)
6626 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6627 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6628 .pointer(
6629 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6630 .build();
6631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6632 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6633 InputEventInjectionSync::WAIT_FOR_RESULT))
6634 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6635 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6636 spyRight->consumeMotionDown();
6637}
6638
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006639/**
6640 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6641 * windows should be allowed to control split touch.
6642 */
6643TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006644 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006645 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006646 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006647 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006648
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006649 auto window = createForeground();
6650 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006651
6652 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6653
6654 // First finger down, no window touched.
6655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6656 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6657 {100, 200}))
6658 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6659 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6660 window->assertNoEvents();
6661
6662 // Second finger down on window, the window should receive touch down.
6663 const MotionEvent secondFingerDownEvent =
6664 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6665 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6666 AINPUT_SOURCE_TOUCHSCREEN)
6667 .displayId(ADISPLAY_ID_DEFAULT)
6668 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6669 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6670 .x(100)
6671 .y(200))
6672 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6673 .build();
6674 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6675 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6676 InputEventInjectionSync::WAIT_FOR_RESULT))
6677 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6678
6679 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6680 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6681}
6682
6683/**
6684 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6685 * do not receive key events.
6686 */
6687TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006688 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006689 spy->setFocusable(false);
6690
6691 auto window = createForeground();
6692 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6693 setFocusedWindow(window);
6694 window->consumeFocusEvent(true);
6695
6696 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6697 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6698 window->consumeKeyDown(ADISPLAY_ID_NONE);
6699
6700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6701 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6702 window->consumeKeyUp(ADISPLAY_ID_NONE);
6703
6704 spy->assertNoEvents();
6705}
6706
Prabir Pradhand65552b2021-10-07 11:23:50 -07006707class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6708public:
6709 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6710 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6711 std::make_shared<FakeApplicationHandle>();
6712 sp<FakeWindowHandle> overlay =
6713 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6714 ADISPLAY_ID_DEFAULT);
6715 overlay->setFocusable(false);
6716 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006717 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006718 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006719 overlay->setTrustedOverlay(true);
6720
6721 std::shared_ptr<FakeApplicationHandle> application =
6722 std::make_shared<FakeApplicationHandle>();
6723 sp<FakeWindowHandle> window =
6724 new FakeWindowHandle(application, mDispatcher, "Application window",
6725 ADISPLAY_ID_DEFAULT);
6726 window->setFocusable(true);
6727 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006728
6729 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6731 setFocusedWindow(window);
6732 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6733 return {std::move(overlay), std::move(window)};
6734 }
6735
6736 void sendFingerEvent(int32_t action) {
6737 NotifyMotionArgs motionArgs =
6738 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6739 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6740 mDispatcher->notifyMotion(&motionArgs);
6741 }
6742
6743 void sendStylusEvent(int32_t action) {
6744 NotifyMotionArgs motionArgs =
6745 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6746 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6747 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6748 mDispatcher->notifyMotion(&motionArgs);
6749 }
6750};
6751
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006752using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6753
6754TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6755 ScopedSilentDeath _silentDeath;
6756
Prabir Pradhand65552b2021-10-07 11:23:50 -07006757 auto [overlay, window] = setupStylusOverlayScenario();
6758 overlay->setTrustedOverlay(false);
6759 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6760 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6761 ".* not a trusted overlay");
6762}
6763
6764TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6765 auto [overlay, window] = setupStylusOverlayScenario();
6766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6767
6768 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6769 overlay->consumeMotionDown();
6770 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6771 overlay->consumeMotionUp();
6772
6773 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6774 window->consumeMotionDown();
6775 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6776 window->consumeMotionUp();
6777
6778 overlay->assertNoEvents();
6779 window->assertNoEvents();
6780}
6781
6782TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6783 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006784 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6786
6787 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6788 overlay->consumeMotionDown();
6789 window->consumeMotionDown();
6790 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6791 overlay->consumeMotionUp();
6792 window->consumeMotionUp();
6793
6794 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6795 window->consumeMotionDown();
6796 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6797 window->consumeMotionUp();
6798
6799 overlay->assertNoEvents();
6800 window->assertNoEvents();
6801}
6802
Garfield Tane84e6f92019-08-29 17:28:41 -07006803} // namespace android::inputdispatcher