blob: b3f51ee576301cac06be0d2bb5bf74d78e8a1c87 [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 Pradhan76bdecb2022-01-31 11:14:15 -0800994 mInfo.inputConfig = WindowInfo::InputConfig::NONE;
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
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001038 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1039
chaviw3277faf2021-05-19 16:45:23 -05001040 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001041
Bernardo Rufino7393d172021-02-26 13:56:11 +00001042 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1043
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001044 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001045 mInfo.frameLeft = frame.left;
1046 mInfo.frameTop = frame.top;
1047 mInfo.frameRight = frame.right;
1048 mInfo.frameBottom = frame.bottom;
1049 mInfo.touchableRegion.clear();
1050 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001051
1052 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1053 ui::Transform translate;
1054 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1055 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001056 }
1057
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001058 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1059
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001060 void setIsWallpaper(bool isWallpaper) {
1061 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1062 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001063
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001064 void setDupTouchToWallpaper(bool hasWallpaper) {
1065 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1066 }
chaviwd1c23182019-12-20 18:44:56 -08001067
Prabir Pradhand65552b2021-10-07 11:23:50 -07001068 void setInputFeatures(Flags<WindowInfo::Feature> features) { mInfo.inputFeatures = features; }
1069
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001070 void setTrustedOverlay(bool trustedOverlay) {
1071 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1072 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001073
chaviw9eaa22c2020-07-01 16:21:27 -07001074 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1075 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1076 }
1077
1078 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001079
yunho.shinf4a80b82020-11-16 21:13:57 +09001080 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1081
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001082 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1083 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1084 expectedFlags);
1085 }
1086
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001087 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1088 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1089 }
1090
Svet Ganov5d3bc372020-01-26 23:11:07 -08001091 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001092 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001093 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1094 expectedFlags);
1095 }
1096
1097 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001098 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001099 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1100 expectedFlags);
1101 }
1102
1103 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001104 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001105 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1106 }
1107
1108 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1109 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001110 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1111 expectedFlags);
1112 }
1113
Svet Ganov5d3bc372020-01-26 23:11:07 -08001114 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001115 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1116 int32_t expectedFlags = 0) {
1117 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1118 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001119 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1120 }
1121
1122 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001123 int32_t expectedFlags = 0) {
1124 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1125 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001126 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1127 }
1128
1129 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001130 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001131 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1132 expectedFlags);
1133 }
1134
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001135 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1136 int32_t expectedFlags = 0) {
1137 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1138 expectedFlags);
1139 }
1140
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001141 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1142 int32_t expectedFlags = 0) {
1143 InputEvent* event = consume();
1144 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1145 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1146 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1147 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1148 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1149 }
1150
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001151 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1152 ASSERT_NE(mInputReceiver, nullptr)
1153 << "Cannot consume events from a window with no receiver";
1154 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1155 }
1156
Prabir Pradhan99987712020-11-10 18:43:05 -08001157 void consumeCaptureEvent(bool hasCapture) {
1158 ASSERT_NE(mInputReceiver, nullptr)
1159 << "Cannot consume events from a window with no receiver";
1160 mInputReceiver->consumeCaptureEvent(hasCapture);
1161 }
1162
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001163 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1164 std::optional<int32_t> expectedDisplayId,
1165 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001166 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1167 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1168 expectedFlags);
1169 }
1170
arthurhungb89ccb02020-12-30 16:19:01 +08001171 void consumeDragEvent(bool isExiting, float x, float y) {
1172 mInputReceiver->consumeDragEvent(isExiting, x, y);
1173 }
1174
Antonio Kantekf16f2832021-09-28 04:39:20 +00001175 void consumeTouchModeEvent(bool inTouchMode) {
1176 ASSERT_NE(mInputReceiver, nullptr)
1177 << "Cannot consume events from a window with no receiver";
1178 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1179 }
1180
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001181 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001182 if (mInputReceiver == nullptr) {
1183 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1184 return std::nullopt;
1185 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001186 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001187 }
1188
1189 void finishEvent(uint32_t sequenceNum) {
1190 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1191 mInputReceiver->finishEvent(sequenceNum);
1192 }
1193
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001194 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1195 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1196 mInputReceiver->sendTimeline(inputEventId, timeline);
1197 }
1198
chaviwaf87b3e2019-10-01 16:59:28 -07001199 InputEvent* consume() {
1200 if (mInputReceiver == nullptr) {
1201 return nullptr;
1202 }
1203 return mInputReceiver->consume();
1204 }
1205
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001206 MotionEvent* consumeMotion() {
1207 InputEvent* event = consume();
1208 if (event == nullptr) {
1209 ADD_FAILURE() << "Consume failed : no event";
1210 return nullptr;
1211 }
1212 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1213 ADD_FAILURE() << "Instead of motion event, got "
1214 << inputEventTypeToString(event->getType());
1215 return nullptr;
1216 }
1217 return static_cast<MotionEvent*>(event);
1218 }
1219
Arthur Hungb92218b2018-08-14 12:00:21 +08001220 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001221 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001222 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001223 return; // Can't receive events if the window does not have input channel
1224 }
1225 ASSERT_NE(nullptr, mInputReceiver)
1226 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001227 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001228 }
1229
chaviwaf87b3e2019-10-01 16:59:28 -07001230 sp<IBinder> getToken() { return mInfo.token; }
1231
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001232 const std::string& getName() { return mName; }
1233
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001234 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1235 mInfo.ownerPid = ownerPid;
1236 mInfo.ownerUid = ownerUid;
1237 }
1238
Prabir Pradhanedd96402022-02-15 01:46:16 -08001239 int32_t getPid() const { return mInfo.ownerPid; }
1240
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001241 void destroyReceiver() { mInputReceiver = nullptr; }
1242
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001243 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1244
chaviwd1c23182019-12-20 18:44:56 -08001245private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001246 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001247 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001248 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001249};
1250
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001251std::atomic<int32_t> FakeWindowHandle::sId{1};
1252
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001253static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001254 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001255 int32_t displayId = ADISPLAY_ID_NONE,
1256 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001257 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1258 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001259 KeyEvent event;
1260 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1261
1262 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001263 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001264 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1265 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001266
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001267 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1268 if (!allowKeyRepeat) {
1269 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1270 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001271 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001272 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001273 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001274}
1275
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001276static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001277 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001278 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1279}
1280
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001281// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1282// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1283// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001284static InputEventInjectionResult injectKeyDownNoRepeat(
1285 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001286 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1287 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1288 /* allowKeyRepeat */ false);
1289}
1290
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001291static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001293 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1294}
1295
Garfield Tandf26e862020-07-01 20:18:19 -07001296class PointerBuilder {
1297public:
1298 PointerBuilder(int32_t id, int32_t toolType) {
1299 mProperties.clear();
1300 mProperties.id = id;
1301 mProperties.toolType = toolType;
1302 mCoords.clear();
1303 }
1304
1305 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1306
1307 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1308
1309 PointerBuilder& axis(int32_t axis, float value) {
1310 mCoords.setAxisValue(axis, value);
1311 return *this;
1312 }
1313
1314 PointerProperties buildProperties() const { return mProperties; }
1315
1316 PointerCoords buildCoords() const { return mCoords; }
1317
1318private:
1319 PointerProperties mProperties;
1320 PointerCoords mCoords;
1321};
1322
1323class MotionEventBuilder {
1324public:
1325 MotionEventBuilder(int32_t action, int32_t source) {
1326 mAction = action;
1327 mSource = source;
1328 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1329 }
1330
1331 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1332 mEventTime = eventTime;
1333 return *this;
1334 }
1335
1336 MotionEventBuilder& displayId(int32_t displayId) {
1337 mDisplayId = displayId;
1338 return *this;
1339 }
1340
1341 MotionEventBuilder& actionButton(int32_t actionButton) {
1342 mActionButton = actionButton;
1343 return *this;
1344 }
1345
arthurhung6d4bed92021-03-17 11:59:33 +08001346 MotionEventBuilder& buttonState(int32_t buttonState) {
1347 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001348 return *this;
1349 }
1350
1351 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1352 mRawXCursorPosition = rawXCursorPosition;
1353 return *this;
1354 }
1355
1356 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1357 mRawYCursorPosition = rawYCursorPosition;
1358 return *this;
1359 }
1360
1361 MotionEventBuilder& pointer(PointerBuilder pointer) {
1362 mPointers.push_back(pointer);
1363 return *this;
1364 }
1365
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001366 MotionEventBuilder& addFlag(uint32_t flags) {
1367 mFlags |= flags;
1368 return *this;
1369 }
1370
Garfield Tandf26e862020-07-01 20:18:19 -07001371 MotionEvent build() {
1372 std::vector<PointerProperties> pointerProperties;
1373 std::vector<PointerCoords> pointerCoords;
1374 for (const PointerBuilder& pointer : mPointers) {
1375 pointerProperties.push_back(pointer.buildProperties());
1376 pointerCoords.push_back(pointer.buildCoords());
1377 }
1378
1379 // Set mouse cursor position for the most common cases to avoid boilerplate.
1380 if (mSource == AINPUT_SOURCE_MOUSE &&
1381 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1382 mPointers.size() == 1) {
1383 mRawXCursorPosition = pointerCoords[0].getX();
1384 mRawYCursorPosition = pointerCoords[0].getY();
1385 }
1386
1387 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001388 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001389 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001390 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001391 mButtonState, MotionClassification::NONE, identityTransform,
1392 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001393 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1394 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001395
1396 return event;
1397 }
1398
1399private:
1400 int32_t mAction;
1401 int32_t mSource;
1402 nsecs_t mEventTime;
1403 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1404 int32_t mActionButton{0};
1405 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001406 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001407 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1408 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1409
1410 std::vector<PointerBuilder> mPointers;
1411};
1412
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001413static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001414 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001415 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001416 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001417 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1418 injectionTimeout,
1419 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1420}
1421
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001422static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001423 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001424 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001425 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001426 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1427 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001428 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001429 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001430 MotionEvent event = MotionEventBuilder(action, source)
1431 .displayId(displayId)
1432 .eventTime(eventTime)
1433 .rawXCursorPosition(cursorPosition.x)
1434 .rawYCursorPosition(cursorPosition.y)
1435 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1436 .x(position.x)
1437 .y(position.y))
1438 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001439
1440 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001441 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001442}
1443
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001444static InputEventInjectionResult injectMotionDown(
1445 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1446 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001447 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001448}
1449
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001450static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001451 int32_t source, int32_t displayId,
1452 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001453 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001454}
1455
Jackal Guof9696682018-10-05 12:23:23 +08001456static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1457 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1458 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001459 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1460 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1461 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001462
1463 return args;
1464}
1465
chaviwd1c23182019-12-20 18:44:56 -08001466static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1467 const std::vector<PointF>& points) {
1468 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001469 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1470 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1471 }
1472
chaviwd1c23182019-12-20 18:44:56 -08001473 PointerProperties pointerProperties[pointerCount];
1474 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001475
chaviwd1c23182019-12-20 18:44:56 -08001476 for (size_t i = 0; i < pointerCount; i++) {
1477 pointerProperties[i].clear();
1478 pointerProperties[i].id = i;
1479 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001480
chaviwd1c23182019-12-20 18:44:56 -08001481 pointerCoords[i].clear();
1482 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1483 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1484 }
Jackal Guof9696682018-10-05 12:23:23 +08001485
1486 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1487 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001488 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001489 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1490 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001491 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1492 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001493 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1494 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001495
1496 return args;
1497}
1498
chaviwd1c23182019-12-20 18:44:56 -08001499static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1500 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1501}
1502
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001503static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1504 const PointerCaptureRequest& request) {
1505 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001506}
1507
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001508/**
1509 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1510 * broken channel.
1511 */
1512TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1513 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1514 sp<FakeWindowHandle> window =
1515 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1516 ADISPLAY_ID_DEFAULT);
1517
1518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1519
1520 // Window closes its channel, but the window remains.
1521 window->destroyReceiver();
1522 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1523}
1524
Arthur Hungb92218b2018-08-14 12:00:21 +08001525TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001526 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001527 sp<FakeWindowHandle> window =
1528 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001529
Arthur Hung72d8dc32020-03-28 00:48:39 +00001530 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001531 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1532 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1533 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001534
1535 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001536 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001537}
1538
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001539TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1540 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1541 sp<FakeWindowHandle> window =
1542 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1543
1544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1545 // Inject a MotionEvent to an unknown display.
1546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1547 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1548 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1549
1550 // Window should receive motion event.
1551 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1552}
1553
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001554/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001555 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001556 * This test serves as a sanity check for the next test, where setInputWindows is
1557 * called twice.
1558 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001559TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001560 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001561 sp<FakeWindowHandle> window =
1562 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1563 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001564
1565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001567 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1568 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001569 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001570
1571 // Window should receive motion event.
1572 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1573}
1574
1575/**
1576 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001577 */
1578TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001579 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001580 sp<FakeWindowHandle> window =
1581 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1582 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001583
1584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1585 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001587 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1588 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001590
1591 // Window should receive motion event.
1592 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1593}
1594
Arthur Hungb92218b2018-08-14 12:00:21 +08001595// The foreground window should receive the first touch down event.
1596TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001597 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001598 sp<FakeWindowHandle> windowTop =
1599 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1600 sp<FakeWindowHandle> windowSecond =
1601 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001602
Arthur Hung72d8dc32020-03-28 00:48:39 +00001603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1605 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1606 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001607
1608 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001609 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001610 windowSecond->assertNoEvents();
1611}
1612
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001613/**
1614 * Two windows: A top window, and a wallpaper behind the window.
1615 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1616 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001617 * 1. foregroundWindow <-- dup touch to wallpaper
1618 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001619 */
1620TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1621 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1622 sp<FakeWindowHandle> foregroundWindow =
1623 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001624 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001625 sp<FakeWindowHandle> wallpaperWindow =
1626 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001627 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001628 constexpr int expectedWallpaperFlags =
1629 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1630
1631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1633 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1634 {100, 200}))
1635 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1636
1637 // Both foreground window and its wallpaper should receive the touch down
1638 foregroundWindow->consumeMotionDown();
1639 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1640
1641 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1642 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1643 ADISPLAY_ID_DEFAULT, {110, 200}))
1644 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1645
1646 foregroundWindow->consumeMotionMove();
1647 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1648
1649 // Now the foreground window goes away, but the wallpaper stays
1650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1651 foregroundWindow->consumeMotionCancel();
1652 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1653 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1654}
1655
1656/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001657 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1658 * with the following differences:
1659 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1660 * clean up the connection.
1661 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1662 * Ensure that there's no crash in the dispatcher.
1663 */
1664TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1665 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1666 sp<FakeWindowHandle> foregroundWindow =
1667 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001668 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001669 sp<FakeWindowHandle> wallpaperWindow =
1670 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001671 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001672 constexpr int expectedWallpaperFlags =
1673 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1674
1675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1676 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1677 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1678 {100, 200}))
1679 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1680
1681 // Both foreground window and its wallpaper should receive the touch down
1682 foregroundWindow->consumeMotionDown();
1683 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1684
1685 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1686 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1687 ADISPLAY_ID_DEFAULT, {110, 200}))
1688 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1689
1690 foregroundWindow->consumeMotionMove();
1691 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1692
1693 // Wallpaper closes its channel, but the window remains.
1694 wallpaperWindow->destroyReceiver();
1695 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1696
1697 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1698 // is no longer valid.
1699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1700 foregroundWindow->consumeMotionCancel();
1701}
1702
1703/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001704 * A single window that receives touch (on top), and a wallpaper window underneath it.
1705 * The top window gets a multitouch gesture.
1706 * Ensure that wallpaper gets the same gesture.
1707 */
1708TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1709 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1710 sp<FakeWindowHandle> window =
1711 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001712 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001713
1714 sp<FakeWindowHandle> wallpaperWindow =
1715 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001716 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001717 constexpr int expectedWallpaperFlags =
1718 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1719
1720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1721
1722 // Touch down on top window
1723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1724 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1725 {100, 100}))
1726 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1727
1728 // Both top window and its wallpaper should receive the touch down
1729 window->consumeMotionDown();
1730 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1731
1732 // Second finger down on the top window
1733 const MotionEvent secondFingerDownEvent =
1734 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1735 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1736 AINPUT_SOURCE_TOUCHSCREEN)
1737 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1738 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1739 .x(100)
1740 .y(100))
1741 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1742 .x(150)
1743 .y(150))
1744 .build();
1745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1746 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1747 InputEventInjectionSync::WAIT_FOR_RESULT))
1748 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1749
1750 window->consumeMotionPointerDown(1 /* pointerIndex */);
1751 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1752 expectedWallpaperFlags);
1753 window->assertNoEvents();
1754 wallpaperWindow->assertNoEvents();
1755}
1756
1757/**
1758 * Two windows: a window on the left and window on the right.
1759 * A third window, wallpaper, is behind both windows, and spans both top windows.
1760 * The first touch down goes to the left window. A second pointer touches down on the right window.
1761 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1762 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1763 * ACTION_POINTER_DOWN(1).
1764 */
1765TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1766 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1767 sp<FakeWindowHandle> leftWindow =
1768 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1769 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001770 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001771
1772 sp<FakeWindowHandle> rightWindow =
1773 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1774 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001775 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001776
1777 sp<FakeWindowHandle> wallpaperWindow =
1778 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1779 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001780 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001781 constexpr int expectedWallpaperFlags =
1782 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1783
1784 mDispatcher->setInputWindows(
1785 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1786
1787 // Touch down on left window
1788 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1789 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1790 {100, 100}))
1791 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1792
1793 // Both foreground window and its wallpaper should receive the touch down
1794 leftWindow->consumeMotionDown();
1795 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1796
1797 // Second finger down on the right window
1798 const MotionEvent secondFingerDownEvent =
1799 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1800 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1801 AINPUT_SOURCE_TOUCHSCREEN)
1802 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1803 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1804 .x(100)
1805 .y(100))
1806 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1807 .x(300)
1808 .y(100))
1809 .build();
1810 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1811 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1812 InputEventInjectionSync::WAIT_FOR_RESULT))
1813 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1814
1815 leftWindow->consumeMotionMove();
1816 // Since the touch is split, right window gets ACTION_DOWN
1817 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1818 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1819 expectedWallpaperFlags);
1820
1821 // Now, leftWindow, which received the first finger, disappears.
1822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1823 leftWindow->consumeMotionCancel();
1824 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1825 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1826
1827 // The pointer that's still down on the right window moves, and goes to the right window only.
1828 // As far as the dispatcher's concerned though, both pointers are still present.
1829 const MotionEvent secondFingerMoveEvent =
1830 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1831 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1832 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1833 .x(100)
1834 .y(100))
1835 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1836 .x(310)
1837 .y(110))
1838 .build();
1839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1840 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1841 InputEventInjectionSync::WAIT_FOR_RESULT));
1842 rightWindow->consumeMotionMove();
1843
1844 leftWindow->assertNoEvents();
1845 rightWindow->assertNoEvents();
1846 wallpaperWindow->assertNoEvents();
1847}
1848
Garfield Tandf26e862020-07-01 20:18:19 -07001849TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001850 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001851 sp<FakeWindowHandle> windowLeft =
1852 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1853 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001854 sp<FakeWindowHandle> windowRight =
1855 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1856 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001857
1858 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1859
1860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1861
1862 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001864 injectMotionEvent(mDispatcher,
1865 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1866 AINPUT_SOURCE_MOUSE)
1867 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1868 .x(900)
1869 .y(400))
1870 .build()));
1871 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1872 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1873 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1874 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1875
1876 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001878 injectMotionEvent(mDispatcher,
1879 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1880 AINPUT_SOURCE_MOUSE)
1881 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1882 .x(300)
1883 .y(400))
1884 .build()));
1885 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1886 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1887 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1888 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1889 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1890 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1891
1892 // Inject a series of mouse events for a mouse click
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_DOWN, AINPUT_SOURCE_MOUSE)
1896 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1897 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1898 .x(300)
1899 .y(400))
1900 .build()));
1901 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1902
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001904 injectMotionEvent(mDispatcher,
1905 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1906 AINPUT_SOURCE_MOUSE)
1907 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1908 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1909 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1910 .x(300)
1911 .y(400))
1912 .build()));
1913 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1914 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1915
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001916 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001917 injectMotionEvent(mDispatcher,
1918 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1919 AINPUT_SOURCE_MOUSE)
1920 .buttonState(0)
1921 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1922 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1923 .x(300)
1924 .y(400))
1925 .build()));
1926 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1927 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1928
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001930 injectMotionEvent(mDispatcher,
1931 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1932 .buttonState(0)
1933 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1934 .x(300)
1935 .y(400))
1936 .build()));
1937 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1938
1939 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001941 injectMotionEvent(mDispatcher,
1942 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1943 AINPUT_SOURCE_MOUSE)
1944 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1945 .x(900)
1946 .y(400))
1947 .build()));
1948 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1949 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1950 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1951 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1952 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1953 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1954}
1955
1956// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1957// directly in this test.
1958TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001959 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001960 sp<FakeWindowHandle> window =
1961 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1962 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001963
1964 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1965
1966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1967
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001969 injectMotionEvent(mDispatcher,
1970 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1971 AINPUT_SOURCE_MOUSE)
1972 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1973 .x(300)
1974 .y(400))
1975 .build()));
1976 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1977 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1978
1979 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001981 injectMotionEvent(mDispatcher,
1982 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1983 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1984 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1985 .x(300)
1986 .y(400))
1987 .build()));
1988 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1989
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001991 injectMotionEvent(mDispatcher,
1992 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1993 AINPUT_SOURCE_MOUSE)
1994 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1995 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1996 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1997 .x(300)
1998 .y(400))
1999 .build()));
2000 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2001 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2002
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002004 injectMotionEvent(mDispatcher,
2005 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2006 AINPUT_SOURCE_MOUSE)
2007 .buttonState(0)
2008 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2009 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2010 .x(300)
2011 .y(400))
2012 .build()));
2013 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2014 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2015
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002017 injectMotionEvent(mDispatcher,
2018 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2019 .buttonState(0)
2020 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2021 .x(300)
2022 .y(400))
2023 .build()));
2024 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2025
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002027 injectMotionEvent(mDispatcher,
2028 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2029 AINPUT_SOURCE_MOUSE)
2030 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2031 .x(300)
2032 .y(400))
2033 .build()));
2034 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2035 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2036}
2037
Garfield Tan00f511d2019-06-12 16:55:40 -07002038TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002039 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002040
2041 sp<FakeWindowHandle> windowLeft =
2042 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2043 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002044 sp<FakeWindowHandle> windowRight =
2045 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2046 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002047
2048 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2049
Arthur Hung72d8dc32020-03-28 00:48:39 +00002050 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002051
2052 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2053 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002055 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002056 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002057 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002058 windowRight->assertNoEvents();
2059}
2060
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002061TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002062 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002063 sp<FakeWindowHandle> window =
2064 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002065 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002066
Arthur Hung72d8dc32020-03-28 00:48:39 +00002067 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002068 setFocusedWindow(window);
2069
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002070 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002071
2072 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2073 mDispatcher->notifyKey(&keyArgs);
2074
2075 // Window should receive key down event.
2076 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2077
2078 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2079 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002080 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002081 mDispatcher->notifyDeviceReset(&args);
2082 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2083 AKEY_EVENT_FLAG_CANCELED);
2084}
2085
2086TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002087 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002088 sp<FakeWindowHandle> window =
2089 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2090
Arthur Hung72d8dc32020-03-28 00:48:39 +00002091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002092
2093 NotifyMotionArgs motionArgs =
2094 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2095 ADISPLAY_ID_DEFAULT);
2096 mDispatcher->notifyMotion(&motionArgs);
2097
2098 // Window should receive motion down event.
2099 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2100
2101 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2102 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002103 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002104 mDispatcher->notifyDeviceReset(&args);
2105 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2106 0 /*expectedFlags*/);
2107}
2108
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002109/**
2110 * Ensure the correct coordinate spaces are used by InputDispatcher.
2111 *
2112 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2113 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2114 * space.
2115 */
2116class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2117public:
2118 void SetUp() override {
2119 InputDispatcherTest::SetUp();
2120 mDisplayInfos.clear();
2121 mWindowInfos.clear();
2122 }
2123
2124 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2125 gui::DisplayInfo info;
2126 info.displayId = displayId;
2127 info.transform = transform;
2128 mDisplayInfos.push_back(std::move(info));
2129 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2130 }
2131
2132 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2133 mWindowInfos.push_back(*windowHandle->getInfo());
2134 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2135 }
2136
2137 // Set up a test scenario where the display has a scaled projection and there are two windows
2138 // on the display.
2139 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2140 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2141 // respectively.
2142 ui::Transform displayTransform;
2143 displayTransform.set(2, 0, 0, 4);
2144 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2145
2146 std::shared_ptr<FakeApplicationHandle> application =
2147 std::make_shared<FakeApplicationHandle>();
2148
2149 // Add two windows to the display. Their frames are represented in the display space.
2150 sp<FakeWindowHandle> firstWindow =
2151 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002152 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2153 addWindow(firstWindow);
2154
2155 sp<FakeWindowHandle> secondWindow =
2156 new FakeWindowHandle(application, mDispatcher, "Second Window",
2157 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002158 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2159 addWindow(secondWindow);
2160 return {std::move(firstWindow), std::move(secondWindow)};
2161 }
2162
2163private:
2164 std::vector<gui::DisplayInfo> mDisplayInfos;
2165 std::vector<gui::WindowInfo> mWindowInfos;
2166};
2167
2168TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2169 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2170 // Send down to the first window. The point is represented in the display space. The point is
2171 // selected so that if the hit test was done with the transform applied to it, then it would
2172 // end up in the incorrect window.
2173 NotifyMotionArgs downMotionArgs =
2174 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2175 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2176 mDispatcher->notifyMotion(&downMotionArgs);
2177
2178 firstWindow->consumeMotionDown();
2179 secondWindow->assertNoEvents();
2180}
2181
2182// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2183// the event should be treated as being in the logical display space.
2184TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2185 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2186 // Send down to the first window. The point is represented in the logical display space. The
2187 // point is selected so that if the hit test was done in logical display space, then it would
2188 // end up in the incorrect window.
2189 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2190 PointF{75 * 2, 55 * 4});
2191
2192 firstWindow->consumeMotionDown();
2193 secondWindow->assertNoEvents();
2194}
2195
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002196// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2197// event should be treated as being in the logical display space.
2198TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2199 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2200
2201 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2202 ui::Transform injectedEventTransform;
2203 injectedEventTransform.set(matrix);
2204 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2205 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2206
2207 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2208 .displayId(ADISPLAY_ID_DEFAULT)
2209 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2210 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2211 .x(untransformedPoint.x)
2212 .y(untransformedPoint.y))
2213 .build();
2214 event.transform(matrix);
2215
2216 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2217 InputEventInjectionSync::WAIT_FOR_RESULT);
2218
2219 firstWindow->consumeMotionDown();
2220 secondWindow->assertNoEvents();
2221}
2222
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002223TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2224 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2225
2226 // Send down to the second window.
2227 NotifyMotionArgs downMotionArgs =
2228 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2229 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2230 mDispatcher->notifyMotion(&downMotionArgs);
2231
2232 firstWindow->assertNoEvents();
2233 const MotionEvent* event = secondWindow->consumeMotion();
2234 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2235
2236 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2237 EXPECT_EQ(300, event->getRawX(0));
2238 EXPECT_EQ(880, event->getRawY(0));
2239
2240 // Ensure that the x and y values are in the window's coordinate space.
2241 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2242 // the logical display space. This will be the origin of the window space.
2243 EXPECT_EQ(100, event->getX(0));
2244 EXPECT_EQ(80, event->getY(0));
2245}
2246
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002247using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2248 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002249
2250class TransferTouchFixture : public InputDispatcherTest,
2251 public ::testing::WithParamInterface<TransferFunction> {};
2252
2253TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002254 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002255
2256 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002257 sp<FakeWindowHandle> firstWindow =
2258 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2259 sp<FakeWindowHandle> secondWindow =
2260 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002261
2262 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002263 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002264
2265 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002266 NotifyMotionArgs downMotionArgs =
2267 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2268 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002269 mDispatcher->notifyMotion(&downMotionArgs);
2270 // Only the first window should get the down event
2271 firstWindow->consumeMotionDown();
2272 secondWindow->assertNoEvents();
2273
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002274 // Transfer touch to the second window
2275 TransferFunction f = GetParam();
2276 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2277 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002278 // The first window gets cancel and the second gets down
2279 firstWindow->consumeMotionCancel();
2280 secondWindow->consumeMotionDown();
2281
2282 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002283 NotifyMotionArgs upMotionArgs =
2284 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2285 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002286 mDispatcher->notifyMotion(&upMotionArgs);
2287 // The first window gets no events and the second gets up
2288 firstWindow->assertNoEvents();
2289 secondWindow->consumeMotionUp();
2290}
2291
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002292TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002293 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002294
2295 PointF touchPoint = {10, 10};
2296
2297 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002298 sp<FakeWindowHandle> firstWindow =
2299 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002300 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002301 sp<FakeWindowHandle> secondWindow =
2302 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002303 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002304
2305 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002307
2308 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002309 NotifyMotionArgs downMotionArgs =
2310 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2311 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002312 mDispatcher->notifyMotion(&downMotionArgs);
2313 // Only the first window should get the down event
2314 firstWindow->consumeMotionDown();
2315 secondWindow->assertNoEvents();
2316
2317 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002318 NotifyMotionArgs pointerDownMotionArgs =
2319 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2320 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2321 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2322 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002323 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2324 // Only the first window should get the pointer down event
2325 firstWindow->consumeMotionPointerDown(1);
2326 secondWindow->assertNoEvents();
2327
2328 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002329 TransferFunction f = GetParam();
2330 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2331 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002332 // The first window gets cancel and the second gets down and pointer down
2333 firstWindow->consumeMotionCancel();
2334 secondWindow->consumeMotionDown();
2335 secondWindow->consumeMotionPointerDown(1);
2336
2337 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002338 NotifyMotionArgs pointerUpMotionArgs =
2339 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2340 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2341 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2342 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002343 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2344 // The first window gets nothing and the second gets pointer up
2345 firstWindow->assertNoEvents();
2346 secondWindow->consumeMotionPointerUp(1);
2347
2348 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002349 NotifyMotionArgs upMotionArgs =
2350 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2351 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002352 mDispatcher->notifyMotion(&upMotionArgs);
2353 // The first window gets nothing and the second gets up
2354 firstWindow->assertNoEvents();
2355 secondWindow->consumeMotionUp();
2356}
2357
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002358// For the cases of single pointer touch and two pointers non-split touch, the api's
2359// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2360// for the case where there are multiple pointers split across several windows.
2361INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2362 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002363 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2364 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002365 return dispatcher->transferTouch(destChannelToken);
2366 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002367 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2368 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002369 return dispatcher->transferTouchFocus(from, to,
2370 false /*isDragAndDrop*/);
2371 }));
2372
Svet Ganov5d3bc372020-01-26 23:11:07 -08002373TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002374 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002375
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002376 sp<FakeWindowHandle> firstWindow =
2377 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002378 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002379
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002380 sp<FakeWindowHandle> secondWindow =
2381 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002382 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002383
2384 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002385 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002386
2387 PointF pointInFirst = {300, 200};
2388 PointF pointInSecond = {300, 600};
2389
2390 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002391 NotifyMotionArgs firstDownMotionArgs =
2392 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2393 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002394 mDispatcher->notifyMotion(&firstDownMotionArgs);
2395 // Only the first window should get the down event
2396 firstWindow->consumeMotionDown();
2397 secondWindow->assertNoEvents();
2398
2399 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002400 NotifyMotionArgs secondDownMotionArgs =
2401 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2402 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2403 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2404 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002405 mDispatcher->notifyMotion(&secondDownMotionArgs);
2406 // The first window gets a move and the second a down
2407 firstWindow->consumeMotionMove();
2408 secondWindow->consumeMotionDown();
2409
2410 // Transfer touch focus to the second window
2411 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2412 // The first window gets cancel and the new gets pointer down (it already saw down)
2413 firstWindow->consumeMotionCancel();
2414 secondWindow->consumeMotionPointerDown(1);
2415
2416 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002417 NotifyMotionArgs pointerUpMotionArgs =
2418 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2419 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2420 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2421 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002422 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2423 // The first window gets nothing and the second gets pointer up
2424 firstWindow->assertNoEvents();
2425 secondWindow->consumeMotionPointerUp(1);
2426
2427 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002428 NotifyMotionArgs upMotionArgs =
2429 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2430 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002431 mDispatcher->notifyMotion(&upMotionArgs);
2432 // The first window gets nothing and the second gets up
2433 firstWindow->assertNoEvents();
2434 secondWindow->consumeMotionUp();
2435}
2436
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002437// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2438// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2439// touch is not supported, so the touch should continue on those windows and the transferred-to
2440// window should get nothing.
2441TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2442 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2443
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002444 sp<FakeWindowHandle> firstWindow =
2445 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2446 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002447
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002448 sp<FakeWindowHandle> secondWindow =
2449 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2450 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002451
2452 // Add the windows to the dispatcher
2453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2454
2455 PointF pointInFirst = {300, 200};
2456 PointF pointInSecond = {300, 600};
2457
2458 // Send down to the first window
2459 NotifyMotionArgs firstDownMotionArgs =
2460 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2461 ADISPLAY_ID_DEFAULT, {pointInFirst});
2462 mDispatcher->notifyMotion(&firstDownMotionArgs);
2463 // Only the first window should get the down event
2464 firstWindow->consumeMotionDown();
2465 secondWindow->assertNoEvents();
2466
2467 // Send down to the second window
2468 NotifyMotionArgs secondDownMotionArgs =
2469 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2470 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2471 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2472 {pointInFirst, pointInSecond});
2473 mDispatcher->notifyMotion(&secondDownMotionArgs);
2474 // The first window gets a move and the second a down
2475 firstWindow->consumeMotionMove();
2476 secondWindow->consumeMotionDown();
2477
2478 // Transfer touch focus to the second window
2479 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2480 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2481 ASSERT_FALSE(transferred);
2482 firstWindow->assertNoEvents();
2483 secondWindow->assertNoEvents();
2484
2485 // The rest of the dispatch should proceed as normal
2486 // Send pointer up to the second window
2487 NotifyMotionArgs pointerUpMotionArgs =
2488 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2489 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2490 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2491 {pointInFirst, pointInSecond});
2492 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2493 // The first window gets MOVE and the second gets pointer up
2494 firstWindow->consumeMotionMove();
2495 secondWindow->consumeMotionUp();
2496
2497 // Send up event to the first window
2498 NotifyMotionArgs upMotionArgs =
2499 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2500 ADISPLAY_ID_DEFAULT);
2501 mDispatcher->notifyMotion(&upMotionArgs);
2502 // The first window gets nothing and the second gets up
2503 firstWindow->consumeMotionUp();
2504 secondWindow->assertNoEvents();
2505}
2506
Arthur Hungabbb9d82021-09-01 14:52:30 +00002507// This case will create two windows and one mirrored window on the default display and mirror
2508// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2509// the windows info of second display before default display.
2510TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2511 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2512 sp<FakeWindowHandle> firstWindowInPrimary =
2513 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2514 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002515 sp<FakeWindowHandle> secondWindowInPrimary =
2516 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2517 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002518
2519 sp<FakeWindowHandle> mirrorWindowInPrimary =
2520 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2521 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002522
2523 sp<FakeWindowHandle> firstWindowInSecondary =
2524 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2525 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002526
2527 sp<FakeWindowHandle> secondWindowInSecondary =
2528 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2529 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002530
2531 // Update window info, let it find window handle of second display first.
2532 mDispatcher->setInputWindows(
2533 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2534 {ADISPLAY_ID_DEFAULT,
2535 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2536
2537 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2538 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2539 {50, 50}))
2540 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2541
2542 // Window should receive motion event.
2543 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2544
2545 // Transfer touch focus
2546 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2547 secondWindowInPrimary->getToken()));
2548 // The first window gets cancel.
2549 firstWindowInPrimary->consumeMotionCancel();
2550 secondWindowInPrimary->consumeMotionDown();
2551
2552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2553 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2554 ADISPLAY_ID_DEFAULT, {150, 50}))
2555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2556 firstWindowInPrimary->assertNoEvents();
2557 secondWindowInPrimary->consumeMotionMove();
2558
2559 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2560 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2561 {150, 50}))
2562 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2563 firstWindowInPrimary->assertNoEvents();
2564 secondWindowInPrimary->consumeMotionUp();
2565}
2566
2567// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2568// 'transferTouch' api.
2569TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2570 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2571 sp<FakeWindowHandle> firstWindowInPrimary =
2572 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2573 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002574 sp<FakeWindowHandle> secondWindowInPrimary =
2575 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2576 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002577
2578 sp<FakeWindowHandle> mirrorWindowInPrimary =
2579 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2580 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002581
2582 sp<FakeWindowHandle> firstWindowInSecondary =
2583 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2584 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002585
2586 sp<FakeWindowHandle> secondWindowInSecondary =
2587 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2588 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002589
2590 // Update window info, let it find window handle of second display first.
2591 mDispatcher->setInputWindows(
2592 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2593 {ADISPLAY_ID_DEFAULT,
2594 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2595
2596 // Touch on second display.
2597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2598 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2600
2601 // Window should receive motion event.
2602 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2603
2604 // Transfer touch focus
2605 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2606
2607 // The first window gets cancel.
2608 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2609 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2610
2611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2612 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2613 SECOND_DISPLAY_ID, {150, 50}))
2614 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2615 firstWindowInPrimary->assertNoEvents();
2616 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2617
2618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2619 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2621 firstWindowInPrimary->assertNoEvents();
2622 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2623}
2624
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002625TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002626 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002627 sp<FakeWindowHandle> window =
2628 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2629
Vishnu Nair47074b82020-08-14 11:54:47 -07002630 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002632 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002633
2634 window->consumeFocusEvent(true);
2635
2636 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2637 mDispatcher->notifyKey(&keyArgs);
2638
2639 // Window should receive key down event.
2640 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2641}
2642
2643TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002644 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002645 sp<FakeWindowHandle> window =
2646 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2647
Arthur Hung72d8dc32020-03-28 00:48:39 +00002648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002649
2650 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2651 mDispatcher->notifyKey(&keyArgs);
2652 mDispatcher->waitForIdle();
2653
2654 window->assertNoEvents();
2655}
2656
2657// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2658TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002659 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002660 sp<FakeWindowHandle> window =
2661 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2662
Arthur Hung72d8dc32020-03-28 00:48:39 +00002663 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002664
2665 // Send key
2666 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2667 mDispatcher->notifyKey(&keyArgs);
2668 // Send motion
2669 NotifyMotionArgs motionArgs =
2670 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2671 ADISPLAY_ID_DEFAULT);
2672 mDispatcher->notifyMotion(&motionArgs);
2673
2674 // Window should receive only the motion event
2675 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2676 window->assertNoEvents(); // Key event or focus event will not be received
2677}
2678
arthurhungea3f4fc2020-12-21 23:18:53 +08002679TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2680 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2681
arthurhungea3f4fc2020-12-21 23:18:53 +08002682 sp<FakeWindowHandle> firstWindow =
2683 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2684 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002685
arthurhungea3f4fc2020-12-21 23:18:53 +08002686 sp<FakeWindowHandle> secondWindow =
2687 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2688 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002689
2690 // Add the windows to the dispatcher
2691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2692
2693 PointF pointInFirst = {300, 200};
2694 PointF pointInSecond = {300, 600};
2695
2696 // Send down to the first window
2697 NotifyMotionArgs firstDownMotionArgs =
2698 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2699 ADISPLAY_ID_DEFAULT, {pointInFirst});
2700 mDispatcher->notifyMotion(&firstDownMotionArgs);
2701 // Only the first window should get the down event
2702 firstWindow->consumeMotionDown();
2703 secondWindow->assertNoEvents();
2704
2705 // Send down to the second window
2706 NotifyMotionArgs secondDownMotionArgs =
2707 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2708 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2709 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2710 {pointInFirst, pointInSecond});
2711 mDispatcher->notifyMotion(&secondDownMotionArgs);
2712 // The first window gets a move and the second a down
2713 firstWindow->consumeMotionMove();
2714 secondWindow->consumeMotionDown();
2715
2716 // Send pointer cancel to the second window
2717 NotifyMotionArgs pointerUpMotionArgs =
2718 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2719 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2720 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2721 {pointInFirst, pointInSecond});
2722 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2723 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2724 // The first window gets move and the second gets cancel.
2725 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2726 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2727
2728 // Send up event.
2729 NotifyMotionArgs upMotionArgs =
2730 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2731 ADISPLAY_ID_DEFAULT);
2732 mDispatcher->notifyMotion(&upMotionArgs);
2733 // The first window gets up and the second gets nothing.
2734 firstWindow->consumeMotionUp();
2735 secondWindow->assertNoEvents();
2736}
2737
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002738TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2739 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2740
2741 sp<FakeWindowHandle> window =
2742 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2744 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2745 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2746 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2747
2748 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2749 window->assertNoEvents();
2750 mDispatcher->waitForIdle();
2751}
2752
chaviwd1c23182019-12-20 18:44:56 -08002753class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002754public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002755 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002756 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002757 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002758 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002759 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002760 }
2761
chaviwd1c23182019-12-20 18:44:56 -08002762 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2763
2764 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2765 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2766 expectedDisplayId, expectedFlags);
2767 }
2768
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002769 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2770
2771 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2772
chaviwd1c23182019-12-20 18:44:56 -08002773 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2774 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2775 expectedDisplayId, expectedFlags);
2776 }
2777
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002778 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2779 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2780 expectedDisplayId, expectedFlags);
2781 }
2782
chaviwd1c23182019-12-20 18:44:56 -08002783 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2784 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2785 expectedDisplayId, expectedFlags);
2786 }
2787
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002788 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2789 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2790 expectedDisplayId, expectedFlags);
2791 }
2792
Arthur Hungfbfa5722021-11-16 02:45:54 +00002793 void consumeMotionPointerDown(int32_t pointerIdx) {
2794 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2795 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2796 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2797 0 /*expectedFlags*/);
2798 }
2799
Evan Rosky84f07f02021-04-16 10:42:42 -07002800 MotionEvent* consumeMotion() {
2801 InputEvent* event = mInputReceiver->consume();
2802 if (!event) {
2803 ADD_FAILURE() << "No event was produced";
2804 return nullptr;
2805 }
2806 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2807 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2808 return nullptr;
2809 }
2810 return static_cast<MotionEvent*>(event);
2811 }
2812
chaviwd1c23182019-12-20 18:44:56 -08002813 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2814
2815private:
2816 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002817};
2818
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002819using InputDispatcherMonitorTest = InputDispatcherTest;
2820
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002821/**
2822 * Two entities that receive touch: A window, and a global monitor.
2823 * The touch goes to the window, and then the window disappears.
2824 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2825 * for the monitor, as well.
2826 * 1. foregroundWindow
2827 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2828 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002829TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002830 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2831 sp<FakeWindowHandle> window =
2832 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2833
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002834 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002835
2836 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2838 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2839 {100, 200}))
2840 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2841
2842 // Both the foreground window and the global monitor should receive the touch down
2843 window->consumeMotionDown();
2844 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2845
2846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2847 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2848 ADISPLAY_ID_DEFAULT, {110, 200}))
2849 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2850
2851 window->consumeMotionMove();
2852 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2853
2854 // Now the foreground window goes away
2855 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2856 window->consumeMotionCancel();
2857 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2858
2859 // If more events come in, there will be no more foreground window to send them to. This will
2860 // cause a cancel for the monitor, as well.
2861 ASSERT_EQ(InputEventInjectionResult::FAILED,
2862 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2863 ADISPLAY_ID_DEFAULT, {120, 200}))
2864 << "Injection should fail because the window was removed";
2865 window->assertNoEvents();
2866 // Global monitor now gets the cancel
2867 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2868}
2869
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002870TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002871 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002872 sp<FakeWindowHandle> window =
2873 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002874 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002875
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002876 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002877
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002879 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002880 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002881 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002882 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002883}
2884
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002885TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2886 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002887
Chris Yea209fde2020-07-22 13:54:51 -07002888 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002889 sp<FakeWindowHandle> window =
2890 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002891 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002892
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002894 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002895 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002896 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002897 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002898
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002899 // Pilfer pointers from the monitor.
2900 // This should not do anything and the window should continue to receive events.
2901 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002902
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002904 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2905 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002906 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002907
2908 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2909 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002910}
2911
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002912TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002913 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2914 sp<FakeWindowHandle> window =
2915 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2917 window->setWindowOffset(20, 40);
2918 window->setWindowTransform(0, 1, -1, 0);
2919
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002920 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002921
2922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2923 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2924 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2925 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2926 MotionEvent* event = monitor.consumeMotion();
2927 // Even though window has transform, gesture monitor must not.
2928 ASSERT_EQ(ui::Transform(), event->getTransform());
2929}
2930
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002931TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002932 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002933 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002934
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002935 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002936 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002937 << "Injection should fail if there is a monitor, but no touchable window";
2938 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002939}
2940
chaviw81e2bb92019-12-18 15:03:51 -08002941TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002942 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002943 sp<FakeWindowHandle> window =
2944 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2945
Arthur Hung72d8dc32020-03-28 00:48:39 +00002946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002947
2948 NotifyMotionArgs motionArgs =
2949 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2950 ADISPLAY_ID_DEFAULT);
2951
2952 mDispatcher->notifyMotion(&motionArgs);
2953 // Window should receive motion down event.
2954 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2955
2956 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002957 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002958 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2959 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2960 motionArgs.pointerCoords[0].getX() - 10);
2961
2962 mDispatcher->notifyMotion(&motionArgs);
2963 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2964 0 /*expectedFlags*/);
2965}
2966
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002967/**
2968 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2969 * the device default right away. In the test scenario, we check both the default value,
2970 * and the action of enabling / disabling.
2971 */
2972TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002973 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002974 sp<FakeWindowHandle> window =
2975 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08002976 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002977
2978 // Set focused application.
2979 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002980 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002981
2982 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002984 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002985 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2986
2987 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002988 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002989 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002990 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2991
2992 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08002993 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
2994 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002995 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002996 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002998 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002999 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3000
3001 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003002 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003003 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003004 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3005
3006 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003007 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3008 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003009 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003010 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003012 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003013 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3014
3015 window->assertNoEvents();
3016}
3017
Gang Wange9087892020-01-07 12:17:14 -05003018TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003019 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003020 sp<FakeWindowHandle> window =
3021 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3022
3023 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003024 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003025
Arthur Hung72d8dc32020-03-28 00:48:39 +00003026 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003027 setFocusedWindow(window);
3028
Gang Wange9087892020-01-07 12:17:14 -05003029 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3030
3031 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3032 mDispatcher->notifyKey(&keyArgs);
3033
3034 InputEvent* event = window->consume();
3035 ASSERT_NE(event, nullptr);
3036
3037 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3038 ASSERT_NE(verified, nullptr);
3039 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3040
3041 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3042 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3043 ASSERT_EQ(keyArgs.source, verified->source);
3044 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3045
3046 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3047
3048 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003049 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003050 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003051 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3052 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3053 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3054 ASSERT_EQ(0, verifiedKey.repeatCount);
3055}
3056
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003057TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003058 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003059 sp<FakeWindowHandle> window =
3060 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3061
3062 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3063
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003064 ui::Transform transform;
3065 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3066
3067 gui::DisplayInfo displayInfo;
3068 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3069 displayInfo.transform = transform;
3070
3071 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003072
3073 NotifyMotionArgs motionArgs =
3074 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3075 ADISPLAY_ID_DEFAULT);
3076 mDispatcher->notifyMotion(&motionArgs);
3077
3078 InputEvent* event = window->consume();
3079 ASSERT_NE(event, nullptr);
3080
3081 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3082 ASSERT_NE(verified, nullptr);
3083 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3084
3085 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3086 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3087 EXPECT_EQ(motionArgs.source, verified->source);
3088 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3089
3090 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3091
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003092 const vec2 rawXY =
3093 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3094 motionArgs.pointerCoords[0].getXYValue());
3095 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3096 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003097 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003098 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003099 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003100 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3101 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3102}
3103
chaviw09c8d2d2020-08-24 15:48:26 -07003104/**
3105 * Ensure that separate calls to sign the same data are generating the same key.
3106 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3107 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3108 * tests.
3109 */
3110TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3111 KeyEvent event = getTestKeyEvent();
3112 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3113
3114 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3115 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3116 ASSERT_EQ(hmac1, hmac2);
3117}
3118
3119/**
3120 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3121 */
3122TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3123 KeyEvent event = getTestKeyEvent();
3124 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3125 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3126
3127 verifiedEvent.deviceId += 1;
3128 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3129
3130 verifiedEvent.source += 1;
3131 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3132
3133 verifiedEvent.eventTimeNanos += 1;
3134 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3135
3136 verifiedEvent.displayId += 1;
3137 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3138
3139 verifiedEvent.action += 1;
3140 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3141
3142 verifiedEvent.downTimeNanos += 1;
3143 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3144
3145 verifiedEvent.flags += 1;
3146 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3147
3148 verifiedEvent.keyCode += 1;
3149 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3150
3151 verifiedEvent.scanCode += 1;
3152 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3153
3154 verifiedEvent.metaState += 1;
3155 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3156
3157 verifiedEvent.repeatCount += 1;
3158 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3159}
3160
Vishnu Nair958da932020-08-21 17:12:37 -07003161TEST_F(InputDispatcherTest, SetFocusedWindow) {
3162 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3163 sp<FakeWindowHandle> windowTop =
3164 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3165 sp<FakeWindowHandle> windowSecond =
3166 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3167 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3168
3169 // Top window is also focusable but is not granted focus.
3170 windowTop->setFocusable(true);
3171 windowSecond->setFocusable(true);
3172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3173 setFocusedWindow(windowSecond);
3174
3175 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3177 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003178
3179 // Focused window should receive event.
3180 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3181 windowTop->assertNoEvents();
3182}
3183
3184TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3185 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3186 sp<FakeWindowHandle> window =
3187 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3188 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3189
3190 window->setFocusable(true);
3191 // Release channel for window is no longer valid.
3192 window->releaseChannel();
3193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3194 setFocusedWindow(window);
3195
3196 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003197 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3198 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003199
3200 // window channel is invalid, so it should not receive any input event.
3201 window->assertNoEvents();
3202}
3203
3204TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3205 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3206 sp<FakeWindowHandle> window =
3207 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003208 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003209 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3210
Vishnu Nair958da932020-08-21 17:12:37 -07003211 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3212 setFocusedWindow(window);
3213
3214 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003215 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3216 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003217
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003218 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003219 window->assertNoEvents();
3220}
3221
3222TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3223 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3224 sp<FakeWindowHandle> windowTop =
3225 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3226 sp<FakeWindowHandle> windowSecond =
3227 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3228 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3229
3230 windowTop->setFocusable(true);
3231 windowSecond->setFocusable(true);
3232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3233 setFocusedWindow(windowTop);
3234 windowTop->consumeFocusEvent(true);
3235
3236 setFocusedWindow(windowSecond, windowTop);
3237 windowSecond->consumeFocusEvent(true);
3238 windowTop->consumeFocusEvent(false);
3239
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003240 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3241 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003242
3243 // Focused window should receive event.
3244 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3245}
3246
3247TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3248 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3249 sp<FakeWindowHandle> windowTop =
3250 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3251 sp<FakeWindowHandle> windowSecond =
3252 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3254
3255 windowTop->setFocusable(true);
3256 windowSecond->setFocusable(true);
3257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3258 setFocusedWindow(windowSecond, windowTop);
3259
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003260 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3261 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003262
3263 // Event should be dropped.
3264 windowTop->assertNoEvents();
3265 windowSecond->assertNoEvents();
3266}
3267
3268TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3269 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3270 sp<FakeWindowHandle> window =
3271 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3272 sp<FakeWindowHandle> previousFocusedWindow =
3273 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3274 ADISPLAY_ID_DEFAULT);
3275 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3276
3277 window->setFocusable(true);
3278 previousFocusedWindow->setFocusable(true);
3279 window->setVisible(false);
3280 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3281 setFocusedWindow(previousFocusedWindow);
3282 previousFocusedWindow->consumeFocusEvent(true);
3283
3284 // Requesting focus on invisible window takes focus from currently focused window.
3285 setFocusedWindow(window);
3286 previousFocusedWindow->consumeFocusEvent(false);
3287
3288 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003289 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003290 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003291 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003292
3293 // Window does not get focus event or key down.
3294 window->assertNoEvents();
3295
3296 // Window becomes visible.
3297 window->setVisible(true);
3298 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3299
3300 // Window receives focus event.
3301 window->consumeFocusEvent(true);
3302 // Focused window receives key down.
3303 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3304}
3305
Vishnu Nair599f1412021-06-21 10:39:58 -07003306TEST_F(InputDispatcherTest, DisplayRemoved) {
3307 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3308 sp<FakeWindowHandle> window =
3309 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3310 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3311
3312 // window is granted focus.
3313 window->setFocusable(true);
3314 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3315 setFocusedWindow(window);
3316 window->consumeFocusEvent(true);
3317
3318 // When a display is removed window loses focus.
3319 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3320 window->consumeFocusEvent(false);
3321}
3322
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003323/**
3324 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3325 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3326 * of the 'slipperyEnterWindow'.
3327 *
3328 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3329 * a way so that the touched location is no longer covered by the top window.
3330 *
3331 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3332 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3333 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3334 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3335 * with ACTION_DOWN).
3336 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3337 * window moved itself away from the touched location and had Flag::SLIPPERY.
3338 *
3339 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3340 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3341 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3342 *
3343 * In this test, we ensure that the event received by the bottom window has
3344 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3345 */
3346TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3347 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3348 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3349
3350 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3351 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3352
3353 sp<FakeWindowHandle> slipperyExitWindow =
3354 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003355 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003356 // Make sure this one overlaps the bottom window
3357 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3358 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3359 // one. Windows with the same owner are not considered to be occluding each other.
3360 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3361
3362 sp<FakeWindowHandle> slipperyEnterWindow =
3363 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3364 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3365
3366 mDispatcher->setInputWindows(
3367 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3368
3369 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3370 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3371 ADISPLAY_ID_DEFAULT, {{50, 50}});
3372 mDispatcher->notifyMotion(&args);
3373 slipperyExitWindow->consumeMotionDown();
3374 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3375 mDispatcher->setInputWindows(
3376 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3377
3378 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3379 ADISPLAY_ID_DEFAULT, {{51, 51}});
3380 mDispatcher->notifyMotion(&args);
3381
3382 slipperyExitWindow->consumeMotionCancel();
3383
3384 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3385 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3386}
3387
Garfield Tan1c7bc862020-01-28 13:24:04 -08003388class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3389protected:
3390 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3391 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3392
Chris Yea209fde2020-07-22 13:54:51 -07003393 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003394 sp<FakeWindowHandle> mWindow;
3395
3396 virtual void SetUp() override {
3397 mFakePolicy = new FakeInputDispatcherPolicy();
3398 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003399 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003400 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3401 ASSERT_EQ(OK, mDispatcher->start());
3402
3403 setUpWindow();
3404 }
3405
3406 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003407 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003408 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3409
Vishnu Nair47074b82020-08-14 11:54:47 -07003410 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003412 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003413 mWindow->consumeFocusEvent(true);
3414 }
3415
Chris Ye2ad95392020-09-01 13:44:44 -07003416 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003417 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003418 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003419 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3420 mDispatcher->notifyKey(&keyArgs);
3421
3422 // Window should receive key down event.
3423 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3424 }
3425
3426 void expectKeyRepeatOnce(int32_t repeatCount) {
3427 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3428 InputEvent* repeatEvent = mWindow->consume();
3429 ASSERT_NE(nullptr, repeatEvent);
3430
3431 uint32_t eventType = repeatEvent->getType();
3432 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3433
3434 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3435 uint32_t eventAction = repeatKeyEvent->getAction();
3436 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3437 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3438 }
3439
Chris Ye2ad95392020-09-01 13:44:44 -07003440 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003441 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003442 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003443 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3444 mDispatcher->notifyKey(&keyArgs);
3445
3446 // Window should receive key down event.
3447 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3448 0 /*expectedFlags*/);
3449 }
3450};
3451
3452TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003453 sendAndConsumeKeyDown(1 /* deviceId */);
3454 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3455 expectKeyRepeatOnce(repeatCount);
3456 }
3457}
3458
3459TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3460 sendAndConsumeKeyDown(1 /* deviceId */);
3461 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3462 expectKeyRepeatOnce(repeatCount);
3463 }
3464 sendAndConsumeKeyDown(2 /* deviceId */);
3465 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003466 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3467 expectKeyRepeatOnce(repeatCount);
3468 }
3469}
3470
3471TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003472 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003473 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003474 sendAndConsumeKeyUp(1 /* deviceId */);
3475 mWindow->assertNoEvents();
3476}
3477
3478TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3479 sendAndConsumeKeyDown(1 /* deviceId */);
3480 expectKeyRepeatOnce(1 /*repeatCount*/);
3481 sendAndConsumeKeyDown(2 /* deviceId */);
3482 expectKeyRepeatOnce(1 /*repeatCount*/);
3483 // Stale key up from device 1.
3484 sendAndConsumeKeyUp(1 /* deviceId */);
3485 // Device 2 is still down, keep repeating
3486 expectKeyRepeatOnce(2 /*repeatCount*/);
3487 expectKeyRepeatOnce(3 /*repeatCount*/);
3488 // Device 2 key up
3489 sendAndConsumeKeyUp(2 /* deviceId */);
3490 mWindow->assertNoEvents();
3491}
3492
3493TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3494 sendAndConsumeKeyDown(1 /* deviceId */);
3495 expectKeyRepeatOnce(1 /*repeatCount*/);
3496 sendAndConsumeKeyDown(2 /* deviceId */);
3497 expectKeyRepeatOnce(1 /*repeatCount*/);
3498 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3499 sendAndConsumeKeyUp(2 /* deviceId */);
3500 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003501 mWindow->assertNoEvents();
3502}
3503
liushenxiang42232912021-05-21 20:24:09 +08003504TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3505 sendAndConsumeKeyDown(DEVICE_ID);
3506 expectKeyRepeatOnce(1 /*repeatCount*/);
3507 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3508 mDispatcher->notifyDeviceReset(&args);
3509 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3510 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3511 mWindow->assertNoEvents();
3512}
3513
Garfield Tan1c7bc862020-01-28 13:24:04 -08003514TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003515 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003516 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3517 InputEvent* repeatEvent = mWindow->consume();
3518 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3519 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3520 IdGenerator::getSource(repeatEvent->getId()));
3521 }
3522}
3523
3524TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003525 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003526
3527 std::unordered_set<int32_t> idSet;
3528 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3529 InputEvent* repeatEvent = mWindow->consume();
3530 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3531 int32_t id = repeatEvent->getId();
3532 EXPECT_EQ(idSet.end(), idSet.find(id));
3533 idSet.insert(id);
3534 }
3535}
3536
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003537/* Test InputDispatcher for MultiDisplay */
3538class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3539public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003540 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003541 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003542
Chris Yea209fde2020-07-22 13:54:51 -07003543 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003544 windowInPrimary =
3545 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003546
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003547 // Set focus window for primary display, but focused display would be second one.
3548 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003549 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003550 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003551 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003552 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003553
Chris Yea209fde2020-07-22 13:54:51 -07003554 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003555 windowInSecondary =
3556 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003557 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003558 // Set focus display to second one.
3559 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3560 // Set focus window for second display.
3561 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003562 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003563 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003564 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003565 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003566 }
3567
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003568 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003569 InputDispatcherTest::TearDown();
3570
Chris Yea209fde2020-07-22 13:54:51 -07003571 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003572 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003573 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003574 windowInSecondary.clear();
3575 }
3576
3577protected:
Chris Yea209fde2020-07-22 13:54:51 -07003578 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003579 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003580 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003581 sp<FakeWindowHandle> windowInSecondary;
3582};
3583
3584TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3585 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3587 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3588 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003589 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003590 windowInSecondary->assertNoEvents();
3591
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003592 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3594 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3595 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003596 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003597 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003598}
3599
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003600TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003601 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003602 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3603 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003604 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003605 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003606 windowInSecondary->assertNoEvents();
3607
3608 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003610 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003611 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003612 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003613
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003614 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003615 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003616
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003617 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003618 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3619 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003620
3621 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003622 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003623 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003624 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003625 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003626 windowInSecondary->assertNoEvents();
3627}
3628
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003629// Test per-display input monitors for motion event.
3630TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003631 FakeMonitorReceiver monitorInPrimary =
3632 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3633 FakeMonitorReceiver monitorInSecondary =
3634 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003635
3636 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3638 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3639 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003640 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003641 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003642 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003643 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003644
3645 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3647 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3648 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003649 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003650 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003651 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003652 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003653
3654 // Test inject a non-pointer motion event.
3655 // If specific a display, it will dispatch to the focused window of particular display,
3656 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3658 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3659 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003660 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003661 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003662 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003663 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003664}
3665
3666// Test per-display input monitors for key event.
3667TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003668 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003669 FakeMonitorReceiver monitorInPrimary =
3670 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3671 FakeMonitorReceiver monitorInSecondary =
3672 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003673
3674 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3676 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003677 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003678 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003679 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003680 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003681}
3682
Vishnu Nair958da932020-08-21 17:12:37 -07003683TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3684 sp<FakeWindowHandle> secondWindowInPrimary =
3685 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3686 secondWindowInPrimary->setFocusable(true);
3687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3688 setFocusedWindow(secondWindowInPrimary);
3689 windowInPrimary->consumeFocusEvent(false);
3690 secondWindowInPrimary->consumeFocusEvent(true);
3691
3692 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3694 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003695 windowInPrimary->assertNoEvents();
3696 windowInSecondary->assertNoEvents();
3697 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3698}
3699
Arthur Hungdfd528e2021-12-08 13:23:04 +00003700TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3701 FakeMonitorReceiver monitorInPrimary =
3702 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3703 FakeMonitorReceiver monitorInSecondary =
3704 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3705
3706 // Test touch down on primary display.
3707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3708 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3709 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3710 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3711 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3712
3713 // Test touch down on second display.
3714 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3715 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3716 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3717 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3718 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3719
3720 // Trigger cancel touch.
3721 mDispatcher->cancelCurrentTouch();
3722 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3723 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3724 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3725 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3726
3727 // Test inject a move motion event, no window/monitor should receive the event.
3728 ASSERT_EQ(InputEventInjectionResult::FAILED,
3729 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3730 ADISPLAY_ID_DEFAULT, {110, 200}))
3731 << "Inject motion event should return InputEventInjectionResult::FAILED";
3732 windowInPrimary->assertNoEvents();
3733 monitorInPrimary.assertNoEvents();
3734
3735 ASSERT_EQ(InputEventInjectionResult::FAILED,
3736 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3737 SECOND_DISPLAY_ID, {110, 200}))
3738 << "Inject motion event should return InputEventInjectionResult::FAILED";
3739 windowInSecondary->assertNoEvents();
3740 monitorInSecondary.assertNoEvents();
3741}
3742
Jackal Guof9696682018-10-05 12:23:23 +08003743class InputFilterTest : public InputDispatcherTest {
3744protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003745 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3746 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003747 NotifyMotionArgs motionArgs;
3748
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003749 motionArgs =
3750 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003751 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003752 motionArgs =
3753 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003754 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003755 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003756 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003757 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3758 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003759 } else {
3760 mFakePolicy->assertFilterInputEventWasNotCalled();
3761 }
3762 }
3763
3764 void testNotifyKey(bool expectToBeFiltered) {
3765 NotifyKeyArgs keyArgs;
3766
3767 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3768 mDispatcher->notifyKey(&keyArgs);
3769 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3770 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003771 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003772
3773 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003774 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003775 } else {
3776 mFakePolicy->assertFilterInputEventWasNotCalled();
3777 }
3778 }
3779};
3780
3781// Test InputFilter for MotionEvent
3782TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3783 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3784 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3785 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3786
3787 // Enable InputFilter
3788 mDispatcher->setInputFilterEnabled(true);
3789 // Test touch on both primary and second display, and check if both events are filtered.
3790 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3791 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3792
3793 // Disable InputFilter
3794 mDispatcher->setInputFilterEnabled(false);
3795 // Test touch on both primary and second display, and check if both events aren't filtered.
3796 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3797 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3798}
3799
3800// Test InputFilter for KeyEvent
3801TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3802 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3803 testNotifyKey(/*expectToBeFiltered*/ false);
3804
3805 // Enable InputFilter
3806 mDispatcher->setInputFilterEnabled(true);
3807 // Send a key event, and check if it is filtered.
3808 testNotifyKey(/*expectToBeFiltered*/ true);
3809
3810 // Disable InputFilter
3811 mDispatcher->setInputFilterEnabled(false);
3812 // Send a key event, and check if it isn't filtered.
3813 testNotifyKey(/*expectToBeFiltered*/ false);
3814}
3815
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003816// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3817// logical display coordinate space.
3818TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3819 ui::Transform firstDisplayTransform;
3820 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3821 ui::Transform secondDisplayTransform;
3822 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3823
3824 std::vector<gui::DisplayInfo> displayInfos(2);
3825 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3826 displayInfos[0].transform = firstDisplayTransform;
3827 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3828 displayInfos[1].transform = secondDisplayTransform;
3829
3830 mDispatcher->onWindowInfosChanged({}, displayInfos);
3831
3832 // Enable InputFilter
3833 mDispatcher->setInputFilterEnabled(true);
3834
3835 // Ensure the correct transforms are used for the displays.
3836 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3837 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3838}
3839
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003840class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3841protected:
3842 virtual void SetUp() override {
3843 InputDispatcherTest::SetUp();
3844
3845 /**
3846 * We don't need to enable input filter to test the injected event policy, but we enabled it
3847 * here to make the tests more realistic, since this policy only matters when inputfilter is
3848 * on.
3849 */
3850 mDispatcher->setInputFilterEnabled(true);
3851
3852 std::shared_ptr<InputApplicationHandle> application =
3853 std::make_shared<FakeApplicationHandle>();
3854 mWindow =
3855 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3856
3857 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3858 mWindow->setFocusable(true);
3859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3860 setFocusedWindow(mWindow);
3861 mWindow->consumeFocusEvent(true);
3862 }
3863
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003864 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3865 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003866 KeyEvent event;
3867
3868 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3869 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3870 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3871 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3872 const int32_t additionalPolicyFlags =
3873 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3874 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3875 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3876 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3877 policyFlags | additionalPolicyFlags));
3878
3879 InputEvent* received = mWindow->consume();
3880 ASSERT_NE(nullptr, received);
3881 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003882 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3883 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3884 ASSERT_EQ(flags, keyEvent.getFlags());
3885 }
3886
3887 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3888 int32_t flags) {
3889 MotionEvent event;
3890 PointerProperties pointerProperties[1];
3891 PointerCoords pointerCoords[1];
3892 pointerProperties[0].clear();
3893 pointerProperties[0].id = 0;
3894 pointerCoords[0].clear();
3895 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3896 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3897
3898 ui::Transform identityTransform;
3899 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3900 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3901 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3902 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3903 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003904 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003905 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003906 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3907
3908 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3910 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3911 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3912 policyFlags | additionalPolicyFlags));
3913
3914 InputEvent* received = mWindow->consume();
3915 ASSERT_NE(nullptr, received);
3916 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3917 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3918 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3919 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003920 }
3921
3922private:
3923 sp<FakeWindowHandle> mWindow;
3924};
3925
3926TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003927 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3928 // filter. Without it, the event will no different from a regularly injected event, and the
3929 // injected device id will be overwritten.
3930 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3931 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003932}
3933
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003934TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003935 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003936 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3937 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3938}
3939
3940TEST_F(InputFilterInjectionPolicyTest,
3941 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3942 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3943 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3944 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003945}
3946
3947TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3948 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003949 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003950}
3951
chaviwfd6d3512019-03-25 13:23:49 -07003952class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003953 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003954 InputDispatcherTest::SetUp();
3955
Chris Yea209fde2020-07-22 13:54:51 -07003956 std::shared_ptr<FakeApplicationHandle> application =
3957 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003958 mUnfocusedWindow =
3959 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003960 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07003961
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003962 mFocusedWindow =
3963 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3964 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07003965
3966 // Set focused application.
3967 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003968 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003969
3970 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003972 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003973 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003974 }
3975
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003976 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003977 InputDispatcherTest::TearDown();
3978
3979 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003980 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003981 }
3982
3983protected:
3984 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003985 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003986 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003987};
3988
3989// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3990// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3991// the onPointerDownOutsideFocus callback.
3992TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003993 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003994 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3995 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003996 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003997 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003998
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003999 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004000 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4001}
4002
4003// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4004// DOWN on the window that doesn't have focus. Ensure no window received the
4005// onPointerDownOutsideFocus callback.
4006TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004008 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004009 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004010 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004011
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004012 ASSERT_TRUE(mDispatcher->waitForIdle());
4013 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004014}
4015
4016// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4017// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4018TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004019 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4020 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004021 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004022 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004023
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004024 ASSERT_TRUE(mDispatcher->waitForIdle());
4025 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004026}
4027
4028// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4029// DOWN on the window that already has focus. Ensure no window received the
4030// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004031TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004032 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004033 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004034 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004035 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004036 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004037
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004038 ASSERT_TRUE(mDispatcher->waitForIdle());
4039 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004040}
4041
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004042// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4043// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4044TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4045 const MotionEvent event =
4046 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4047 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4048 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4049 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4050 .build();
4051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4053 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4054
4055 ASSERT_TRUE(mDispatcher->waitForIdle());
4056 mFakePolicy->assertOnPointerDownWasNotCalled();
4057 // Ensure that the unfocused window did not receive any FOCUS events.
4058 mUnfocusedWindow->assertNoEvents();
4059}
4060
chaviwaf87b3e2019-10-01 16:59:28 -07004061// These tests ensures we can send touch events to a single client when there are multiple input
4062// windows that point to the same client token.
4063class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4064 virtual void SetUp() override {
4065 InputDispatcherTest::SetUp();
4066
Chris Yea209fde2020-07-22 13:54:51 -07004067 std::shared_ptr<FakeApplicationHandle> application =
4068 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004069 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4070 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004071 mWindow1->setFrame(Rect(0, 0, 100, 100));
4072
4073 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4074 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004075 mWindow2->setFrame(Rect(100, 100, 200, 200));
4076
Arthur Hung72d8dc32020-03-28 00:48:39 +00004077 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004078 }
4079
4080protected:
4081 sp<FakeWindowHandle> mWindow1;
4082 sp<FakeWindowHandle> mWindow2;
4083
4084 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004085 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004086 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4087 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004088 }
4089
4090 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4091 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004092 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004093 InputEvent* event = window->consume();
4094
4095 ASSERT_NE(nullptr, event) << name.c_str()
4096 << ": consumer should have returned non-NULL event.";
4097
4098 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4099 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4100 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4101
4102 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004103 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004104
4105 for (size_t i = 0; i < points.size(); i++) {
4106 float expectedX = points[i].x;
4107 float expectedY = points[i].y;
4108
4109 EXPECT_EQ(expectedX, motionEvent.getX(i))
4110 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4111 << ", got " << motionEvent.getX(i);
4112 EXPECT_EQ(expectedY, motionEvent.getY(i))
4113 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4114 << ", got " << motionEvent.getY(i);
4115 }
4116 }
chaviw9eaa22c2020-07-01 16:21:27 -07004117
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004118 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004119 std::vector<PointF> expectedPoints) {
4120 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4121 ADISPLAY_ID_DEFAULT, touchedPoints);
4122 mDispatcher->notifyMotion(&motionArgs);
4123
4124 // Always consume from window1 since it's the window that has the InputReceiver
4125 consumeMotionEvent(mWindow1, action, expectedPoints);
4126 }
chaviwaf87b3e2019-10-01 16:59:28 -07004127};
4128
4129TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4130 // Touch Window 1
4131 PointF touchedPoint = {10, 10};
4132 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004133 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004134
4135 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004136 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004137
4138 // Touch Window 2
4139 touchedPoint = {150, 150};
4140 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004141 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004142}
4143
chaviw9eaa22c2020-07-01 16:21:27 -07004144TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4145 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004146 mWindow2->setWindowScale(0.5f, 0.5f);
4147
4148 // Touch Window 1
4149 PointF touchedPoint = {10, 10};
4150 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004151 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004152 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004153 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004154
4155 // Touch Window 2
4156 touchedPoint = {150, 150};
4157 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004158 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4159 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004160
chaviw9eaa22c2020-07-01 16:21:27 -07004161 // Update the transform so rotation is set
4162 mWindow2->setWindowTransform(0, -1, 1, 0);
4163 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4164 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004165}
4166
chaviw9eaa22c2020-07-01 16:21:27 -07004167TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004168 mWindow2->setWindowScale(0.5f, 0.5f);
4169
4170 // Touch Window 1
4171 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4172 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004173 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004174
4175 // Touch Window 2
4176 int32_t actionPointerDown =
4177 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004178 touchedPoints.push_back(PointF{150, 150});
4179 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4180 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004181
chaviw9eaa22c2020-07-01 16:21:27 -07004182 // Release Window 2
4183 int32_t actionPointerUp =
4184 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4185 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4186 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004187
chaviw9eaa22c2020-07-01 16:21:27 -07004188 // Update the transform so rotation is set for Window 2
4189 mWindow2->setWindowTransform(0, -1, 1, 0);
4190 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4191 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004192}
4193
chaviw9eaa22c2020-07-01 16:21:27 -07004194TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004195 mWindow2->setWindowScale(0.5f, 0.5f);
4196
4197 // Touch Window 1
4198 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4199 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004200 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004201
4202 // Touch Window 2
4203 int32_t actionPointerDown =
4204 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004205 touchedPoints.push_back(PointF{150, 150});
4206 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004207
chaviw9eaa22c2020-07-01 16:21:27 -07004208 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004209
4210 // Move both windows
4211 touchedPoints = {{20, 20}, {175, 175}};
4212 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4213 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4214
chaviw9eaa22c2020-07-01 16:21:27 -07004215 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004216
chaviw9eaa22c2020-07-01 16:21:27 -07004217 // Release Window 2
4218 int32_t actionPointerUp =
4219 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4220 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4221 expectedPoints.pop_back();
4222
4223 // Touch Window 2
4224 mWindow2->setWindowTransform(0, -1, 1, 0);
4225 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4226 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4227
4228 // Move both windows
4229 touchedPoints = {{20, 20}, {175, 175}};
4230 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4231 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4232
4233 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004234}
4235
4236TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4237 mWindow1->setWindowScale(0.5f, 0.5f);
4238
4239 // Touch Window 1
4240 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4241 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004242 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004243
4244 // Touch Window 2
4245 int32_t actionPointerDown =
4246 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004247 touchedPoints.push_back(PointF{150, 150});
4248 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004249
chaviw9eaa22c2020-07-01 16:21:27 -07004250 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004251
4252 // Move both windows
4253 touchedPoints = {{20, 20}, {175, 175}};
4254 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4255 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4256
chaviw9eaa22c2020-07-01 16:21:27 -07004257 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004258}
4259
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004260class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4261 virtual void SetUp() override {
4262 InputDispatcherTest::SetUp();
4263
Chris Yea209fde2020-07-22 13:54:51 -07004264 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004265 mApplication->setDispatchingTimeout(20ms);
4266 mWindow =
4267 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4268 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004269 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004270 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004271
4272 // Set focused application.
4273 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4274
4275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004276 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004277 mWindow->consumeFocusEvent(true);
4278 }
4279
4280 virtual void TearDown() override {
4281 InputDispatcherTest::TearDown();
4282 mWindow.clear();
4283 }
4284
4285protected:
Chris Yea209fde2020-07-22 13:54:51 -07004286 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004287 sp<FakeWindowHandle> mWindow;
4288 static constexpr PointF WINDOW_LOCATION = {20, 20};
4289
4290 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004292 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4293 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004295 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4296 WINDOW_LOCATION));
4297 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004298
4299 sp<FakeWindowHandle> addSpyWindow() {
4300 sp<FakeWindowHandle> spy =
4301 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4302 spy->setTrustedOverlay(true);
4303 spy->setFocusable(false);
4304 spy->setInputFeatures(WindowInfo::Feature::SPY);
4305 spy->setDispatchingTimeout(30ms);
4306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4307 return spy;
4308 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004309};
4310
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004311// Send a tap and respond, which should not cause an ANR.
4312TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4313 tapOnWindow();
4314 mWindow->consumeMotionDown();
4315 mWindow->consumeMotionUp();
4316 ASSERT_TRUE(mDispatcher->waitForIdle());
4317 mFakePolicy->assertNotifyAnrWasNotCalled();
4318}
4319
4320// Send a regular key and respond, which should not cause an ANR.
4321TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004322 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004323 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4324 ASSERT_TRUE(mDispatcher->waitForIdle());
4325 mFakePolicy->assertNotifyAnrWasNotCalled();
4326}
4327
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004328TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4329 mWindow->setFocusable(false);
4330 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4331 mWindow->consumeFocusEvent(false);
4332
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004333 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004334 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004335 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4336 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004337 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004338 // Key will not go to window because we have no focused window.
4339 // The 'no focused window' ANR timer should start instead.
4340
4341 // Now, the focused application goes away.
4342 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4343 // The key should get dropped and there should be no ANR.
4344
4345 ASSERT_TRUE(mDispatcher->waitForIdle());
4346 mFakePolicy->assertNotifyAnrWasNotCalled();
4347}
4348
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004349// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004350// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4351// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004352TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004354 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4355 WINDOW_LOCATION));
4356
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004357 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4358 ASSERT_TRUE(sequenceNum);
4359 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004360 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004361
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004362 mWindow->finishEvent(*sequenceNum);
4363 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4364 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004365 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004366 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004367}
4368
4369// Send a key to the app and have the app not respond right away.
4370TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4371 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004373 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4374 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004375 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004376 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004377 ASSERT_TRUE(mDispatcher->waitForIdle());
4378}
4379
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004380// We have a focused application, but no focused window
4381TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004382 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4384 mWindow->consumeFocusEvent(false);
4385
4386 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004388 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4389 WINDOW_LOCATION));
4390 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4391 mDispatcher->waitForIdle();
4392 mFakePolicy->assertNotifyAnrWasNotCalled();
4393
4394 // Once a focused event arrives, we get an ANR for this application
4395 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4396 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004397 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004398 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004399 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004400 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004401 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004402 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004403 ASSERT_TRUE(mDispatcher->waitForIdle());
4404}
4405
4406// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004407// Make sure that we don't notify policy twice about the same ANR.
4408TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004409 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004410 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4411 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004412
4413 // Once a focused event arrives, we get an ANR for this application
4414 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4415 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004417 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004418 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004420 const std::chrono::duration appTimeout =
4421 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004422 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004423
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004424 std::this_thread::sleep_for(appTimeout);
4425 // ANR should not be raised again. It is up to policy to do that if it desires.
4426 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004427
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004428 // If we now get a focused window, the ANR should stop, but the policy handles that via
4429 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004430 ASSERT_TRUE(mDispatcher->waitForIdle());
4431}
4432
4433// We have a focused application, but no focused window
4434TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004435 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4437 mWindow->consumeFocusEvent(false);
4438
4439 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004440 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004441 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004442 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4443 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004444
4445 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004446 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004447
4448 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004449 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004450 ASSERT_TRUE(mDispatcher->waitForIdle());
4451 mWindow->assertNoEvents();
4452}
4453
4454/**
4455 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4456 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4457 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4458 * the ANR mechanism should still work.
4459 *
4460 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4461 * DOWN event, while not responding on the second one.
4462 */
4463TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4464 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4465 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4466 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4467 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4468 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004469 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004470
4471 // Now send ACTION_UP, with identical timestamp
4472 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4473 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4474 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4475 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004476 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004477
4478 // We have now sent down and up. Let's consume first event and then ANR on the second.
4479 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4480 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004481 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004482}
4483
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004484// A spy window can receive an ANR
4485TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4486 sp<FakeWindowHandle> spy = addSpyWindow();
4487
4488 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4489 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4490 WINDOW_LOCATION));
4491 mWindow->consumeMotionDown();
4492
4493 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4494 ASSERT_TRUE(sequenceNum);
4495 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004496 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004497
4498 spy->finishEvent(*sequenceNum);
4499 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4500 0 /*flags*/);
4501 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004502 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004503}
4504
4505// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004506// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004507TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4508 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004509
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4511 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004512 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004514
4515 // Stuck on the ACTION_UP
4516 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004517 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004518
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004519 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004520 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004521 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4522 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004523
4524 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4525 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004526 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004527 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004528 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004529}
4530
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004531// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004532// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004533TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4534 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004535
4536 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->consumeMotionDown();
4541 // Stuck on the ACTION_UP
4542 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004543 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004544
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004545 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004547 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4548 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549
4550 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4551 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004552 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004553 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004554 spy->assertNoEvents();
4555}
4556
4557TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4558 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4559
4560 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4561
4562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4563 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4564 WINDOW_LOCATION));
4565
4566 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4567 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4568 ASSERT_TRUE(consumeSeq);
4569
Prabir Pradhanedd96402022-02-15 01:46:16 -08004570 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004571
4572 monitor.finishEvent(*consumeSeq);
4573 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4574
4575 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004576 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004577}
4578
4579// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4580// process events, you don't get an anr. When the window later becomes unresponsive again, you
4581// get an ANR again.
4582// 1. tap -> block on ACTION_UP -> receive ANR
4583// 2. consume all pending events (= queue becomes healthy again)
4584// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4585TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4586 tapOnWindow();
4587
4588 mWindow->consumeMotionDown();
4589 // Block on ACTION_UP
4590 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004591 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004592 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4593 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004594 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004595 mWindow->assertNoEvents();
4596
4597 tapOnWindow();
4598 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004599 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004600 mWindow->consumeMotionUp();
4601
4602 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004603 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004604 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004605 mWindow->assertNoEvents();
4606}
4607
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004608// If a connection remains unresponsive for a while, make sure policy is only notified once about
4609// it.
4610TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4613 WINDOW_LOCATION));
4614
4615 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004616 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004618 // 'notifyConnectionUnresponsive' should only be called once per connection
4619 mFakePolicy->assertNotifyAnrWasNotCalled();
4620 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621 mWindow->consumeMotionDown();
4622 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4623 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4624 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004625 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004626 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004627 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628}
4629
4630/**
4631 * If a window is processing a motion event, and then a key event comes in, the key event should
4632 * not to to the focused window until the motion is processed.
4633 *
4634 * Warning!!!
4635 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4636 * and the injection timeout that we specify when injecting the key.
4637 * We must have the injection timeout (10ms) be smaller than
4638 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4639 *
4640 * If that value changes, this test should also change.
4641 */
4642TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4643 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4645
4646 tapOnWindow();
4647 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4648 ASSERT_TRUE(downSequenceNum);
4649 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4650 ASSERT_TRUE(upSequenceNum);
4651 // Don't finish the events yet, and send a key
4652 // Injection will "succeed" because we will eventually give up and send the key to the focused
4653 // window even if motions are still being processed. But because the injection timeout is short,
4654 // we will receive INJECTION_TIMED_OUT as the result.
4655
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004656 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004657 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004658 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4659 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660 // Key will not be sent to the window, yet, because the window is still processing events
4661 // and the key remains pending, waiting for the touch events to be processed
4662 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4663 ASSERT_FALSE(keySequenceNum);
4664
4665 std::this_thread::sleep_for(500ms);
4666 // if we wait long enough though, dispatcher will give up, and still send the key
4667 // to the focused window, even though we have not yet finished the motion event
4668 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4669 mWindow->finishEvent(*downSequenceNum);
4670 mWindow->finishEvent(*upSequenceNum);
4671}
4672
4673/**
4674 * If a window is processing a motion event, and then a key event comes in, the key event should
4675 * not go to the focused window until the motion is processed.
4676 * If then a new motion comes in, then the pending key event should be going to the currently
4677 * focused window right away.
4678 */
4679TEST_F(InputDispatcherSingleWindowAnr,
4680 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4681 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4683
4684 tapOnWindow();
4685 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4686 ASSERT_TRUE(downSequenceNum);
4687 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4688 ASSERT_TRUE(upSequenceNum);
4689 // Don't finish the events yet, and send a key
4690 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004691 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004693 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004694 // At this point, key is still pending, and should not be sent to the application yet.
4695 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4696 ASSERT_FALSE(keySequenceNum);
4697
4698 // Now tap down again. It should cause the pending key to go to the focused window right away.
4699 tapOnWindow();
4700 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4701 // the other events yet. We can finish events in any order.
4702 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4703 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4704 mWindow->consumeMotionDown();
4705 mWindow->consumeMotionUp();
4706 mWindow->assertNoEvents();
4707}
4708
4709class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4710 virtual void SetUp() override {
4711 InputDispatcherTest::SetUp();
4712
Chris Yea209fde2020-07-22 13:54:51 -07004713 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004714 mApplication->setDispatchingTimeout(10ms);
4715 mUnfocusedWindow =
4716 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4717 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004718 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004719 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004720
4721 mFocusedWindow =
4722 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004723 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004724 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004725
4726 // Set focused application.
4727 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004728 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004729
4730 // Expect one focus window exist in display.
4731 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004732 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004733 mFocusedWindow->consumeFocusEvent(true);
4734 }
4735
4736 virtual void TearDown() override {
4737 InputDispatcherTest::TearDown();
4738
4739 mUnfocusedWindow.clear();
4740 mFocusedWindow.clear();
4741 }
4742
4743protected:
Chris Yea209fde2020-07-22 13:54:51 -07004744 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745 sp<FakeWindowHandle> mUnfocusedWindow;
4746 sp<FakeWindowHandle> mFocusedWindow;
4747 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4748 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4749 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4750
4751 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4752
4753 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4754
4755private:
4756 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004757 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004758 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4759 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004760 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004761 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4762 location));
4763 }
4764};
4765
4766// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4767// should be ANR'd first.
4768TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004769 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4771 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004772 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004773 mFocusedWindow->consumeMotionDown();
4774 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4775 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4776 // We consumed all events, so no ANR
4777 ASSERT_TRUE(mDispatcher->waitForIdle());
4778 mFakePolicy->assertNotifyAnrWasNotCalled();
4779
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4782 FOCUSED_WINDOW_LOCATION));
4783 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4784 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004785
4786 const std::chrono::duration timeout =
4787 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004788 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004789 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4790 // sequence to make it consistent
4791 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004792 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004793 mFocusedWindow->consumeMotionDown();
4794 // This cancel is generated because the connection was unresponsive
4795 mFocusedWindow->consumeMotionCancel();
4796 mFocusedWindow->assertNoEvents();
4797 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004799 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4800 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004801 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802}
4803
4804// If we have 2 windows with identical timeouts that are both unresponsive,
4805// it doesn't matter which order they should have ANR.
4806// But we should receive ANR for both.
4807TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4808 // Set the timeout for unfocused window to match the focused window
4809 mUnfocusedWindow->setDispatchingTimeout(10ms);
4810 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4811
4812 tapOnFocusedWindow();
4813 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08004814 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
4815 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
4816 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817
4818 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004819 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4820 mFocusedWindow->getToken() == anrConnectionToken2);
4821 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4822 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004823
4824 ASSERT_TRUE(mDispatcher->waitForIdle());
4825 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004826
4827 mFocusedWindow->consumeMotionDown();
4828 mFocusedWindow->consumeMotionUp();
4829 mUnfocusedWindow->consumeMotionOutside();
4830
Prabir Pradhanedd96402022-02-15 01:46:16 -08004831 sp<IBinder> responsiveToken1, responsiveToken2;
4832 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
4833 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004834
4835 // Both applications should be marked as responsive, in any order
4836 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4837 mFocusedWindow->getToken() == responsiveToken2);
4838 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4839 mUnfocusedWindow->getToken() == responsiveToken2);
4840 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841}
4842
4843// If a window is already not responding, the second tap on the same window should be ignored.
4844// We should also log an error to account for the dropped event (not tested here).
4845// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4846TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4847 tapOnFocusedWindow();
4848 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4849 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4850 // Receive the events, but don't respond
4851 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4852 ASSERT_TRUE(downEventSequenceNum);
4853 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4854 ASSERT_TRUE(upEventSequenceNum);
4855 const std::chrono::duration timeout =
4856 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004857 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004858
4859 // Tap once again
4860 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004861 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004862 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4863 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004864 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004865 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4866 FOCUSED_WINDOW_LOCATION));
4867 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4868 // valid touch target
4869 mUnfocusedWindow->assertNoEvents();
4870
4871 // Consume the first tap
4872 mFocusedWindow->finishEvent(*downEventSequenceNum);
4873 mFocusedWindow->finishEvent(*upEventSequenceNum);
4874 ASSERT_TRUE(mDispatcher->waitForIdle());
4875 // The second tap did not go to the focused window
4876 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004877 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08004878 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4879 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004880 mFakePolicy->assertNotifyAnrWasNotCalled();
4881}
4882
4883// If you tap outside of all windows, there will not be ANR
4884TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004885 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004886 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4887 LOCATION_OUTSIDE_ALL_WINDOWS));
4888 ASSERT_TRUE(mDispatcher->waitForIdle());
4889 mFakePolicy->assertNotifyAnrWasNotCalled();
4890}
4891
4892// Since the focused window is paused, tapping on it should not produce any events
4893TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4894 mFocusedWindow->setPaused(true);
4895 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4896
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004897 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004898 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4899 FOCUSED_WINDOW_LOCATION));
4900
4901 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4902 ASSERT_TRUE(mDispatcher->waitForIdle());
4903 // Should not ANR because the window is paused, and touches shouldn't go to it
4904 mFakePolicy->assertNotifyAnrWasNotCalled();
4905
4906 mFocusedWindow->assertNoEvents();
4907 mUnfocusedWindow->assertNoEvents();
4908}
4909
4910/**
4911 * If a window is processing a motion event, and then a key event comes in, the key event should
4912 * not to to the focused window until the motion is processed.
4913 * If a different window becomes focused at this time, the key should go to that window instead.
4914 *
4915 * Warning!!!
4916 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4917 * and the injection timeout that we specify when injecting the key.
4918 * We must have the injection timeout (10ms) be smaller than
4919 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4920 *
4921 * If that value changes, this test should also change.
4922 */
4923TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4924 // Set a long ANR timeout to prevent it from triggering
4925 mFocusedWindow->setDispatchingTimeout(2s);
4926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4927
4928 tapOnUnfocusedWindow();
4929 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4930 ASSERT_TRUE(downSequenceNum);
4931 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4932 ASSERT_TRUE(upSequenceNum);
4933 // Don't finish the events yet, and send a key
4934 // Injection will succeed because we will eventually give up and send the key to the focused
4935 // window even if motions are still being processed.
4936
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004937 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004938 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004939 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941 // Key will not be sent to the window, yet, because the window is still processing events
4942 // and the key remains pending, waiting for the touch events to be processed
4943 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4944 ASSERT_FALSE(keySequenceNum);
4945
4946 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004947 mFocusedWindow->setFocusable(false);
4948 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004950 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004951
4952 // Focus events should precede the key events
4953 mUnfocusedWindow->consumeFocusEvent(true);
4954 mFocusedWindow->consumeFocusEvent(false);
4955
4956 // Finish the tap events, which should unblock dispatcher
4957 mUnfocusedWindow->finishEvent(*downSequenceNum);
4958 mUnfocusedWindow->finishEvent(*upSequenceNum);
4959
4960 // Now that all queues are cleared and no backlog in the connections, the key event
4961 // can finally go to the newly focused "mUnfocusedWindow".
4962 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4963 mFocusedWindow->assertNoEvents();
4964 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004965 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004966}
4967
4968// When the touch stream is split across 2 windows, and one of them does not respond,
4969// then ANR should be raised and the touch should be canceled for the unresponsive window.
4970// The other window should not be affected by that.
4971TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4972 // Touch Window 1
4973 NotifyMotionArgs motionArgs =
4974 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4975 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4976 mDispatcher->notifyMotion(&motionArgs);
4977 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4978 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4979
4980 // Touch Window 2
4981 int32_t actionPointerDown =
4982 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4983
4984 motionArgs =
4985 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4986 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4987 mDispatcher->notifyMotion(&motionArgs);
4988
4989 const std::chrono::duration timeout =
4990 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004991 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004992
4993 mUnfocusedWindow->consumeMotionDown();
4994 mFocusedWindow->consumeMotionDown();
4995 // Focused window may or may not receive ACTION_MOVE
4996 // But it should definitely receive ACTION_CANCEL due to the ANR
4997 InputEvent* event;
4998 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4999 ASSERT_TRUE(moveOrCancelSequenceNum);
5000 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5001 ASSERT_NE(nullptr, event);
5002 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5003 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5004 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5005 mFocusedWindow->consumeMotionCancel();
5006 } else {
5007 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5008 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005009 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005010 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5011 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005012
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005013 mUnfocusedWindow->assertNoEvents();
5014 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005015 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005016}
5017
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005018/**
5019 * If we have no focused window, and a key comes in, we start the ANR timer.
5020 * The focused application should add a focused window before the timer runs out to prevent ANR.
5021 *
5022 * If the user touches another application during this time, the key should be dropped.
5023 * Next, if a new focused window comes in, without toggling the focused application,
5024 * then no ANR should occur.
5025 *
5026 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5027 * but in some cases the policy may not update the focused application.
5028 */
5029TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5030 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5031 std::make_shared<FakeApplicationHandle>();
5032 focusedApplication->setDispatchingTimeout(60ms);
5033 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5034 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5035 mFocusedWindow->setFocusable(false);
5036
5037 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5038 mFocusedWindow->consumeFocusEvent(false);
5039
5040 // Send a key. The ANR timer should start because there is no focused window.
5041 // 'focusedApplication' will get blamed if this timer completes.
5042 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005043 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005044 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005045 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5046 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005048
5049 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5050 // then the injected touches won't cause the focused event to get dropped.
5051 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5052 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5053 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5054 // For this test, it means that the key would get delivered to the window once it becomes
5055 // focused.
5056 std::this_thread::sleep_for(10ms);
5057
5058 // Touch unfocused window. This should force the pending key to get dropped.
5059 NotifyMotionArgs motionArgs =
5060 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5061 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5062 mDispatcher->notifyMotion(&motionArgs);
5063
5064 // We do not consume the motion right away, because that would require dispatcher to first
5065 // process (== drop) the key event, and by that time, ANR will be raised.
5066 // Set the focused window first.
5067 mFocusedWindow->setFocusable(true);
5068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5069 setFocusedWindow(mFocusedWindow);
5070 mFocusedWindow->consumeFocusEvent(true);
5071 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5072 // to another application. This could be a bug / behaviour in the policy.
5073
5074 mUnfocusedWindow->consumeMotionDown();
5075
5076 ASSERT_TRUE(mDispatcher->waitForIdle());
5077 // Should not ANR because we actually have a focused window. It was just added too slowly.
5078 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5079}
5080
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005081// These tests ensure we cannot send touch events to a window that's positioned behind a window
5082// that has feature NO_INPUT_CHANNEL.
5083// Layout:
5084// Top (closest to user)
5085// mNoInputWindow (above all windows)
5086// mBottomWindow
5087// Bottom (furthest from user)
5088class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5089 virtual void SetUp() override {
5090 InputDispatcherTest::SetUp();
5091
5092 mApplication = std::make_shared<FakeApplicationHandle>();
5093 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5094 "Window without input channel", ADISPLAY_ID_DEFAULT,
5095 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5096
chaviw3277faf2021-05-19 16:45:23 -05005097 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005098 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5099 // It's perfectly valid for this window to not have an associated input channel
5100
5101 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5102 ADISPLAY_ID_DEFAULT);
5103 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5104
5105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5106 }
5107
5108protected:
5109 std::shared_ptr<FakeApplicationHandle> mApplication;
5110 sp<FakeWindowHandle> mNoInputWindow;
5111 sp<FakeWindowHandle> mBottomWindow;
5112};
5113
5114TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5115 PointF touchedPoint = {10, 10};
5116
5117 NotifyMotionArgs motionArgs =
5118 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5119 ADISPLAY_ID_DEFAULT, {touchedPoint});
5120 mDispatcher->notifyMotion(&motionArgs);
5121
5122 mNoInputWindow->assertNoEvents();
5123 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5124 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5125 // and therefore should prevent mBottomWindow from receiving touches
5126 mBottomWindow->assertNoEvents();
5127}
5128
5129/**
5130 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5131 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5132 */
5133TEST_F(InputDispatcherMultiWindowOcclusionTests,
5134 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5135 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5136 "Window with input channel and NO_INPUT_CHANNEL",
5137 ADISPLAY_ID_DEFAULT);
5138
chaviw3277faf2021-05-19 16:45:23 -05005139 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005140 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5142
5143 PointF touchedPoint = {10, 10};
5144
5145 NotifyMotionArgs motionArgs =
5146 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5147 ADISPLAY_ID_DEFAULT, {touchedPoint});
5148 mDispatcher->notifyMotion(&motionArgs);
5149
5150 mNoInputWindow->assertNoEvents();
5151 mBottomWindow->assertNoEvents();
5152}
5153
Vishnu Nair958da932020-08-21 17:12:37 -07005154class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5155protected:
5156 std::shared_ptr<FakeApplicationHandle> mApp;
5157 sp<FakeWindowHandle> mWindow;
5158 sp<FakeWindowHandle> mMirror;
5159
5160 virtual void SetUp() override {
5161 InputDispatcherTest::SetUp();
5162 mApp = std::make_shared<FakeApplicationHandle>();
5163 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5164 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5165 mWindow->getToken());
5166 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5167 mWindow->setFocusable(true);
5168 mMirror->setFocusable(true);
5169 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5170 }
5171};
5172
5173TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5174 // Request focus on a mirrored window
5175 setFocusedWindow(mMirror);
5176
5177 // window gets focused
5178 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005179 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5180 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005181 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5182}
5183
5184// A focused & mirrored window remains focused only if the window and its mirror are both
5185// focusable.
5186TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5187 setFocusedWindow(mMirror);
5188
5189 // window gets focused
5190 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005191 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5192 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005193 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5195 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005196 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5197
5198 mMirror->setFocusable(false);
5199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5200
5201 // window loses focus since one of the windows associated with the token in not focusable
5202 mWindow->consumeFocusEvent(false);
5203
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005204 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5205 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005206 mWindow->assertNoEvents();
5207}
5208
5209// A focused & mirrored window remains focused until the window and its mirror both become
5210// invisible.
5211TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5212 setFocusedWindow(mMirror);
5213
5214 // window gets focused
5215 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005216 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5217 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005218 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005219 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5220 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005221 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5222
5223 mMirror->setVisible(false);
5224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5225
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5227 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005228 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005229 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5230 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005231 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5232
5233 mWindow->setVisible(false);
5234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5235
5236 // window loses focus only after all windows associated with the token become invisible.
5237 mWindow->consumeFocusEvent(false);
5238
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005239 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5240 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005241 mWindow->assertNoEvents();
5242}
5243
5244// A focused & mirrored window remains focused until both windows are removed.
5245TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5246 setFocusedWindow(mMirror);
5247
5248 // window gets focused
5249 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005250 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5251 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005252 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005253 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5254 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005255 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5256
5257 // single window is removed but the window token remains focused
5258 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5259
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5261 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005262 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005263 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5264 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005265 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5266
5267 // Both windows are removed
5268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5269 mWindow->consumeFocusEvent(false);
5270
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005271 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5272 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005273 mWindow->assertNoEvents();
5274}
5275
5276// Focus request can be pending until one window becomes visible.
5277TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5278 // Request focus on an invisible mirror.
5279 mWindow->setVisible(false);
5280 mMirror->setVisible(false);
5281 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5282 setFocusedWindow(mMirror);
5283
5284 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005285 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005286 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005287 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005288
5289 mMirror->setVisible(true);
5290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5291
5292 // window gets focused
5293 mWindow->consumeFocusEvent(true);
5294 // window gets the pending key event
5295 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5296}
Prabir Pradhan99987712020-11-10 18:43:05 -08005297
5298class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5299protected:
5300 std::shared_ptr<FakeApplicationHandle> mApp;
5301 sp<FakeWindowHandle> mWindow;
5302 sp<FakeWindowHandle> mSecondWindow;
5303
5304 void SetUp() override {
5305 InputDispatcherTest::SetUp();
5306 mApp = std::make_shared<FakeApplicationHandle>();
5307 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5308 mWindow->setFocusable(true);
5309 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5310 mSecondWindow->setFocusable(true);
5311
5312 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5313 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5314
5315 setFocusedWindow(mWindow);
5316 mWindow->consumeFocusEvent(true);
5317 }
5318
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005319 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5320 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005321 mDispatcher->notifyPointerCaptureChanged(&args);
5322 }
5323
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005324 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5325 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005326 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005327 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5328 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005329 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005330 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005331 }
5332};
5333
5334TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5335 // Ensure that capture cannot be obtained for unfocused windows.
5336 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5337 mFakePolicy->assertSetPointerCaptureNotCalled();
5338 mSecondWindow->assertNoEvents();
5339
5340 // Ensure that capture can be enabled from the focus window.
5341 requestAndVerifyPointerCapture(mWindow, true);
5342
5343 // Ensure that capture cannot be disabled from a window that does not have capture.
5344 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5345 mFakePolicy->assertSetPointerCaptureNotCalled();
5346
5347 // Ensure that capture can be disabled from the window with capture.
5348 requestAndVerifyPointerCapture(mWindow, false);
5349}
5350
5351TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005352 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005353
5354 setFocusedWindow(mSecondWindow);
5355
5356 // Ensure that the capture disabled event was sent first.
5357 mWindow->consumeCaptureEvent(false);
5358 mWindow->consumeFocusEvent(false);
5359 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005360 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005361
5362 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005363 notifyPointerCaptureChanged({});
5364 notifyPointerCaptureChanged(request);
5365 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005366 mWindow->assertNoEvents();
5367 mSecondWindow->assertNoEvents();
5368 mFakePolicy->assertSetPointerCaptureNotCalled();
5369}
5370
5371TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005372 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005373
5374 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005375 notifyPointerCaptureChanged({});
5376 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005377
5378 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005379 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005380 mWindow->consumeCaptureEvent(false);
5381 mWindow->assertNoEvents();
5382}
5383
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005384TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5385 requestAndVerifyPointerCapture(mWindow, true);
5386
5387 // The first window loses focus.
5388 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005389 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005390 mWindow->consumeCaptureEvent(false);
5391
5392 // Request Pointer Capture from the second window before the notification from InputReader
5393 // arrives.
5394 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005395 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005396
5397 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005398 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005399
5400 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005401 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005402
5403 mSecondWindow->consumeFocusEvent(true);
5404 mSecondWindow->consumeCaptureEvent(true);
5405}
5406
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005407TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5408 // App repeatedly enables and disables capture.
5409 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5410 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5411 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5412 mFakePolicy->assertSetPointerCaptureCalled(false);
5413 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5414 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5415
5416 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5417 // first request is now stale, this should do nothing.
5418 notifyPointerCaptureChanged(firstRequest);
5419 mWindow->assertNoEvents();
5420
5421 // InputReader notifies that the second request was enabled.
5422 notifyPointerCaptureChanged(secondRequest);
5423 mWindow->consumeCaptureEvent(true);
5424}
5425
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005426class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5427protected:
5428 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005429
5430 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5431 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5432
5433 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5434 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5435
5436 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5437 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5438 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5439 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5440 MAXIMUM_OBSCURING_OPACITY);
5441
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005442 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005443 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005444 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005445
5446 sp<FakeWindowHandle> mTouchWindow;
5447
5448 virtual void SetUp() override {
5449 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005450 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005451 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5452 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5453 }
5454
5455 virtual void TearDown() override {
5456 InputDispatcherTest::TearDown();
5457 mTouchWindow.clear();
5458 }
5459
chaviw3277faf2021-05-19 16:45:23 -05005460 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5461 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005462 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005463 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005464 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005465 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005466 return window;
5467 }
5468
5469 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5470 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5471 sp<FakeWindowHandle> window =
5472 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5473 // Generate an arbitrary PID based on the UID
5474 window->setOwnerInfo(1777 + (uid % 10000), uid);
5475 return window;
5476 }
5477
5478 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5479 NotifyMotionArgs args =
5480 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5481 ADISPLAY_ID_DEFAULT, points);
5482 mDispatcher->notifyMotion(&args);
5483 }
5484};
5485
5486TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005487 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005488 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005489 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005490
5491 touch();
5492
5493 mTouchWindow->assertNoEvents();
5494}
5495
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005496TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005497 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5498 const sp<FakeWindowHandle>& w =
5499 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5500 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5501
5502 touch();
5503
5504 mTouchWindow->assertNoEvents();
5505}
5506
5507TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005508 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5509 const sp<FakeWindowHandle>& w =
5510 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5511 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5512
5513 touch();
5514
5515 w->assertNoEvents();
5516}
5517
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005518TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005519 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005521
5522 touch();
5523
5524 mTouchWindow->consumeAnyMotionDown();
5525}
5526
5527TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005528 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005529 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005530 w->setFrame(Rect(0, 0, 50, 50));
5531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005532
5533 touch({PointF{100, 100}});
5534
5535 mTouchWindow->consumeAnyMotionDown();
5536}
5537
5538TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005539 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005540 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5542
5543 touch();
5544
5545 mTouchWindow->consumeAnyMotionDown();
5546}
5547
5548TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5549 const sp<FakeWindowHandle>& w =
5550 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005552
5553 touch();
5554
5555 mTouchWindow->consumeAnyMotionDown();
5556}
5557
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005558TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5559 const sp<FakeWindowHandle>& w =
5560 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5561 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5562
5563 touch();
5564
5565 w->assertNoEvents();
5566}
5567
5568/**
5569 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5570 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5571 * window, the occluding window will still receive ACTION_OUTSIDE event.
5572 */
5573TEST_F(InputDispatcherUntrustedTouchesTest,
5574 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5575 const sp<FakeWindowHandle>& w =
5576 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005577 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5579
5580 touch();
5581
5582 w->consumeMotionOutside();
5583}
5584
5585TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5586 const sp<FakeWindowHandle>& w =
5587 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005588 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5590
5591 touch();
5592
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005593 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005594}
5595
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005596TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005597 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005598 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5599 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5601
5602 touch();
5603
5604 mTouchWindow->consumeAnyMotionDown();
5605}
5606
5607TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5608 const sp<FakeWindowHandle>& w =
5609 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5610 MAXIMUM_OBSCURING_OPACITY);
5611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005612
5613 touch();
5614
5615 mTouchWindow->consumeAnyMotionDown();
5616}
5617
5618TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005619 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005620 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5621 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005622 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5623
5624 touch();
5625
5626 mTouchWindow->assertNoEvents();
5627}
5628
5629TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5630 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5631 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005632 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5633 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005634 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005635 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5636 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5638
5639 touch();
5640
5641 mTouchWindow->assertNoEvents();
5642}
5643
5644TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5645 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5646 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005647 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5648 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005649 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005650 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5651 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005652 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5653
5654 touch();
5655
5656 mTouchWindow->consumeAnyMotionDown();
5657}
5658
5659TEST_F(InputDispatcherUntrustedTouchesTest,
5660 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5661 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005662 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5663 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005664 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005665 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5666 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5668
5669 touch();
5670
5671 mTouchWindow->consumeAnyMotionDown();
5672}
5673
5674TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5675 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005676 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5677 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005678 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005679 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5680 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005682
5683 touch();
5684
5685 mTouchWindow->assertNoEvents();
5686}
5687
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005688TEST_F(InputDispatcherUntrustedTouchesTest,
5689 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5690 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005691 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5692 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005693 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005694 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5695 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5697
5698 touch();
5699
5700 mTouchWindow->assertNoEvents();
5701}
5702
5703TEST_F(InputDispatcherUntrustedTouchesTest,
5704 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5705 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005706 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5707 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005708 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005709 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5710 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5712
5713 touch();
5714
5715 mTouchWindow->consumeAnyMotionDown();
5716}
5717
5718TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5719 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005720 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5721 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5723
5724 touch();
5725
5726 mTouchWindow->consumeAnyMotionDown();
5727}
5728
5729TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5730 const sp<FakeWindowHandle>& w =
5731 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5733
5734 touch();
5735
5736 mTouchWindow->consumeAnyMotionDown();
5737}
5738
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005739TEST_F(InputDispatcherUntrustedTouchesTest,
5740 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5741 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5742 const sp<FakeWindowHandle>& w =
5743 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5744 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5745
5746 touch();
5747
5748 mTouchWindow->assertNoEvents();
5749}
5750
5751TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5752 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5753 const sp<FakeWindowHandle>& w =
5754 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5756
5757 touch();
5758
5759 mTouchWindow->consumeAnyMotionDown();
5760}
5761
5762TEST_F(InputDispatcherUntrustedTouchesTest,
5763 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5764 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5765 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005766 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5767 OPACITY_ABOVE_THRESHOLD);
5768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5769
5770 touch();
5771
5772 mTouchWindow->consumeAnyMotionDown();
5773}
5774
5775TEST_F(InputDispatcherUntrustedTouchesTest,
5776 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5777 const sp<FakeWindowHandle>& w1 =
5778 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5779 OPACITY_BELOW_THRESHOLD);
5780 const sp<FakeWindowHandle>& w2 =
5781 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5782 OPACITY_BELOW_THRESHOLD);
5783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5784
5785 touch();
5786
5787 mTouchWindow->assertNoEvents();
5788}
5789
5790/**
5791 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5792 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5793 * (which alone would result in allowing touches) does not affect the blocking behavior.
5794 */
5795TEST_F(InputDispatcherUntrustedTouchesTest,
5796 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5797 const sp<FakeWindowHandle>& wB =
5798 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5799 OPACITY_BELOW_THRESHOLD);
5800 const sp<FakeWindowHandle>& wC =
5801 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5802 OPACITY_BELOW_THRESHOLD);
5803 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5804
5805 touch();
5806
5807 mTouchWindow->assertNoEvents();
5808}
5809
5810/**
5811 * This test is testing that a window from a different UID but with same application token doesn't
5812 * block the touch. Apps can share the application token for close UI collaboration for example.
5813 */
5814TEST_F(InputDispatcherUntrustedTouchesTest,
5815 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5816 const sp<FakeWindowHandle>& w =
5817 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5818 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5820
5821 touch();
5822
5823 mTouchWindow->consumeAnyMotionDown();
5824}
5825
arthurhungb89ccb02020-12-30 16:19:01 +08005826class InputDispatcherDragTests : public InputDispatcherTest {
5827protected:
5828 std::shared_ptr<FakeApplicationHandle> mApp;
5829 sp<FakeWindowHandle> mWindow;
5830 sp<FakeWindowHandle> mSecondWindow;
5831 sp<FakeWindowHandle> mDragWindow;
5832
5833 void SetUp() override {
5834 InputDispatcherTest::SetUp();
5835 mApp = std::make_shared<FakeApplicationHandle>();
5836 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5837 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005838
5839 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5840 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005841
5842 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5844 }
5845
5846 // Start performing drag, we will create a drag window and transfer touch to it.
5847 void performDrag() {
5848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5849 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5850 {50, 50}))
5851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5852
5853 // Window should receive motion event.
5854 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5855
5856 // The drag window covers the entire display
5857 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5858 mDispatcher->setInputWindows(
5859 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5860
5861 // Transfer touch focus to the drag window
5862 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5863 true /* isDragDrop */);
5864 mWindow->consumeMotionCancel();
5865 mDragWindow->consumeMotionDown();
5866 }
arthurhung6d4bed92021-03-17 11:59:33 +08005867
5868 // Start performing drag, we will create a drag window and transfer touch to it.
5869 void performStylusDrag() {
5870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5871 injectMotionEvent(mDispatcher,
5872 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5873 AINPUT_SOURCE_STYLUS)
5874 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5875 .pointer(PointerBuilder(0,
5876 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5877 .x(50)
5878 .y(50))
5879 .build()));
5880 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5881
5882 // The drag window covers the entire display
5883 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5884 mDispatcher->setInputWindows(
5885 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5886
5887 // Transfer touch focus to the drag window
5888 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5889 true /* isDragDrop */);
5890 mWindow->consumeMotionCancel();
5891 mDragWindow->consumeMotionDown();
5892 }
arthurhungb89ccb02020-12-30 16:19:01 +08005893};
5894
5895TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5896 performDrag();
5897
5898 // Move on window.
5899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5900 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5901 ADISPLAY_ID_DEFAULT, {50, 50}))
5902 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5903 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5904 mWindow->consumeDragEvent(false, 50, 50);
5905 mSecondWindow->assertNoEvents();
5906
5907 // Move to another window.
5908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5909 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5910 ADISPLAY_ID_DEFAULT, {150, 50}))
5911 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5912 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5913 mWindow->consumeDragEvent(true, 150, 50);
5914 mSecondWindow->consumeDragEvent(false, 50, 50);
5915
5916 // Move back to original window.
5917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5918 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5919 ADISPLAY_ID_DEFAULT, {50, 50}))
5920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5921 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5922 mWindow->consumeDragEvent(false, 50, 50);
5923 mSecondWindow->consumeDragEvent(true, -50, 50);
5924
5925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5926 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5927 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5928 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5929 mWindow->assertNoEvents();
5930 mSecondWindow->assertNoEvents();
5931}
5932
arthurhungf452d0b2021-01-06 00:19:52 +08005933TEST_F(InputDispatcherDragTests, DragAndDrop) {
5934 performDrag();
5935
5936 // Move on window.
5937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5938 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5939 ADISPLAY_ID_DEFAULT, {50, 50}))
5940 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5941 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5942 mWindow->consumeDragEvent(false, 50, 50);
5943 mSecondWindow->assertNoEvents();
5944
5945 // Move to another window.
5946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5947 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5948 ADISPLAY_ID_DEFAULT, {150, 50}))
5949 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5950 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5951 mWindow->consumeDragEvent(true, 150, 50);
5952 mSecondWindow->consumeDragEvent(false, 50, 50);
5953
5954 // drop to another window.
5955 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5956 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5957 {150, 50}))
5958 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5959 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5960 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5961 mWindow->assertNoEvents();
5962 mSecondWindow->assertNoEvents();
5963}
5964
arthurhung6d4bed92021-03-17 11:59:33 +08005965TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5966 performStylusDrag();
5967
5968 // Move on window and keep button pressed.
5969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5970 injectMotionEvent(mDispatcher,
5971 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5972 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5973 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5974 .x(50)
5975 .y(50))
5976 .build()))
5977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5978 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5979 mWindow->consumeDragEvent(false, 50, 50);
5980 mSecondWindow->assertNoEvents();
5981
5982 // Move to another window and release button, expect to drop item.
5983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5984 injectMotionEvent(mDispatcher,
5985 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5986 .buttonState(0)
5987 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5988 .x(150)
5989 .y(50))
5990 .build()))
5991 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5992 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5993 mWindow->assertNoEvents();
5994 mSecondWindow->assertNoEvents();
5995 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5996
5997 // nothing to the window.
5998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5999 injectMotionEvent(mDispatcher,
6000 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6001 .buttonState(0)
6002 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6003 .x(150)
6004 .y(50))
6005 .build()))
6006 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6007 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6008 mWindow->assertNoEvents();
6009 mSecondWindow->assertNoEvents();
6010}
6011
Arthur Hung6d0571e2021-04-09 20:18:16 +08006012TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6013 performDrag();
6014
6015 // Set second window invisible.
6016 mSecondWindow->setVisible(false);
6017 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6018
6019 // Move on window.
6020 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6021 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6022 ADISPLAY_ID_DEFAULT, {50, 50}))
6023 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6024 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6025 mWindow->consumeDragEvent(false, 50, 50);
6026 mSecondWindow->assertNoEvents();
6027
6028 // Move to another window.
6029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6030 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6031 ADISPLAY_ID_DEFAULT, {150, 50}))
6032 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6033 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6034 mWindow->consumeDragEvent(true, 150, 50);
6035 mSecondWindow->assertNoEvents();
6036
6037 // drop to another window.
6038 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6039 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6040 {150, 50}))
6041 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6042 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6043 mFakePolicy->assertDropTargetEquals(nullptr);
6044 mWindow->assertNoEvents();
6045 mSecondWindow->assertNoEvents();
6046}
6047
Vishnu Nair062a8672021-09-03 16:07:44 -07006048class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6049
6050TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6051 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6052 sp<FakeWindowHandle> window =
6053 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6054 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6055 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6056 window->setFocusable(true);
6057 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6058 setFocusedWindow(window);
6059 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6060
6061 // With the flag set, window should not get any input
6062 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6063 mDispatcher->notifyKey(&keyArgs);
6064 window->assertNoEvents();
6065
6066 NotifyMotionArgs motionArgs =
6067 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6068 ADISPLAY_ID_DEFAULT);
6069 mDispatcher->notifyMotion(&motionArgs);
6070 window->assertNoEvents();
6071
6072 // With the flag cleared, the window should get input
6073 window->setInputFeatures({});
6074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6075
6076 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6077 mDispatcher->notifyKey(&keyArgs);
6078 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6079
6080 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6081 ADISPLAY_ID_DEFAULT);
6082 mDispatcher->notifyMotion(&motionArgs);
6083 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6084 window->assertNoEvents();
6085}
6086
6087TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6088 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6089 std::make_shared<FakeApplicationHandle>();
6090 sp<FakeWindowHandle> obscuringWindow =
6091 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6092 ADISPLAY_ID_DEFAULT);
6093 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6094 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006095 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006096 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6097 sp<FakeWindowHandle> window =
6098 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6099 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6100 window->setOwnerInfo(222, 222);
6101 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6102 window->setFocusable(true);
6103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6104 setFocusedWindow(window);
6105 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6106
6107 // With the flag set, window should not get any input
6108 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6109 mDispatcher->notifyKey(&keyArgs);
6110 window->assertNoEvents();
6111
6112 NotifyMotionArgs motionArgs =
6113 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6114 ADISPLAY_ID_DEFAULT);
6115 mDispatcher->notifyMotion(&motionArgs);
6116 window->assertNoEvents();
6117
6118 // With the flag cleared, the window should get input
6119 window->setInputFeatures({});
6120 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6121
6122 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6123 mDispatcher->notifyKey(&keyArgs);
6124 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6125
6126 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6127 ADISPLAY_ID_DEFAULT);
6128 mDispatcher->notifyMotion(&motionArgs);
6129 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6130 window->assertNoEvents();
6131}
6132
6133TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6134 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6135 std::make_shared<FakeApplicationHandle>();
6136 sp<FakeWindowHandle> obscuringWindow =
6137 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6138 ADISPLAY_ID_DEFAULT);
6139 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6140 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006141 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006142 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6143 sp<FakeWindowHandle> window =
6144 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6145 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6146 window->setOwnerInfo(222, 222);
6147 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6148 window->setFocusable(true);
6149 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6150 setFocusedWindow(window);
6151 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6152
6153 // With the flag set, window should not get any input
6154 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6155 mDispatcher->notifyKey(&keyArgs);
6156 window->assertNoEvents();
6157
6158 NotifyMotionArgs motionArgs =
6159 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6160 ADISPLAY_ID_DEFAULT);
6161 mDispatcher->notifyMotion(&motionArgs);
6162 window->assertNoEvents();
6163
6164 // When the window is no longer obscured because it went on top, it should get input
6165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6166
6167 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6168 mDispatcher->notifyKey(&keyArgs);
6169 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6170
6171 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6172 ADISPLAY_ID_DEFAULT);
6173 mDispatcher->notifyMotion(&motionArgs);
6174 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6175 window->assertNoEvents();
6176}
6177
Antonio Kantekf16f2832021-09-28 04:39:20 +00006178class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6179protected:
6180 std::shared_ptr<FakeApplicationHandle> mApp;
6181 sp<FakeWindowHandle> mWindow;
6182 sp<FakeWindowHandle> mSecondWindow;
6183
6184 void SetUp() override {
6185 InputDispatcherTest::SetUp();
6186
6187 mApp = std::make_shared<FakeApplicationHandle>();
6188 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6189 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006190 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006191 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6192 mSecondWindow->setFocusable(true);
6193
6194 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6195 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006196 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006197
6198 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6199 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6200 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006201 }
6202
Antonio Kantekea47acb2021-12-23 12:41:25 -08006203 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006204 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006205 mWindow->consumeTouchModeEvent(inTouchMode);
6206 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6207 }
6208};
6209
Antonio Kantek26defcf2022-02-08 01:12:27 +00006210TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006211 const WindowInfo& windowInfo = *mWindow->getInfo();
6212 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6213 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006214}
6215
Antonio Kantek26defcf2022-02-08 01:12:27 +00006216TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6217 const WindowInfo& windowInfo = *mWindow->getInfo();
6218 int32_t ownerPid = windowInfo.ownerPid;
6219 int32_t ownerUid = windowInfo.ownerUid;
6220 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6221 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6222 ownerUid, /* hasPermission */ false));
6223 mWindow->assertNoEvents();
6224 mSecondWindow->assertNoEvents();
6225}
6226
6227TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6228 const WindowInfo& windowInfo = *mWindow->getInfo();
6229 int32_t ownerPid = windowInfo.ownerPid;
6230 int32_t ownerUid = windowInfo.ownerUid;
6231 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6232 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6233 /* hasPermission */ true);
6234}
6235
Antonio Kantekf16f2832021-09-28 04:39:20 +00006236TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006237 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006238 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6239 windowInfo.ownerPid, windowInfo.ownerUid,
6240 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006241 mWindow->assertNoEvents();
6242 mSecondWindow->assertNoEvents();
6243}
6244
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006245class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6246public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006247 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006248 std::shared_ptr<FakeApplicationHandle> application =
6249 std::make_shared<FakeApplicationHandle>();
6250 std::string name = "Fake Spy ";
6251 name += std::to_string(mSpyCount++);
6252 sp<FakeWindowHandle> spy =
6253 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6254 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006255 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006256 return spy;
6257 }
6258
6259 sp<FakeWindowHandle> createForeground() {
6260 std::shared_ptr<FakeApplicationHandle> application =
6261 std::make_shared<FakeApplicationHandle>();
6262 sp<FakeWindowHandle> window =
6263 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006264 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006265 return window;
6266 }
6267
6268private:
6269 int mSpyCount{0};
6270};
6271
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006272using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006273/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006274 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6275 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006276TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6277 ScopedSilentDeath _silentDeath;
6278
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006279 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006280 spy->setTrustedOverlay(false);
6281 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6282 ".* not a trusted overlay");
6283}
6284
6285/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006286 * Input injection into a display with a spy window but no foreground windows should succeed.
6287 */
6288TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006289 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6291
6292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6293 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6294 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6295 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6296}
6297
6298/**
6299 * Verify the order in which different input windows receive events. The touched foreground window
6300 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6301 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6302 * receive events before ones belows it.
6303 *
6304 * Here, we set up a scenario with four windows in the following Z order from the top:
6305 * spy1, spy2, window, spy3.
6306 * We then inject an event and verify that the foreground "window" receives it first, followed by
6307 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6308 * window.
6309 */
6310TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6311 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006312 auto spy1 = createSpy();
6313 auto spy2 = createSpy();
6314 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006315 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6316 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6317 const size_t numChannels = channels.size();
6318
Michael Wright8e9a8562022-02-09 13:44:29 +00006319 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006320 if (!epollFd.ok()) {
6321 FAIL() << "Failed to create epoll fd";
6322 }
6323
6324 for (size_t i = 0; i < numChannels; i++) {
6325 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6326 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6327 FAIL() << "Failed to add fd to epoll";
6328 }
6329 }
6330
6331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6332 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6333 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6334
6335 std::vector<size_t> eventOrder;
6336 std::vector<struct epoll_event> events(numChannels);
6337 for (;;) {
6338 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6339 (100ms).count());
6340 if (nFds < 0) {
6341 FAIL() << "Failed to call epoll_wait";
6342 }
6343 if (nFds == 0) {
6344 break; // epoll_wait timed out
6345 }
6346 for (int i = 0; i < nFds; i++) {
6347 ASSERT_EQ(EPOLLIN, events[i].events);
6348 eventOrder.push_back(events[i].data.u64);
6349 channels[i]->consumeMotionDown();
6350 }
6351 }
6352
6353 // Verify the order in which the events were received.
6354 EXPECT_EQ(3u, eventOrder.size());
6355 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6356 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6357 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6358}
6359
6360/**
6361 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6362 */
6363TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6364 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006365 auto spy = createSpy();
6366 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006367 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6368
6369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6370 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6371 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6372 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6373 spy->assertNoEvents();
6374}
6375
6376/**
6377 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6378 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6379 * to the window.
6380 */
6381TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6382 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006383 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006384 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6385 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6386
6387 // Inject an event outside the spy window's touchable region.
6388 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6389 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6390 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6391 window->consumeMotionDown();
6392 spy->assertNoEvents();
6393 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6394 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6395 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6396 window->consumeMotionUp();
6397 spy->assertNoEvents();
6398
6399 // Inject an event inside the spy window's touchable region.
6400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6401 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6402 {5, 10}))
6403 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6404 window->consumeMotionDown();
6405 spy->consumeMotionDown();
6406}
6407
6408/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006409 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006410 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006411 */
6412TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6413 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006414 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006415 auto spy = createSpy();
6416 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006417 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006418 spy->setFrame(Rect{0, 0, 20, 20});
6419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6420
6421 // Inject an event outside the spy window's frame and touchable region.
6422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006423 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6424 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006425 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6426 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006427 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006428}
6429
6430/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006431 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6432 * any other windows - including other spy windows - will also be cancelled.
6433 */
6434TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6435 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006436 auto spy1 = createSpy();
6437 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006438 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6439
6440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6441 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6442 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6443 window->consumeMotionDown();
6444 spy1->consumeMotionDown();
6445 spy2->consumeMotionDown();
6446
6447 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006448 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006449 spy2->assertNoEvents();
6450 spy1->consumeMotionCancel();
6451 window->consumeMotionCancel();
6452
6453 // The rest of the gesture should only be sent to the second spy window.
6454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6455 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6456 ADISPLAY_ID_DEFAULT))
6457 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6458 spy2->consumeMotionMove();
6459 spy1->assertNoEvents();
6460 window->assertNoEvents();
6461}
6462
6463/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006464 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6465 * in the middle of the gesture.
6466 */
6467TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6468 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006469 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006470 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6471
6472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6473 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6474 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6475 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6476 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6477
6478 window->releaseChannel();
6479
6480 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6481
6482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6483 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6484 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6485 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6486}
6487
6488/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006489 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6490 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006491 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006492TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006493 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006494 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006495
6496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6497
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006498 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6500 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6501 {100, 200}))
6502 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006503 spy->consumeMotionDown();
6504 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006505
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006506 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006507 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006508 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006509
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006510 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006511 const MotionEvent secondFingerDownEvent =
6512 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6513 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6514 AINPUT_SOURCE_TOUCHSCREEN)
6515 .displayId(ADISPLAY_ID_DEFAULT)
6516 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6517 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6518 .x(100)
6519 .y(200))
6520 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6521 .build();
6522 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6523 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6524 InputEventInjectionSync::WAIT_FOR_RESULT))
6525 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6526
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006527 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6528
6529 // Third finger goes down outside all windows, so injection should fail.
6530 const MotionEvent thirdFingerDownEvent =
6531 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6532 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6533 AINPUT_SOURCE_TOUCHSCREEN)
6534 .displayId(ADISPLAY_ID_DEFAULT)
6535 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6536 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6537 .x(100)
6538 .y(200))
6539 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6540 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6541 .build();
6542 ASSERT_EQ(InputEventInjectionResult::FAILED,
6543 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6544 InputEventInjectionSync::WAIT_FOR_RESULT))
6545 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6546
6547 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006548 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006549}
6550
6551/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006552 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6553 * pointers that are down within its bounds.
6554 */
6555TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6556 auto windowLeft = createForeground();
6557 windowLeft->setFrame({0, 0, 100, 200});
6558 auto windowRight = createForeground();
6559 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006560 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006561 spy->setFrame({0, 0, 200, 200});
6562 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6563
6564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6565 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6566 {50, 50}))
6567 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6568 windowLeft->consumeMotionDown();
6569 spy->consumeMotionDown();
6570
6571 const MotionEvent secondFingerDownEvent =
6572 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6573 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6574 AINPUT_SOURCE_TOUCHSCREEN)
6575 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6576 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6577 .pointer(
6578 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6579 .build();
6580 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6581 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6582 InputEventInjectionSync::WAIT_FOR_RESULT))
6583 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6584 windowRight->consumeMotionDown();
6585 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6586}
6587
6588/**
6589 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6590 * the spy should receive the second pointer with ACTION_DOWN.
6591 */
6592TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6593 auto window = createForeground();
6594 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006595 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006596 spyRight->setFrame({100, 0, 200, 200});
6597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6598
6599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6600 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6601 {50, 50}))
6602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6603 window->consumeMotionDown();
6604 spyRight->assertNoEvents();
6605
6606 const MotionEvent secondFingerDownEvent =
6607 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6608 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6609 AINPUT_SOURCE_TOUCHSCREEN)
6610 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6611 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6612 .pointer(
6613 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6614 .build();
6615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6616 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6617 InputEventInjectionSync::WAIT_FOR_RESULT))
6618 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6619 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6620 spyRight->consumeMotionDown();
6621}
6622
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006623/**
6624 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6625 * windows should be allowed to control split touch.
6626 */
6627TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006628 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006629 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006630 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006631 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006632
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006633 auto window = createForeground();
6634 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006635
6636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6637
6638 // First finger down, no window touched.
6639 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6640 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6641 {100, 200}))
6642 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6643 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6644 window->assertNoEvents();
6645
6646 // Second finger down on window, the window should receive touch down.
6647 const MotionEvent secondFingerDownEvent =
6648 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6649 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6650 AINPUT_SOURCE_TOUCHSCREEN)
6651 .displayId(ADISPLAY_ID_DEFAULT)
6652 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6653 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6654 .x(100)
6655 .y(200))
6656 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6657 .build();
6658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6659 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6660 InputEventInjectionSync::WAIT_FOR_RESULT))
6661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6662
6663 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6664 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6665}
6666
6667/**
6668 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6669 * do not receive key events.
6670 */
6671TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006672 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006673 spy->setFocusable(false);
6674
6675 auto window = createForeground();
6676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6677 setFocusedWindow(window);
6678 window->consumeFocusEvent(true);
6679
6680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6681 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6682 window->consumeKeyDown(ADISPLAY_ID_NONE);
6683
6684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6685 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6686 window->consumeKeyUp(ADISPLAY_ID_NONE);
6687
6688 spy->assertNoEvents();
6689}
6690
Prabir Pradhand65552b2021-10-07 11:23:50 -07006691class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6692public:
6693 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6694 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6695 std::make_shared<FakeApplicationHandle>();
6696 sp<FakeWindowHandle> overlay =
6697 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6698 ADISPLAY_ID_DEFAULT);
6699 overlay->setFocusable(false);
6700 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006701 overlay->setTouchable(false);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006702 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6703 overlay->setTrustedOverlay(true);
6704
6705 std::shared_ptr<FakeApplicationHandle> application =
6706 std::make_shared<FakeApplicationHandle>();
6707 sp<FakeWindowHandle> window =
6708 new FakeWindowHandle(application, mDispatcher, "Application window",
6709 ADISPLAY_ID_DEFAULT);
6710 window->setFocusable(true);
6711 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006712
6713 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6715 setFocusedWindow(window);
6716 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6717 return {std::move(overlay), std::move(window)};
6718 }
6719
6720 void sendFingerEvent(int32_t action) {
6721 NotifyMotionArgs motionArgs =
6722 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6723 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6724 mDispatcher->notifyMotion(&motionArgs);
6725 }
6726
6727 void sendStylusEvent(int32_t action) {
6728 NotifyMotionArgs motionArgs =
6729 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6730 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6731 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6732 mDispatcher->notifyMotion(&motionArgs);
6733 }
6734};
6735
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006736using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6737
6738TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6739 ScopedSilentDeath _silentDeath;
6740
Prabir Pradhand65552b2021-10-07 11:23:50 -07006741 auto [overlay, window] = setupStylusOverlayScenario();
6742 overlay->setTrustedOverlay(false);
6743 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6744 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6745 ".* not a trusted overlay");
6746}
6747
6748TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6749 auto [overlay, window] = setupStylusOverlayScenario();
6750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6751
6752 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6753 overlay->consumeMotionDown();
6754 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6755 overlay->consumeMotionUp();
6756
6757 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6758 window->consumeMotionDown();
6759 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6760 window->consumeMotionUp();
6761
6762 overlay->assertNoEvents();
6763 window->assertNoEvents();
6764}
6765
6766TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6767 auto [overlay, window] = setupStylusOverlayScenario();
6768 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6770
6771 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6772 overlay->consumeMotionDown();
6773 window->consumeMotionDown();
6774 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6775 overlay->consumeMotionUp();
6776 window->consumeMotionUp();
6777
6778 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6779 window->consumeMotionDown();
6780 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6781 window->consumeMotionUp();
6782
6783 overlay->assertNoEvents();
6784 window->assertNoEvents();
6785}
6786
Garfield Tane84e6f92019-08-29 17:28:41 -07006787} // namespace android::inputdispatcher